text
stringlengths 54
60.6k
|
|---|
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkPProbeFilter.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkPProbeFilter.h"
#include "vtkCompositeDataPipeline.h"
#include "vtkCharArray.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkMultiProcessController.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkCellData.h"
#include "vtkPolyData.h"
#include "vtkStreamingDemandDrivenPipeline.h"
vtkCxxRevisionMacro(vtkPProbeFilter, "1.22");
vtkStandardNewMacro(vtkPProbeFilter);
vtkCxxSetObjectMacro(vtkPProbeFilter, Controller, vtkMultiProcessController);
//----------------------------------------------------------------------------
vtkPProbeFilter::vtkPProbeFilter()
{
this->Controller = 0;
this->SetController(vtkMultiProcessController::GetGlobalController());
}
//----------------------------------------------------------------------------
vtkPProbeFilter::~vtkPProbeFilter()
{
this->SetController(0);
}
//----------------------------------------------------------------------------
int vtkPProbeFilter::RequestInformation(vtkInformation *request,
vtkInformationVector **inputVector,
vtkInformationVector *outputVector)
{
this->Superclass::RequestInformation(request, inputVector, outputVector);
vtkInformation *outInfo = outputVector->GetInformationObject(0);
outInfo->Set(vtkStreamingDemandDrivenPipeline::MAXIMUM_NUMBER_OF_PIECES(),
-1);
return 1;
}
//----------------------------------------------------------------------------
int vtkPProbeFilter::RequestData(vtkInformation *request,
vtkInformationVector **inputVector,
vtkInformationVector *outputVector)
{
if (!this->Superclass::RequestData(request, inputVector, outputVector))
{
return 0;
}
vtkInformation *outInfo = outputVector->GetInformationObject(0);
vtkDataSet *output = vtkDataSet::SafeDownCast(
outInfo->Get(vtkDataObject::DATA_OBJECT()));
int procid = 0;
int numProcs = 1;
if ( this->Controller )
{
procid = this->Controller->GetLocalProcessId();
numProcs = this->Controller->GetNumberOfProcesses();
}
vtkIdType numPoints = this->NumberOfValidPoints;
if ( procid )
{
// Satellite node
this->Controller->Send(&numPoints, 1, 0, PROBE_COMMUNICATION_TAG);
if ( numPoints > 0 )
{
this->Controller->Send(output, 0, PROBE_COMMUNICATION_TAG);
}
output->ReleaseData();
}
else if ( numProcs > 1 )
{
vtkIdType numRemoteValidPoints = 0;
vtkDataSet *remoteProbeOutput = output->NewInstance();
vtkPointData *remotePointData;
vtkPointData *pointData = output->GetPointData();
vtkIdType i;
vtkIdType k;
vtkIdType pointId;
for (i = 1; i < numProcs; i++)
{
this->Controller->Receive(&numRemoteValidPoints, 1, i, PROBE_COMMUNICATION_TAG);
if (numRemoteValidPoints > 0)
{
this->Controller->Receive(remoteProbeOutput, i, PROBE_COMMUNICATION_TAG);
remotePointData = remoteProbeOutput->GetPointData();
vtkCharArray* maskArray = vtkCharArray::SafeDownCast(
remotePointData->GetArray(this->ValidPointMaskArrayName));
// Iterate over all point data in the output gathered from the remove
// and copy array values from all the pointIds which have the mask array
// bit set to 1.
vtkIdType numRemotePoints = remoteProbeOutput->GetNumberOfPoints();
for (pointId=0; (pointId < numRemotePoints) && maskArray; pointId++)
{
if (maskArray->GetValue(pointId) == 1)
{
for (k = 0; k < pointData->GetNumberOfArrays(); k++)
{
vtkAbstractArray *oaa = pointData->GetArray(k);
vtkAbstractArray *raa = remotePointData->GetArray(oaa->GetName());
if (raa != NULL)
{
oaa->SetTuple(pointId, pointId, raa);
}
}
}
}
}
}
remoteProbeOutput->Delete();
}
return 1;
}
//----------------------------------------------------------------------------
int vtkPProbeFilter::RequestUpdateExtent(vtkInformation *,
vtkInformationVector **inputVector,
vtkInformationVector *outputVector)
{
vtkInformation *inInfo = inputVector[0]->GetInformationObject(0);
vtkInformation *sourceInfo = inputVector[1]->GetInformationObject(0);
vtkInformation *outInfo = outputVector->GetInformationObject(0);
inInfo->Set(vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER(), 0);
inInfo->Set(vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_PIECES(), 1);
inInfo->Set(vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_GHOST_LEVELS(),
0);
sourceInfo->Set(
vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER(),
outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER()));
sourceInfo->Set(
vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_PIECES(),
outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_PIECES()));
sourceInfo->Set(
vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_GHOST_LEVELS(),
outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_GHOST_LEVELS()));
return 1;
}
//----------------------------------------------------------------------------
int vtkPProbeFilter::FillInputPortInformation(int port, vtkInformation *info)
{
if (!this->Superclass::FillInputPortInformation(port, info))
{
return 0;
}
if (port == 1)
{
info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkDataObject");
}
return 1;
}
//----------------------------------------------------------------------------
void vtkPProbeFilter::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "Controller " << this->Controller << endl;
}
<commit_msg>BUG: Fixed bug in the parallel probe filter.<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkPProbeFilter.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkPProbeFilter.h"
#include "vtkCompositeDataPipeline.h"
#include "vtkCharArray.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkMultiProcessController.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkCellData.h"
#include "vtkOnePieceExtentTranslator.h"
#include "vtkPolyData.h"
#include "vtkStreamingDemandDrivenPipeline.h"
vtkCxxRevisionMacro(vtkPProbeFilter, "1.22.12.1");
vtkStandardNewMacro(vtkPProbeFilter);
vtkCxxSetObjectMacro(vtkPProbeFilter, Controller, vtkMultiProcessController);
//----------------------------------------------------------------------------
vtkPProbeFilter::vtkPProbeFilter()
{
this->Controller = 0;
this->SetController(vtkMultiProcessController::GetGlobalController());
}
//----------------------------------------------------------------------------
vtkPProbeFilter::~vtkPProbeFilter()
{
this->SetController(0);
}
//----------------------------------------------------------------------------
int vtkPProbeFilter::RequestInformation(vtkInformation *request,
vtkInformationVector **inputVector,
vtkInformationVector *outputVector)
{
this->Superclass::RequestInformation(request, inputVector, outputVector);
vtkInformation *outInfo = outputVector->GetInformationObject(0);
outInfo->Set(vtkStreamingDemandDrivenPipeline::MAXIMUM_NUMBER_OF_PIECES(),
-1);
// Setup ExtentTranslator so that all downstream piece requests are
// converted to whole extent update requests, as need by this filter.
vtkStreamingDemandDrivenPipeline* sddp =
vtkStreamingDemandDrivenPipeline::SafeDownCast(this->GetExecutive());
if (strcmp(
sddp->GetExtentTranslator(outInfo)->GetClassName(),
"vtkOnePieceExtentTranslator") != 0)
{
vtkExtentTranslator* et = vtkOnePieceExtentTranslator::New();
sddp->SetExtentTranslator(outInfo, et);
et->Delete();
}
return 1;
}
//----------------------------------------------------------------------------
int vtkPProbeFilter::RequestData(vtkInformation *request,
vtkInformationVector **inputVector,
vtkInformationVector *outputVector)
{
if (!this->Superclass::RequestData(request, inputVector, outputVector))
{
return 0;
}
vtkInformation *outInfo = outputVector->GetInformationObject(0);
vtkDataSet *output = vtkDataSet::SafeDownCast(
outInfo->Get(vtkDataObject::DATA_OBJECT()));
int procid = 0;
int numProcs = 1;
if ( this->Controller )
{
procid = this->Controller->GetLocalProcessId();
numProcs = this->Controller->GetNumberOfProcesses();
}
vtkIdType numPoints = this->NumberOfValidPoints;
if ( procid )
{
// Satellite node
this->Controller->Send(&numPoints, 1, 0, PROBE_COMMUNICATION_TAG);
if ( numPoints > 0 )
{
this->Controller->Send(output, 0, PROBE_COMMUNICATION_TAG);
}
output->ReleaseData();
}
else if ( numProcs > 1 )
{
vtkIdType numRemoteValidPoints = 0;
vtkDataSet *remoteProbeOutput = output->NewInstance();
vtkPointData *remotePointData;
vtkPointData *pointData = output->GetPointData();
vtkIdType i;
vtkIdType k;
vtkIdType pointId;
for (i = 1; i < numProcs; i++)
{
this->Controller->Receive(&numRemoteValidPoints, 1, i, PROBE_COMMUNICATION_TAG);
if (numRemoteValidPoints > 0)
{
this->Controller->Receive(remoteProbeOutput, i, PROBE_COMMUNICATION_TAG);
remotePointData = remoteProbeOutput->GetPointData();
vtkCharArray* maskArray = vtkCharArray::SafeDownCast(
remotePointData->GetArray(this->ValidPointMaskArrayName));
// Iterate over all point data in the output gathered from the remove
// and copy array values from all the pointIds which have the mask array
// bit set to 1.
vtkIdType numRemotePoints = remoteProbeOutput->GetNumberOfPoints();
for (pointId=0; (pointId < numRemotePoints) && maskArray; pointId++)
{
if (maskArray->GetValue(pointId) == 1)
{
for (k = 0; k < pointData->GetNumberOfArrays(); k++)
{
vtkAbstractArray *oaa = pointData->GetArray(k);
vtkAbstractArray *raa = remotePointData->GetArray(oaa->GetName());
if (raa != NULL)
{
oaa->SetTuple(pointId, pointId, raa);
}
}
}
}
}
}
remoteProbeOutput->Delete();
}
return 1;
}
#include "vtkInformationIntegerVectorKey.h"
//----------------------------------------------------------------------------
int vtkPProbeFilter::RequestUpdateExtent(vtkInformation *,
vtkInformationVector **inputVector,
vtkInformationVector *outputVector)
{
vtkInformation *inInfo = inputVector[0]->GetInformationObject(0);
vtkInformation *sourceInfo = inputVector[1]->GetInformationObject(0);
vtkInformation *outInfo = outputVector->GetInformationObject(0);
vtkStreamingDemandDrivenPipeline* sddp =
vtkStreamingDemandDrivenPipeline::SafeDownCast(this->GetExecutive());
if (sddp)
{
sddp->SetUpdateExtentToWholeExtent(inInfo);
}
//inInfo->Set(vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER(), 0);
//inInfo->Set(vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_PIECES(), 1);
//inInfo->Set(vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_GHOST_LEVELS(),
// 0);
sourceInfo->Set(
vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER(),
outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER()));
sourceInfo->Set(
vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_PIECES(),
outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_PIECES()));
sourceInfo->Set(
vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_GHOST_LEVELS(),
outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_GHOST_LEVELS()));
return 1;
}
//----------------------------------------------------------------------------
int vtkPProbeFilter::FillInputPortInformation(int port, vtkInformation *info)
{
if (!this->Superclass::FillInputPortInformation(port, info))
{
return 0;
}
if (port == 1)
{
info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkDataObject");
}
return 1;
}
//----------------------------------------------------------------------------
void vtkPProbeFilter::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "Controller " << this->Controller << endl;
}
<|endoftext|>
|
<commit_before>#ifndef _KUKA_FRI_
#define _KUKA_FRI_
#include <chrono>
#include <stdexcept>
#include <boost/units/physical_dimensions/torque.hpp>
#include <boost/units/physical_dimensions/plane_angle.hpp>
#include <boost/units/physical_dimensions/torque.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/asio.hpp>
// Kuka include files
#include "friClientIf.h"
#include "friClientData.h"
namespace KUKA {
namespace LBRState {
const int NUM_DOF = 7;
const int LBRMONITORMESSAGEID = 0x245142;
}
namespace LBRCommand {
// Following from Kuka friLBRCommand.cpp
const int LBRCOMMANDMESSAGEID = 0x34001;
}
}
namespace robone { namespace robot {
struct state_tag{}; /// @todo consider moving to separate tag header
struct command_tag{};
struct external_state_tag{}; /// @todo consider eliding external and internal sensor tag
struct interpolated_state_tag{};
namespace arm {
namespace kuka {
// Following from Kuka example program
const int default_port_id = 30200;
namespace detail {
template<typename OutputIterator>
void copyJointState(tRepeatedDoubleArguments* values,OutputIterator it){
std::copy(static_cast<double*>(values->value),static_cast<double*>(values->value)+KUKA::LBRState::NUM_DOF,it);
}
}
}
/// copy measured joint angle to output iterator
template<typename OutputIterator>
void copy(const FRIMonitoringMessage& monitoringMsg, OutputIterator it, boost::units::plane_angle_base_dimension, robone::robot::state_tag){
if (monitoringMsg.monitorData.has_measuredJointPosition) {
kuka::detail::copyJointState(static_cast<tRepeatedDoubleArguments*>(monitoringMsg.monitorData.measuredJointPosition.value.arg),it);
}
}
/// copy commanded joint angle to output iterator
template<typename OutputIterator>
void copy(const FRIMonitoringMessage& monitoringMsg, OutputIterator it, boost::units::plane_angle_base_dimension, robone::robot::command_tag){
if (monitoringMsg.monitorData.has_commandedJointPosition) {
kuka::detail::copyJointState(static_cast<tRepeatedDoubleArguments*>(monitoringMsg.monitorData.commandedJointPosition.value.arg),it);
}
}
/// copy measured joint torque to output iterator
template<typename OutputIterator>
void copy(const FRIMonitoringMessage& monitoringMsg, OutputIterator it, boost::units::torque_dimension, robone::robot::state_tag){
if (monitoringMsg.monitorData.has_measuredTorque) {
kuka::detail::copyJointState(static_cast<tRepeatedDoubleArguments*>(monitoringMsg.monitorData.measuredTorque.value.arg),it);
}
}
/// copy measured external joint torque to output iterator
template<typename OutputIterator>
void copy(const FRIMonitoringMessage& monitoringMsg, OutputIterator it, boost::units::torque_dimension, external_state_tag){
if (monitoringMsg.monitorData.has_externalTorque) {
kuka::detail::copyJointState(static_cast<tRepeatedDoubleArguments*>(monitoringMsg.monitorData.externalTorque.value.arg),it);
}
}
/// copy commanded joint torque to output iterator
template<typename OutputIterator>
void copy(const FRIMonitoringMessage& monitoringMsg, OutputIterator it, boost::units::torque_dimension, command_tag){
if (monitoringMsg.monitorData.has_commandedTorque) {
kuka::detail::copyJointState(static_cast<tRepeatedDoubleArguments*>(monitoringMsg.monitorData.commandedTorque.value.arg),it);
}
}
/// copy interpolated commanded joint angles
template<typename OutputIterator>
void copy(const FRIMonitoringMessage& monitoringMsg, OutputIterator it,boost::units::plane_angle_base_dimension,interpolated_state_tag){
if (monitoringMsg.ipoData.has_jointPosition) {
kuka::detail::copyJointState(static_cast<tRepeatedDoubleArguments*>(monitoringMsg.ipoData.jointPosition.value.arg),it);
}
}
/// @todo consider changing these get* functions to get(data,type_tag());
KUKA::FRI::ESafetyState getSafetyState(const FRIMonitoringMessage& monitoringMsg) {
KUKA::FRI::ESafetyState KukaSafetyState = KUKA::FRI::ESafetyState::NORMAL_OPERATION;
if (monitoringMsg.has_robotInfo) {
if (monitoringMsg.robotInfo.has_safetyState)
KukaSafetyState = static_cast<KUKA::FRI::ESafetyState>(monitoringMsg.robotInfo.safetyState);
}
return KukaSafetyState;
}
/// @todo consider changing these get* functions to get(data,type_tag());
KUKA::FRI::EOperationMode getOperationMode(const FRIMonitoringMessage& monitoringMsg) {
KUKA::FRI::EOperationMode KukaSafetyState = KUKA::FRI::EOperationMode::TEST_MODE_1;
if (monitoringMsg.has_robotInfo) {
if (monitoringMsg.robotInfo.has_operationMode)
KukaSafetyState = static_cast<KUKA::FRI::EOperationMode>(monitoringMsg.robotInfo.operationMode);
}
return KukaSafetyState;
}
/// @todo consider changing these get* functions to get(data,type_tag());
/// @todo this one requires a callback... figure it out
KUKA::FRI::EDriveState getDriveState(const FRIMonitoringMessage& monitoringMsg) {
KUKA::FRI::EDriveState KukaSafetyState = KUKA::FRI::EDriveState::OFF;
if (monitoringMsg.has_robotInfo) {
// KukaSafetyState = static_cast<KUKA::FRI::EDriveState>(monitoringMsg.robotInfo.driveState);
}
return KukaSafetyState;
}
#if 0 // original getConnectionInfo
getConnectionInfo(const FRIMonitoringMessage& monitoringMsg){
if (monitoringMsg.has_connectionInfo) {
KukaSessionState = monitoringMsg.connectionInfo.sessionState;
KukaQuality = monitoringMsg.connectionInfo.quality;
if (monitoringMsg.connectionInfo.has_sendPeriod)
KukaSendPeriod = monitoringMsg.connectionInfo.sendPeriod;
if (monitoringMsg.connectionInfo.has_receiveMultiplier)
KukaReceiveMultiplier = monitoringMsg.connectionInfo.receiveMultiplier;
}
}
#endif
KUKA::FRI::ESessionState getSessionState(const FRIMonitoringMessage& monitoringMsg){
KUKA::FRI::ESessionState KukaSessionState = KUKA::FRI::ESessionState::IDLE;
if (monitoringMsg.has_connectionInfo) {
KukaSessionState = static_cast<KUKA::FRI::ESessionState>(monitoringMsg.connectionInfo.sessionState);
}
return KukaSessionState;
}
KUKA::FRI::EConnectionQuality getConnectionQuality(const FRIMonitoringMessage& monitoringMsg){
KUKA::FRI::EConnectionQuality KukaQuality = KUKA::FRI::EConnectionQuality::POOR;
if (monitoringMsg.has_connectionInfo) {
KukaQuality = static_cast<KUKA::FRI::EConnectionQuality>(monitoringMsg.connectionInfo.quality);
}
return KukaQuality;
}
uint32_t getSendPeriod(const FRIMonitoringMessage& monitoringMsg){
uint32_t KukaSendPeriod = 0;
if (monitoringMsg.has_connectionInfo) {
if (monitoringMsg.connectionInfo.has_sendPeriod)
KukaSendPeriod = monitoringMsg.connectionInfo.sendPeriod;
}
return KukaSendPeriod;
}
std::size_t getReceiveMultiplier(const FRIMonitoringMessage& monitoringMsg){
std::size_t KukaReceiveMultiplier = 0;
if (monitoringMsg.has_connectionInfo) {
if (monitoringMsg.connectionInfo.has_receiveMultiplier)
KukaReceiveMultiplier = monitoringMsg.connectionInfo.receiveMultiplier;
}
return KukaReceiveMultiplier;
}
std::chrono::time_point<std::chrono::high_resolution_clock> getTimeStamp(const FRIMonitoringMessage& monitoringMsg){
// defaults to the epoch
std::chrono::time_point<std::chrono::high_resolution_clock> timestamp;
if (monitoringMsg.monitorData.has_timestamp) {
timestamp += std::chrono::seconds(monitoringMsg.monitorData.timestamp.sec) +
std::chrono::nanoseconds(monitoringMsg.monitorData.timestamp.nanosec);
}
return timestamp;
}
/// @todo replace with something generic
struct KukaState {
typedef boost::array<double,KUKA::LBRState::NUM_DOF> joint_state;
joint_state position;
joint_state torque;
joint_state commandedPosition;
joint_state commandedTorque;
joint_state ipoJointPosition;
KUKA::FRI::ESessionState sessionState;
KUKA::FRI::EConnectionQuality connectionQuality;
KUKA::FRI::ESafetyState safetyState;
KUKA::FRI::EOperationMode operationMode;
KUKA::FRI::EDriveState driveState;
std::chrono::time_point<std::chrono::high_resolution_clock> timestamp;
};
// Decode message buffer (using nanopb decoder)
void decode(KUKA::FRI::ClientData& friData){
/// @todo FRI_MONITOR_MSG_MAX_SIZE may not be the right size... probably need the actual size received
if (!friData.decoder.decode(friData.receiveBuffer, KUKA::FRI::FRI_MONITOR_MSG_MAX_SIZE)) {
throw std::runtime_error( "Error decoding received data");
}
// check message type
if (friData.expectedMonitorMsgID != friData.monitoringMsg.header.messageIdentifier)
{
throw std::invalid_argument(std::string("KukaFRI.hpp: Problem reading buffer, id code: ") +
boost::lexical_cast<std::string>(static_cast<int>(friData.monitoringMsg.header.messageIdentifier)) +
std::string(" does not match expected id code: ") +
boost::lexical_cast<std::string>(static_cast<int>(friData.expectedMonitorMsgID)) + std::string("\n")
);
return;
}
}
/// encode data in the class into the send buffer
/// @todo update the statements in here to run on the actual data types available
void encode(KUKA::FRI::ClientData& friData,KukaState& state){
// Check whether to send a response
friData.lastSendCounter = 0;
// set sequence counters
friData.commandMsg.header.sequenceCounter = friData.sequenceCounter++;
friData.commandMsg.header.reflectedSequenceCounter = friData.monitoringMsg.header.sequenceCounter;
// copy current joint position to commanded position
friData.commandMsg.has_commandData = true;
friData.commandMsg.commandData.has_jointPosition = true;
tRepeatedDoubleArguments *dest = (tRepeatedDoubleArguments*)friData.commandMsg.commandData.jointPosition.value.arg;
if ((state.sessionState == KUKA::FRI::COMMANDING_WAIT) || (state.sessionState == KUKA::FRI::COMMANDING_ACTIVE))
std::copy(state.ipoJointPosition.begin(),state.ipoJointPosition.end(),dest->value); /// @todo is this the right thing to copy?
else
std::copy(state.commandedPosition.begin(),state.commandedPosition.end(),dest->value); /// @todo is this the right thing to copy?
int buffersize = KUKA::FRI::FRI_COMMAND_MSG_MAX_SIZE;
if (!friData.encoder.encode(friData.sendBuffer, buffersize))
return;
}
void copy(const FRIMonitoringMessage& monitoringMsg, KukaState& state ){
copy(monitoringMsg,state.position.begin(),boost::units::plane_angle_base_dimension(),robone::robot::state_tag());
copy(monitoringMsg,state.torque.begin(),boost::units::torque_dimension(),robone::robot::state_tag());
copy(monitoringMsg,state.commandedPosition.begin(),boost::units::plane_angle_base_dimension(),robone::robot::command_tag());
copy(monitoringMsg,state.commandedTorque.begin(),boost::units::torque_dimension(),robone::robot::command_tag());
copy(monitoringMsg,state.ipoJointPosition.begin(),boost::units::plane_angle_base_dimension(),robone::robot::interpolated_state_tag());
state.sessionState = getSessionState(monitoringMsg);
state.connectionQuality = getConnectionQuality(monitoringMsg);
state.safetyState = getSafetyState(monitoringMsg);
state.operationMode = getOperationMode(monitoringMsg);
/// @todo this one requires a callback... figure it out
//state.driveState = getDriveState(monitoringMsg);
/// @todo fill out missing state update steps
}
/// @todo implment async version of this, probably in a small class
/// @todo implement sending state
void update_state(boost::asio::ip::udp::socket& socket, KUKA::FRI::ClientData& friData, KukaState& state){
std::size_t buf_size = socket.receive(boost::asio::buffer(friData.receiveBuffer,KUKA::FRI::FRI_MONITOR_MSG_MAX_SIZE));
copy(friData.monitoringMsg,state);
friData.lastSendCounter++;
// Check whether to send a response
if (friData.lastSendCounter >= friData.monitoringMsg.connectionInfo.receiveMultiplier){
encode(friData,state);
socket.send(boost::asio::buffer(friData.sendBuffer,KUKA::FRI::FRI_MONITOR_MSG_MAX_SIZE));
}
}
}}} /// namespace robone::robot::arm
#endif
<commit_msg>#12 INTERMEDIATE CODE: correct buffer sizes now passed around<commit_after>#ifndef _KUKA_FRI_
#define _KUKA_FRI_
#include <chrono>
#include <stdexcept>
#include <boost/units/physical_dimensions/torque.hpp>
#include <boost/units/physical_dimensions/plane_angle.hpp>
#include <boost/units/physical_dimensions/torque.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/asio.hpp>
// Kuka include files
#include "friClientIf.h"
#include "friClientData.h"
namespace KUKA {
namespace LBRState {
const int NUM_DOF = 7;
const int LBRMONITORMESSAGEID = 0x245142;
}
namespace LBRCommand {
// Following from Kuka friLBRCommand.cpp
const int LBRCOMMANDMESSAGEID = 0x34001;
}
}
namespace robone { namespace robot {
struct state_tag{}; /// @todo consider moving to separate tag header
struct command_tag{};
struct external_state_tag{}; /// @todo consider eliding external and internal sensor tag
struct interpolated_state_tag{};
namespace arm {
namespace kuka {
// Following from Kuka example program
const int default_port_id = 30200;
namespace detail {
template<typename OutputIterator>
void copyJointState(tRepeatedDoubleArguments* values,OutputIterator it){
std::copy(static_cast<double*>(values->value),static_cast<double*>(values->value)+KUKA::LBRState::NUM_DOF,it);
}
}
}
/// copy measured joint angle to output iterator
template<typename OutputIterator>
void copy(const FRIMonitoringMessage& monitoringMsg, OutputIterator it, boost::units::plane_angle_base_dimension, robone::robot::state_tag){
if (monitoringMsg.monitorData.has_measuredJointPosition) {
kuka::detail::copyJointState(static_cast<tRepeatedDoubleArguments*>(monitoringMsg.monitorData.measuredJointPosition.value.arg),it);
}
}
/// copy commanded joint angle to output iterator
template<typename OutputIterator>
void copy(const FRIMonitoringMessage& monitoringMsg, OutputIterator it, boost::units::plane_angle_base_dimension, robone::robot::command_tag){
if (monitoringMsg.monitorData.has_commandedJointPosition) {
kuka::detail::copyJointState(static_cast<tRepeatedDoubleArguments*>(monitoringMsg.monitorData.commandedJointPosition.value.arg),it);
}
}
/// copy measured joint torque to output iterator
template<typename OutputIterator>
void copy(const FRIMonitoringMessage& monitoringMsg, OutputIterator it, boost::units::torque_dimension, robone::robot::state_tag){
if (monitoringMsg.monitorData.has_measuredTorque) {
kuka::detail::copyJointState(static_cast<tRepeatedDoubleArguments*>(monitoringMsg.monitorData.measuredTorque.value.arg),it);
}
}
/// copy measured external joint torque to output iterator
template<typename OutputIterator>
void copy(const FRIMonitoringMessage& monitoringMsg, OutputIterator it, boost::units::torque_dimension, external_state_tag){
if (monitoringMsg.monitorData.has_externalTorque) {
kuka::detail::copyJointState(static_cast<tRepeatedDoubleArguments*>(monitoringMsg.monitorData.externalTorque.value.arg),it);
}
}
/// copy commanded joint torque to output iterator
template<typename OutputIterator>
void copy(const FRIMonitoringMessage& monitoringMsg, OutputIterator it, boost::units::torque_dimension, command_tag){
if (monitoringMsg.monitorData.has_commandedTorque) {
kuka::detail::copyJointState(static_cast<tRepeatedDoubleArguments*>(monitoringMsg.monitorData.commandedTorque.value.arg),it);
}
}
/// copy interpolated commanded joint angles
template<typename OutputIterator>
void copy(const FRIMonitoringMessage& monitoringMsg, OutputIterator it,boost::units::plane_angle_base_dimension,interpolated_state_tag){
if (monitoringMsg.ipoData.has_jointPosition) {
kuka::detail::copyJointState(static_cast<tRepeatedDoubleArguments*>(monitoringMsg.ipoData.jointPosition.value.arg),it);
}
}
/// @todo consider changing these get* functions to get(data,type_tag());
KUKA::FRI::ESafetyState getSafetyState(const FRIMonitoringMessage& monitoringMsg) {
KUKA::FRI::ESafetyState KukaSafetyState = KUKA::FRI::ESafetyState::NORMAL_OPERATION;
if (monitoringMsg.has_robotInfo) {
if (monitoringMsg.robotInfo.has_safetyState)
KukaSafetyState = static_cast<KUKA::FRI::ESafetyState>(monitoringMsg.robotInfo.safetyState);
}
return KukaSafetyState;
}
/// @todo consider changing these get* functions to get(data,type_tag());
KUKA::FRI::EOperationMode getOperationMode(const FRIMonitoringMessage& monitoringMsg) {
KUKA::FRI::EOperationMode KukaSafetyState = KUKA::FRI::EOperationMode::TEST_MODE_1;
if (monitoringMsg.has_robotInfo) {
if (monitoringMsg.robotInfo.has_operationMode)
KukaSafetyState = static_cast<KUKA::FRI::EOperationMode>(monitoringMsg.robotInfo.operationMode);
}
return KukaSafetyState;
}
/// @todo consider changing these get* functions to get(data,type_tag());
/// @todo this one requires a callback... figure it out
KUKA::FRI::EDriveState getDriveState(const FRIMonitoringMessage& monitoringMsg) {
KUKA::FRI::EDriveState KukaSafetyState = KUKA::FRI::EDriveState::OFF;
if (monitoringMsg.has_robotInfo) {
// KukaSafetyState = static_cast<KUKA::FRI::EDriveState>(monitoringMsg.robotInfo.driveState);
}
return KukaSafetyState;
}
#if 0 // original getConnectionInfo
getConnectionInfo(const FRIMonitoringMessage& monitoringMsg){
if (monitoringMsg.has_connectionInfo) {
KukaSessionState = monitoringMsg.connectionInfo.sessionState;
KukaQuality = monitoringMsg.connectionInfo.quality;
if (monitoringMsg.connectionInfo.has_sendPeriod)
KukaSendPeriod = monitoringMsg.connectionInfo.sendPeriod;
if (monitoringMsg.connectionInfo.has_receiveMultiplier)
KukaReceiveMultiplier = monitoringMsg.connectionInfo.receiveMultiplier;
}
}
#endif
KUKA::FRI::ESessionState getSessionState(const FRIMonitoringMessage& monitoringMsg){
KUKA::FRI::ESessionState KukaSessionState = KUKA::FRI::ESessionState::IDLE;
if (monitoringMsg.has_connectionInfo) {
KukaSessionState = static_cast<KUKA::FRI::ESessionState>(monitoringMsg.connectionInfo.sessionState);
}
return KukaSessionState;
}
KUKA::FRI::EConnectionQuality getConnectionQuality(const FRIMonitoringMessage& monitoringMsg){
KUKA::FRI::EConnectionQuality KukaQuality = KUKA::FRI::EConnectionQuality::POOR;
if (monitoringMsg.has_connectionInfo) {
KukaQuality = static_cast<KUKA::FRI::EConnectionQuality>(monitoringMsg.connectionInfo.quality);
}
return KukaQuality;
}
uint32_t getSendPeriod(const FRIMonitoringMessage& monitoringMsg){
uint32_t KukaSendPeriod = 0;
if (monitoringMsg.has_connectionInfo) {
if (monitoringMsg.connectionInfo.has_sendPeriod)
KukaSendPeriod = monitoringMsg.connectionInfo.sendPeriod;
}
return KukaSendPeriod;
}
std::size_t getReceiveMultiplier(const FRIMonitoringMessage& monitoringMsg){
std::size_t KukaReceiveMultiplier = 0;
if (monitoringMsg.has_connectionInfo) {
if (monitoringMsg.connectionInfo.has_receiveMultiplier)
KukaReceiveMultiplier = monitoringMsg.connectionInfo.receiveMultiplier;
}
return KukaReceiveMultiplier;
}
std::chrono::time_point<std::chrono::high_resolution_clock> getTimeStamp(const FRIMonitoringMessage& monitoringMsg){
// defaults to the epoch
std::chrono::time_point<std::chrono::high_resolution_clock> timestamp;
if (monitoringMsg.monitorData.has_timestamp) {
timestamp += std::chrono::seconds(monitoringMsg.monitorData.timestamp.sec) +
std::chrono::nanoseconds(monitoringMsg.monitorData.timestamp.nanosec);
}
return timestamp;
}
/// @todo replace with something generic
struct KukaState {
typedef boost::array<double,KUKA::LBRState::NUM_DOF> joint_state;
joint_state position;
joint_state torque;
joint_state commandedPosition;
joint_state commandedTorque;
joint_state ipoJointPosition;
KUKA::FRI::ESessionState sessionState;
KUKA::FRI::EConnectionQuality connectionQuality;
KUKA::FRI::ESafetyState safetyState;
KUKA::FRI::EOperationMode operationMode;
KUKA::FRI::EDriveState driveState;
std::chrono::time_point<std::chrono::high_resolution_clock> timestamp;
};
// Decode message buffer (using nanopb decoder)
void decode(KUKA::FRI::ClientData& friData, std::size_t msg_size){
/// @todo FRI_MONITOR_MSG_MAX_SIZE may not be the right size... probably need the actual size received
if (!friData.decoder.decode(friData.receiveBuffer, msg_size)) {
throw std::runtime_error( "Error decoding received data");
}
// check message type
if (friData.expectedMonitorMsgID != friData.monitoringMsg.header.messageIdentifier)
{
throw std::invalid_argument(std::string("KukaFRI.hpp: Problem reading buffer, id code: ") +
boost::lexical_cast<std::string>(static_cast<int>(friData.monitoringMsg.header.messageIdentifier)) +
std::string(" does not match expected id code: ") +
boost::lexical_cast<std::string>(static_cast<int>(friData.expectedMonitorMsgID)) + std::string("\n")
);
return;
}
}
/// encode data in the class into the send buffer
/// @todo update the statements in here to run on the actual data types available
std::size_t encode(KUKA::FRI::ClientData& friData,KukaState& state){
// Check whether to send a response
friData.lastSendCounter = 0;
// set sequence counters
friData.commandMsg.header.sequenceCounter = friData.sequenceCounter++;
friData.commandMsg.header.reflectedSequenceCounter = friData.monitoringMsg.header.sequenceCounter;
// copy current joint position to commanded position
friData.commandMsg.has_commandData = true;
friData.commandMsg.commandData.has_jointPosition = true;
tRepeatedDoubleArguments *dest = (tRepeatedDoubleArguments*)friData.commandMsg.commandData.jointPosition.value.arg;
if ((state.sessionState == KUKA::FRI::COMMANDING_WAIT) || (state.sessionState == KUKA::FRI::COMMANDING_ACTIVE))
std::copy(state.ipoJointPosition.begin(),state.ipoJointPosition.end(),dest->value); /// @todo is this the right thing to copy?
else
std::copy(state.commandedPosition.begin(),state.commandedPosition.end(),dest->value); /// @todo is this the right thing to copy?
int buffersize = KUKA::FRI::FRI_COMMAND_MSG_MAX_SIZE;
if (!friData.encoder.encode(friData.sendBuffer, buffersize))
return 0;
return buffersize;
}
void copy(const FRIMonitoringMessage& monitoringMsg, KukaState& state ){
copy(monitoringMsg,state.position.begin(),boost::units::plane_angle_base_dimension(),robone::robot::state_tag());
copy(monitoringMsg,state.torque.begin(),boost::units::torque_dimension(),robone::robot::state_tag());
copy(monitoringMsg,state.commandedPosition.begin(),boost::units::plane_angle_base_dimension(),robone::robot::command_tag());
copy(monitoringMsg,state.commandedTorque.begin(),boost::units::torque_dimension(),robone::robot::command_tag());
copy(monitoringMsg,state.ipoJointPosition.begin(),boost::units::plane_angle_base_dimension(),robone::robot::interpolated_state_tag());
state.sessionState = getSessionState(monitoringMsg);
state.connectionQuality = getConnectionQuality(monitoringMsg);
state.safetyState = getSafetyState(monitoringMsg);
state.operationMode = getOperationMode(monitoringMsg);
/// @todo this one requires a callback... figure it out
//state.driveState = getDriveState(monitoringMsg);
/// @todo fill out missing state update steps
}
/// @todo implment async version of this, probably in a small class
/// @todo implement sending state
void update_state(boost::asio::ip::udp::socket& socket, KUKA::FRI::ClientData& friData, KukaState& state){
std::size_t buf_size = socket.receive(boost::asio::buffer(friData.receiveBuffer,KUKA::FRI::FRI_MONITOR_MSG_MAX_SIZE));
decode(friData,buf_size);
copy(friData.monitoringMsg,state);
friData.lastSendCounter++;
// Check whether to send a response
if (friData.lastSendCounter >= friData.monitoringMsg.connectionInfo.receiveMultiplier){
buf_size = encode(friData,state);
socket.send(boost::asio::buffer(friData.sendBuffer,buf_size));
}
}
}}} /// namespace robone::robot::arm
#endif
<|endoftext|>
|
<commit_before>// Copyright (c) 2011, Christian Rorvik
// Distributed under the Simplified BSD License (See accompanying file LICENSE.txt)
#ifndef CRUNCH_CONCURRENCY_PLATFORM_WIN32_ATOMIC_OPS_X86_HPP
#define CRUNCH_CONCURRENCY_PLATFORM_WIN32_ATOMIC_OPS_X86_HPP
#include "crunch/base/assert.hpp"
#include "crunch/concurrency/fence.hpp"
#include "crunch/concurrency/memory_order.hpp"
#include <intrin.h>
namespace Crunch { namespace Concurrency { namespace Platform {
namespace Detail
{
inline char AtomicLoad(char volatile const& src) { return src; }
inline short AtomicLoad(short volatile const& src) { return src; }
inline long AtomicLoad(long volatile const& src) { return src; }
inline __int64 AtomicLoad(__int64 volatile const& src)
{
#if defined (CRUNCH_ARCH_X86_64)
return src;
#else
__int64 result;
__asm
{
mov eax, dword ptr [src]
fild qword ptr [eax]
fistp qword ptr [result]
}
return result;
#endif
}
inline __m128i AtomicLoad(__m128i volatile const& src)
{
return _mm_load_si128(const_cast<__m128i const*>(&src));;
}
inline void AtomicStore(char volatile& dst, char src) { dst = src; }
inline void AtomicStore(short volatile& dst, short src) { dst = src; }
inline void AtomicStore(long volatile& dst, long src) { dst = src; }
inline void AtomicStore(__int64 volatile& dst, __int64 src)
{
#if defined (CRUNCH_ARCH_X86_64)
dst = src;
#else
__asm
{
mov eax, dword ptr [dst]
fild qword ptr [src]
fistp qword ptr [eax]
}
#endif
};
inline void AtomicStore(__m128i volatile& dst, __m128i src)
{
_mm_store_si128(const_cast<__m128i*>(&dst), src);
}
inline void AtomicStoreSeqCst(char volatile& dst, char src)
{
CRUNCH_MEMORY_FENCE();
AtomicStore(dst, src);
CRUNCH_MEMORY_FENCE();
}
inline void AtomicStoreSeqCst(short volatile& dst, short src)
{
CRUNCH_MEMORY_FENCE();
AtomicStore(dst, src);
CRUNCH_MEMORY_FENCE();
}
inline void AtomicStoreSeqCst(long volatile& dst, long src)
{
_InterlockedExchange(&dst, src);
}
inline void AtomicStoreSeqCst(__int64 volatile& dst, __int64 src)
{
#if defined (CRUNCH_ARCH_X86_64)
_InterlockedExchange64(&dst, src);
#else
CRUNCH_MEMORY_FENCE();
AtomicStore(dst, src);
CRUNCH_MEMORY_FENCE();
#endif
}
inline void AtomicStoreSeqCst(__m128i volatile& dst, __m128i src)
{
CRUNCH_MEMORY_FENCE();
AtomicStore(dst, src);
CRUNCH_MEMORY_FENCE();
}
#if defined (CRUNCH_ARCH_X86_32)
template<typename Op>
inline __int64 FallbackAtomicOp(__int64 volatile& value, Op op)
{
__int64 oldValue = value;
for (;;)
{
__int64 const newValue = op(oldValue);
__int64 currentValue = _InterlockedCompareExchange64(&value, newValue, oldValue);
if (currentValue == oldValue)
return oldValue;
_mm_pause();
oldValue = currentValue;
}
}
#endif
}
template<typename T>
inline T AtomicLoad(T volatile& src, MemoryOrder ordering = MEMORY_ORDER_SEQ_CST)
{
CRUNCH_ASSERT_ALIGNMENT(&src, sizeof(T));
if (ordering == MEMORY_ORDER_SEQ_CST)
CRUNCH_COMPILER_FENCE();
T result = Detail::AtomicLoad(src);
if (ordering & MEMORY_ORDER_ACQUIRE)
CRUNCH_COMPILER_FENCE();
return result;
}
template<typename T>
inline void AtomicStore(T volatile& dst, T src, MemoryOrder ordering = MEMORY_ORDER_SEQ_CST)
{
CRUNCH_ASSERT_ALIGNMENT(&dst, sizeof(T));
if (ordering == MEMORY_ORDER_SEQ_CST)
{
Detail::AtomicStoreSeqCst(dst, src);
}
else
{
if (ordering & MEMORY_ORDER_RELEASE)
CRUNCH_COMPILER_FENCE();
Detail::AtomicStore(dst, src);
}
}
inline long AtomicSwap(long volatile& dst, long src, MemoryOrder = MEMORY_ORDER_SEQ_CST)
{
CRUNCH_ASSERT_ALIGNMENT(&dst, 4);
return _InterlockedExchange(&dst, src);
}
#if defined (CRUNCH_ARCH_X86_64)
inline __int64 AtomicSwap(__int64 volatile& dst, __int64 src, MemoryOrder = MEMORY_ORDER_SEQ_CST)
{
CRUNCH_ASSERT_ALIGNMENT(&dst, 8);
return _InterlockedExchange64(&dst, src);
}
#endif
inline bool AtomicCompareAndSwap(short volatile& dst, short src, short& cmp, MemoryOrder = MEMORY_ORDER_SEQ_CST)
{
CRUNCH_ASSERT_ALIGNMENT(&dst, 2);
short cmp_ = cmp;
cmp = _InterlockedCompareExchange16(&dst, src, cmp);
return cmp_ == cmp;
}
inline bool AtomicCompareAndSwap(long volatile& dst, long src, long& cmp, MemoryOrder = MEMORY_ORDER_SEQ_CST)
{
CRUNCH_ASSERT_ALIGNMENT(&dst, 4);
long cmp_ = cmp;
cmp = _InterlockedCompareExchange(&dst, src, cmp);
return cmp_ == cmp;
}
inline bool AtomicCompareAndSwap(__int64 volatile& dst, __int64 src, __int64& cmp, MemoryOrder = MEMORY_ORDER_SEQ_CST)
{
CRUNCH_ASSERT_ALIGNMENT(&dst, 8);
__int64 cmp_ = cmp;
cmp = _InterlockedCompareExchange64(&dst, src, cmp);
return cmp_ == cmp;
}
#if defined (CRUNCH_ARCH_X86_64)
inline bool AtomicCompareAndSwap(__m128i volatile& dst, __m128i src, __m128i& cmp, MemoryOrder = MEMORY_ORDER_SEQ_CST)
{
CRUNCH_ASSERT_ALIGNMENT(&dst, 16);
return _InterlockedCompareExchange128(
dst.m128i_i64,
src.m128i_i64[1],
src.m128i_i64[0],
cmp.m128i_i64) != 0;
}
#endif
inline short AtomicIncrement(short volatile& addend, MemoryOrder = MEMORY_ORDER_SEQ_CST)
{
CRUNCH_ASSERT_ALIGNMENT(&addend, 2);
return _InterlockedIncrement16(&addend) - 1;
}
inline long AtomicIncrement(long volatile& addend, MemoryOrder = MEMORY_ORDER_SEQ_CST)
{
CRUNCH_ASSERT_ALIGNMENT(&addend, 4);
return _InterlockedIncrement(&addend) - 1;
}
inline __int64 AtomicIncrement(__int64 volatile& addend, MemoryOrder = MEMORY_ORDER_SEQ_CST)
{
CRUNCH_ASSERT_ALIGNMENT(&addend, 8);
#if defined (CRUNCH_ARCH_X86_64)
return _InterlockedIncrement64(&addend) - 1;
#else
return Detail::FallbackAtomicOp(addend, [] (__int64 x) { return x + 1; });
#endif
}
inline short AtomicDecrement(short volatile& addend, MemoryOrder = MEMORY_ORDER_SEQ_CST)
{
CRUNCH_ASSERT_ALIGNMENT(&addend, 2);
return _InterlockedDecrement16(&addend) + 1;
}
inline long AtomicDecrement(long volatile& addend, MemoryOrder = MEMORY_ORDER_SEQ_CST)
{
CRUNCH_ASSERT_ALIGNMENT(&addend, 4);
return _InterlockedDecrement(&addend) + 1;
}
inline __int64 AtomicDecrement(__int64 volatile& addend, MemoryOrder = MEMORY_ORDER_SEQ_CST)
{
CRUNCH_ASSERT_ALIGNMENT(&addend, 8);
#if defined (CRUNCH_ARCH_X86_64)
return _InterlockedDecrement64(&addend) + 1;
#else
return Detail::FallbackAtomicOp(addend, [] (__int64 x) { return x - 1; });
#endif
}
inline long AtomicAdd(long volatile& addend, long value, MemoryOrder = MEMORY_ORDER_SEQ_CST)
{
CRUNCH_ASSERT_ALIGNMENT(&addend, 4);
return _InterlockedExchangeAdd(&addend, value);
}
inline __int64 AtomicAdd(__int64 volatile& addend, __int64 value, MemoryOrder = MEMORY_ORDER_SEQ_CST)
{
CRUNCH_ASSERT_ALIGNMENT(&addend, 8);
#if defined (CRUNCH_ARCH_X86_64)
return _InterlockedExchangeAdd64(&addend, value);
#else
return Detail::FallbackAtomicOp(addend, [=] (__int64 x) { return x + value; });
#endif
}
inline long AtomicSub(long volatile& addend, long value, MemoryOrder = MEMORY_ORDER_SEQ_CST)
{
CRUNCH_ASSERT_ALIGNMENT(&addend, 4);
return _InterlockedExchangeAdd(&addend, -value);
}
inline __int64 AtomicSub(__int64 volatile& addend, __int64 value, MemoryOrder = MEMORY_ORDER_SEQ_CST)
{
CRUNCH_ASSERT_ALIGNMENT(&addend, 8);
#if defined (CRUNCH_ARCH_X86_64)
return _InterlockedExchangeAdd64(&addend, -value);
#else
return Detail::FallbackAtomicOp(addend, [=] (__int64 x) { return x - value; });
#endif
}
inline char AtomicAnd(char volatile& value, char mask, MemoryOrder = MEMORY_ORDER_SEQ_CST)
{
return _InterlockedAnd8(&value, mask);
}
inline short AtomicAnd(short volatile& value, short mask, MemoryOrder = MEMORY_ORDER_SEQ_CST)
{
CRUNCH_ASSERT_ALIGNMENT(&value, 2);
return _InterlockedAnd16(&value, mask);
}
inline long AtomicAnd(long volatile& value, long mask, MemoryOrder = MEMORY_ORDER_SEQ_CST)
{
CRUNCH_ASSERT_ALIGNMENT(&value, 4);
return _InterlockedAnd(&value, mask);
}
inline __int64 AtomicAnd(__int64 volatile& value, __int64 mask, MemoryOrder = MEMORY_ORDER_SEQ_CST)
{
CRUNCH_ASSERT_ALIGNMENT(&value, 8);
#if defined (CRUNCH_ARCH_X86_64)
return _InterlockedAnd64(&value, mask);
#else
return Detail::FallbackAtomicOp(value, [=] (__int64 x) { return x & mask; });
#endif
}
inline char AtomicOr(char volatile& value, char mask, MemoryOrder = MEMORY_ORDER_SEQ_CST)
{
return _InterlockedOr8(&value, mask);
}
inline short AtomicOr(short volatile& value, short mask, MemoryOrder = MEMORY_ORDER_SEQ_CST)
{
CRUNCH_ASSERT_ALIGNMENT(&value, 2);
return _InterlockedOr16(&value, mask);
}
inline long AtomicOr(long volatile& value, long mask, MemoryOrder = MEMORY_ORDER_SEQ_CST)
{
CRUNCH_ASSERT_ALIGNMENT(&value, 4);
return _InterlockedOr(&value, mask);
}
inline __int64 AtomicOr(__int64 volatile& value, __int64 mask, MemoryOrder = MEMORY_ORDER_SEQ_CST)
{
CRUNCH_ASSERT_ALIGNMENT(&value, 8);
#if defined (CRUNCH_ARCH_X86_64)
return _InterlockedOr64(&value, mask);
#else
return Detail::FallbackAtomicOp(value, [=] (__int64 x) { return x | mask; });
#endif
}
inline char AtomicXor(char volatile& value, char mask, MemoryOrder = MEMORY_ORDER_SEQ_CST)
{
return _InterlockedXor8(&value, mask);
}
inline short AtomicXor(short volatile& value, short mask, MemoryOrder = MEMORY_ORDER_SEQ_CST)
{
CRUNCH_ASSERT_ALIGNMENT(&value, 2);
return _InterlockedXor16(&value, mask);
}
inline long AtomicXor(long volatile& value, long mask, MemoryOrder = MEMORY_ORDER_SEQ_CST)
{
CRUNCH_ASSERT_ALIGNMENT(&value, 4);
return _InterlockedXor(&value, mask);
}
inline __int64 AtomicXor(__int64 volatile& value, __int64 mask, MemoryOrder = MEMORY_ORDER_SEQ_CST)
{
CRUNCH_ASSERT_ALIGNMENT(&value, 8);
#if defined (CRUNCH_ARCH_X86_64)
return _InterlockedXor64(&value, mask);
#else
return Detail::FallbackAtomicOp(value, [=] (__int64 x) { return x ^ mask; });
#endif
}
}}}
#endif
<commit_msg>crunch_concurrency - Added CAS fallback for Swap on x86<commit_after>// Copyright (c) 2011, Christian Rorvik
// Distributed under the Simplified BSD License (See accompanying file LICENSE.txt)
#ifndef CRUNCH_CONCURRENCY_PLATFORM_WIN32_ATOMIC_OPS_X86_HPP
#define CRUNCH_CONCURRENCY_PLATFORM_WIN32_ATOMIC_OPS_X86_HPP
#include "crunch/base/assert.hpp"
#include "crunch/concurrency/fence.hpp"
#include "crunch/concurrency/memory_order.hpp"
#include <intrin.h>
namespace Crunch { namespace Concurrency { namespace Platform {
namespace Detail
{
inline char AtomicLoad(char volatile const& src) { return src; }
inline short AtomicLoad(short volatile const& src) { return src; }
inline long AtomicLoad(long volatile const& src) { return src; }
inline __int64 AtomicLoad(__int64 volatile const& src)
{
#if defined (CRUNCH_ARCH_X86_64)
return src;
#else
__int64 result;
__asm
{
mov eax, dword ptr [src]
fild qword ptr [eax]
fistp qword ptr [result]
}
return result;
#endif
}
inline __m128i AtomicLoad(__m128i volatile const& src)
{
return _mm_load_si128(const_cast<__m128i const*>(&src));;
}
inline void AtomicStore(char volatile& dst, char src) { dst = src; }
inline void AtomicStore(short volatile& dst, short src) { dst = src; }
inline void AtomicStore(long volatile& dst, long src) { dst = src; }
inline void AtomicStore(__int64 volatile& dst, __int64 src)
{
#if defined (CRUNCH_ARCH_X86_64)
dst = src;
#else
__asm
{
mov eax, dword ptr [dst]
fild qword ptr [src]
fistp qword ptr [eax]
}
#endif
};
inline void AtomicStore(__m128i volatile& dst, __m128i src)
{
_mm_store_si128(const_cast<__m128i*>(&dst), src);
}
inline void AtomicStoreSeqCst(char volatile& dst, char src)
{
CRUNCH_MEMORY_FENCE();
AtomicStore(dst, src);
CRUNCH_MEMORY_FENCE();
}
inline void AtomicStoreSeqCst(short volatile& dst, short src)
{
CRUNCH_MEMORY_FENCE();
AtomicStore(dst, src);
CRUNCH_MEMORY_FENCE();
}
inline void AtomicStoreSeqCst(long volatile& dst, long src)
{
_InterlockedExchange(&dst, src);
}
inline void AtomicStoreSeqCst(__int64 volatile& dst, __int64 src)
{
#if defined (CRUNCH_ARCH_X86_64)
_InterlockedExchange64(&dst, src);
#else
CRUNCH_MEMORY_FENCE();
AtomicStore(dst, src);
CRUNCH_MEMORY_FENCE();
#endif
}
inline void AtomicStoreSeqCst(__m128i volatile& dst, __m128i src)
{
CRUNCH_MEMORY_FENCE();
AtomicStore(dst, src);
CRUNCH_MEMORY_FENCE();
}
#if defined (CRUNCH_ARCH_X86_32)
template<typename Op>
inline __int64 FallbackAtomicOp(__int64 volatile& value, Op op)
{
__int64 oldValue = value;
for (;;)
{
__int64 const newValue = op(oldValue);
__int64 currentValue = _InterlockedCompareExchange64(&value, newValue, oldValue);
if (currentValue == oldValue)
return oldValue;
_mm_pause();
oldValue = currentValue;
}
}
#endif
}
template<typename T>
inline T AtomicLoad(T volatile& src, MemoryOrder ordering = MEMORY_ORDER_SEQ_CST)
{
CRUNCH_ASSERT_ALIGNMENT(&src, sizeof(T));
if (ordering == MEMORY_ORDER_SEQ_CST)
CRUNCH_COMPILER_FENCE();
T result = Detail::AtomicLoad(src);
if (ordering & MEMORY_ORDER_ACQUIRE)
CRUNCH_COMPILER_FENCE();
return result;
}
template<typename T>
inline void AtomicStore(T volatile& dst, T src, MemoryOrder ordering = MEMORY_ORDER_SEQ_CST)
{
CRUNCH_ASSERT_ALIGNMENT(&dst, sizeof(T));
if (ordering == MEMORY_ORDER_SEQ_CST)
{
Detail::AtomicStoreSeqCst(dst, src);
}
else
{
if (ordering & MEMORY_ORDER_RELEASE)
CRUNCH_COMPILER_FENCE();
Detail::AtomicStore(dst, src);
}
}
inline long AtomicSwap(long volatile& dst, long src, MemoryOrder = MEMORY_ORDER_SEQ_CST)
{
CRUNCH_ASSERT_ALIGNMENT(&dst, 4);
return _InterlockedExchange(&dst, src);
}
inline __int64 AtomicSwap(__int64 volatile& dst, __int64 src, MemoryOrder = MEMORY_ORDER_SEQ_CST)
{
CRUNCH_ASSERT_ALIGNMENT(&dst, 8);
#if defined (CRUNCH_ARCH_X86_64)
return _InterlockedExchange64(&dst, src);
#else
return Detail::FallbackAtomicOp(dst, [=] (__int64) { return src; });
#endif
}
inline bool AtomicCompareAndSwap(short volatile& dst, short src, short& cmp, MemoryOrder = MEMORY_ORDER_SEQ_CST)
{
CRUNCH_ASSERT_ALIGNMENT(&dst, 2);
short cmp_ = cmp;
cmp = _InterlockedCompareExchange16(&dst, src, cmp);
return cmp_ == cmp;
}
inline bool AtomicCompareAndSwap(long volatile& dst, long src, long& cmp, MemoryOrder = MEMORY_ORDER_SEQ_CST)
{
CRUNCH_ASSERT_ALIGNMENT(&dst, 4);
long cmp_ = cmp;
cmp = _InterlockedCompareExchange(&dst, src, cmp);
return cmp_ == cmp;
}
inline bool AtomicCompareAndSwap(__int64 volatile& dst, __int64 src, __int64& cmp, MemoryOrder = MEMORY_ORDER_SEQ_CST)
{
CRUNCH_ASSERT_ALIGNMENT(&dst, 8);
__int64 cmp_ = cmp;
cmp = _InterlockedCompareExchange64(&dst, src, cmp);
return cmp_ == cmp;
}
#if defined (CRUNCH_ARCH_X86_64)
inline bool AtomicCompareAndSwap(__m128i volatile& dst, __m128i src, __m128i& cmp, MemoryOrder = MEMORY_ORDER_SEQ_CST)
{
CRUNCH_ASSERT_ALIGNMENT(&dst, 16);
return _InterlockedCompareExchange128(
dst.m128i_i64,
src.m128i_i64[1],
src.m128i_i64[0],
cmp.m128i_i64) != 0;
}
#endif
inline short AtomicIncrement(short volatile& addend, MemoryOrder = MEMORY_ORDER_SEQ_CST)
{
CRUNCH_ASSERT_ALIGNMENT(&addend, 2);
return _InterlockedIncrement16(&addend) - 1;
}
inline long AtomicIncrement(long volatile& addend, MemoryOrder = MEMORY_ORDER_SEQ_CST)
{
CRUNCH_ASSERT_ALIGNMENT(&addend, 4);
return _InterlockedIncrement(&addend) - 1;
}
inline __int64 AtomicIncrement(__int64 volatile& addend, MemoryOrder = MEMORY_ORDER_SEQ_CST)
{
CRUNCH_ASSERT_ALIGNMENT(&addend, 8);
#if defined (CRUNCH_ARCH_X86_64)
return _InterlockedIncrement64(&addend) - 1;
#else
return Detail::FallbackAtomicOp(addend, [] (__int64 x) { return x + 1; });
#endif
}
inline short AtomicDecrement(short volatile& addend, MemoryOrder = MEMORY_ORDER_SEQ_CST)
{
CRUNCH_ASSERT_ALIGNMENT(&addend, 2);
return _InterlockedDecrement16(&addend) + 1;
}
inline long AtomicDecrement(long volatile& addend, MemoryOrder = MEMORY_ORDER_SEQ_CST)
{
CRUNCH_ASSERT_ALIGNMENT(&addend, 4);
return _InterlockedDecrement(&addend) + 1;
}
inline __int64 AtomicDecrement(__int64 volatile& addend, MemoryOrder = MEMORY_ORDER_SEQ_CST)
{
CRUNCH_ASSERT_ALIGNMENT(&addend, 8);
#if defined (CRUNCH_ARCH_X86_64)
return _InterlockedDecrement64(&addend) + 1;
#else
return Detail::FallbackAtomicOp(addend, [] (__int64 x) { return x - 1; });
#endif
}
inline long AtomicAdd(long volatile& addend, long value, MemoryOrder = MEMORY_ORDER_SEQ_CST)
{
CRUNCH_ASSERT_ALIGNMENT(&addend, 4);
return _InterlockedExchangeAdd(&addend, value);
}
inline __int64 AtomicAdd(__int64 volatile& addend, __int64 value, MemoryOrder = MEMORY_ORDER_SEQ_CST)
{
CRUNCH_ASSERT_ALIGNMENT(&addend, 8);
#if defined (CRUNCH_ARCH_X86_64)
return _InterlockedExchangeAdd64(&addend, value);
#else
return Detail::FallbackAtomicOp(addend, [=] (__int64 x) { return x + value; });
#endif
}
inline long AtomicSub(long volatile& addend, long value, MemoryOrder = MEMORY_ORDER_SEQ_CST)
{
CRUNCH_ASSERT_ALIGNMENT(&addend, 4);
return _InterlockedExchangeAdd(&addend, -value);
}
inline __int64 AtomicSub(__int64 volatile& addend, __int64 value, MemoryOrder = MEMORY_ORDER_SEQ_CST)
{
CRUNCH_ASSERT_ALIGNMENT(&addend, 8);
#if defined (CRUNCH_ARCH_X86_64)
return _InterlockedExchangeAdd64(&addend, -value);
#else
return Detail::FallbackAtomicOp(addend, [=] (__int64 x) { return x - value; });
#endif
}
inline char AtomicAnd(char volatile& value, char mask, MemoryOrder = MEMORY_ORDER_SEQ_CST)
{
return _InterlockedAnd8(&value, mask);
}
inline short AtomicAnd(short volatile& value, short mask, MemoryOrder = MEMORY_ORDER_SEQ_CST)
{
CRUNCH_ASSERT_ALIGNMENT(&value, 2);
return _InterlockedAnd16(&value, mask);
}
inline long AtomicAnd(long volatile& value, long mask, MemoryOrder = MEMORY_ORDER_SEQ_CST)
{
CRUNCH_ASSERT_ALIGNMENT(&value, 4);
return _InterlockedAnd(&value, mask);
}
inline __int64 AtomicAnd(__int64 volatile& value, __int64 mask, MemoryOrder = MEMORY_ORDER_SEQ_CST)
{
CRUNCH_ASSERT_ALIGNMENT(&value, 8);
#if defined (CRUNCH_ARCH_X86_64)
return _InterlockedAnd64(&value, mask);
#else
return Detail::FallbackAtomicOp(value, [=] (__int64 x) { return x & mask; });
#endif
}
inline char AtomicOr(char volatile& value, char mask, MemoryOrder = MEMORY_ORDER_SEQ_CST)
{
return _InterlockedOr8(&value, mask);
}
inline short AtomicOr(short volatile& value, short mask, MemoryOrder = MEMORY_ORDER_SEQ_CST)
{
CRUNCH_ASSERT_ALIGNMENT(&value, 2);
return _InterlockedOr16(&value, mask);
}
inline long AtomicOr(long volatile& value, long mask, MemoryOrder = MEMORY_ORDER_SEQ_CST)
{
CRUNCH_ASSERT_ALIGNMENT(&value, 4);
return _InterlockedOr(&value, mask);
}
inline __int64 AtomicOr(__int64 volatile& value, __int64 mask, MemoryOrder = MEMORY_ORDER_SEQ_CST)
{
CRUNCH_ASSERT_ALIGNMENT(&value, 8);
#if defined (CRUNCH_ARCH_X86_64)
return _InterlockedOr64(&value, mask);
#else
return Detail::FallbackAtomicOp(value, [=] (__int64 x) { return x | mask; });
#endif
}
inline char AtomicXor(char volatile& value, char mask, MemoryOrder = MEMORY_ORDER_SEQ_CST)
{
return _InterlockedXor8(&value, mask);
}
inline short AtomicXor(short volatile& value, short mask, MemoryOrder = MEMORY_ORDER_SEQ_CST)
{
CRUNCH_ASSERT_ALIGNMENT(&value, 2);
return _InterlockedXor16(&value, mask);
}
inline long AtomicXor(long volatile& value, long mask, MemoryOrder = MEMORY_ORDER_SEQ_CST)
{
CRUNCH_ASSERT_ALIGNMENT(&value, 4);
return _InterlockedXor(&value, mask);
}
inline __int64 AtomicXor(__int64 volatile& value, __int64 mask, MemoryOrder = MEMORY_ORDER_SEQ_CST)
{
CRUNCH_ASSERT_ALIGNMENT(&value, 8);
#if defined (CRUNCH_ARCH_X86_64)
return _InterlockedXor64(&value, mask);
#else
return Detail::FallbackAtomicOp(value, [=] (__int64 x) { return x ^ mask; });
#endif
}
}}}
#endif
<|endoftext|>
|
<commit_before>/*
* ClutterMozHeadless; A headless Mozilla renderer
* Copyright (c) 2009, Intel Corporation.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU Lesser General Public License,
* version 2.1, as published by the Free Software Foundation.
*
* This program is distributed in the hope 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.
*
* Authored by Chris Lord <chris@linux.intel.com>
*/
#include <nsIGlobalHistory2.h>
#include <nsWeakReference.h>
#include <nsIGenericFactory.h>
#include <nsIIOService.h>
#include <nsIObserverService.h>
#include <nsIURI.h>
#include <nsNetUtil.h>
#include <nsStringGlue.h>
#include "clutter-mozheadless.h"
#include "clutter-mozheadless-history.h"
#include <moz-headless.h>
#include <mhs/mhs.h>
class HeadlessGlobalHistory : public nsIGlobalHistory2,
public nsSupportsWeakReference
{
public:
HeadlessGlobalHistory();
virtual ~HeadlessGlobalHistory();
static HeadlessGlobalHistory *GetSingleton(void);
static HeadlessGlobalHistory *sHeadlessGlobalHistory;
NS_DECL_ISUPPORTS
NS_DECL_NSIGLOBALHISTORY2
void SendLinkVisitedEvent (nsIURI *aURI);
private:
MhsHistory *mMhsHistory;
};
static void
_link_visited_cb (MhsHistory *history,
const gchar *uri,
HeadlessGlobalHistory *global_history)
{
nsresult rv;
nsCOMPtr<nsIIOService> io_service =
do_GetService (NS_IOSERVICE_CONTRACTID, &rv);
if (!NS_FAILED (rv))
{
nsDependentCString uri_cstring (uri);
nsCOMPtr<nsIURI> ns_uri;
rv = io_service->NewURI (uri_cstring, nsnull, nsnull, getter_AddRefs (ns_uri));
if (!NS_FAILED (rv))
global_history->SendLinkVisitedEvent (ns_uri);
}
}
HeadlessGlobalHistory::HeadlessGlobalHistory(void)
{
mMhsHistory = mhs_history_new ();
g_signal_connect (mMhsHistory, "link-visited",
G_CALLBACK (_link_visited_cb), this);
}
HeadlessGlobalHistory::~HeadlessGlobalHistory()
{
if (mMhsHistory) {
g_signal_handlers_disconnect_by_func (mMhsHistory,
(gpointer)_link_visited_cb,
this);
g_object_unref (mMhsHistory);
mMhsHistory = NULL;
}
if (sHeadlessGlobalHistory == this)
sHeadlessGlobalHistory = nsnull;
}
HeadlessGlobalHistory *HeadlessGlobalHistory::sHeadlessGlobalHistory = nsnull;
HeadlessGlobalHistory *
HeadlessGlobalHistory::GetSingleton(void)
{
if (!sHeadlessGlobalHistory) {
sHeadlessGlobalHistory = new HeadlessGlobalHistory ();
}
return sHeadlessGlobalHistory;
}
NS_IMETHODIMP_(nsrefcnt)
HeadlessGlobalHistory::AddRef ()
{
return 1;
}
NS_IMETHODIMP_(nsrefcnt)
HeadlessGlobalHistory::Release ()
{
return 1;
}
NS_IMPL_QUERY_INTERFACE2(HeadlessGlobalHistory,
nsIGlobalHistory2,
nsISupportsWeakReference)
NS_IMETHODIMP
HeadlessGlobalHistory::AddURI(nsIURI *aURI,
PRBool aRedirect,
PRBool aToplevel,
nsIURI *aReferrer)
{
nsCAutoString uriString, refString;
nsresult rv = aURI->GetSpec(uriString);
if (NS_FAILED(rv))
return rv;
const char *referrer = NULL;
if (aReferrer) {
rv = aReferrer->GetSpec(refString);
if (NS_FAILED(rv))
return rv;
referrer = refString.get();
}
GError *error = NULL;
gboolean result =
mhs_history_add_uri (mMhsHistory,
(const gchar *)uriString.get(),
(gboolean)aRedirect,
(gboolean)aToplevel,
(const gchar *)referrer,
&error);
if (!result)
{
g_warning ("Error adding URI: %s", error->message);
g_error_free (error);
return NS_ERROR_UNEXPECTED;
}
return NS_OK;
}
NS_IMETHODIMP
HeadlessGlobalHistory::IsVisited(nsIURI *aURI, PRBool *_retval)
{
nsCAutoString uriString;
nsresult rv = aURI->GetSpec(uriString);
if (NS_FAILED(rv))
return rv;
GError *error = NULL;
gboolean is_visited = FALSE;
gboolean result =
mhs_history_is_visited (mMhsHistory,
(const gchar *)uriString.get(),
&is_visited,
&error);
if (!result)
{
g_warning ("Error checking is-visited: %s", error->message);
g_error_free (error);
return NS_ERROR_UNEXPECTED;
}
else
*_retval = is_visited;
return NS_OK;
}
NS_IMETHODIMP
HeadlessGlobalHistory::SetPageTitle(nsIURI *aURI, const nsAString &aTitle)
{
nsCAutoString uriString;
nsresult rv = aURI->GetSpec(uriString);
if (NS_FAILED(rv))
return rv;
char *title_utf8 = ToNewUTF8String(aTitle);
GError *error = NULL;
gboolean result =
mhs_history_set_page_title (mMhsHistory,
(const gchar *)uriString.get(),
(const gchar *)title_utf8,
&error);
if (!result)
{
g_warning ("Error setting page title: %s", error->message);
g_error_free (error);
rv = NS_ERROR_UNEXPECTED;
}
else
rv = NS_OK;
NS_Free (title_utf8);
return rv;
}
void
HeadlessGlobalHistory::SendLinkVisitedEvent (nsIURI *aURI)
{
nsCOMPtr<nsIObserverService> obsService =
do_GetService("@mozilla.org/observer-service;1");
if (obsService)
obsService->NotifyObservers(aURI, NS_LINK_VISITED_EVENT_TOPIC, nsnull);
}
#define HEADLESS_GLOBALHISTORY_CID \
{0x45f4a193, 0xe8ec, 0x4687, {0xa9, 0x29, 0xf8, 0x5c, 0x92, 0x49, 0x40, 0x31}}
NS_GENERIC_FACTORY_SINGLETON_CONSTRUCTOR(HeadlessGlobalHistory, HeadlessGlobalHistory::GetSingleton)
static const nsModuleComponentInfo historyServiceComp = {
"Global history",
HEADLESS_GLOBALHISTORY_CID,
"@mozilla.org/browser/global-history;2",
HeadlessGlobalHistoryConstructor
};
void
clutter_mozheadless_history_init ()
{
static gboolean comp_is_registered = FALSE;
if (!comp_is_registered)
{
moz_headless_register_component ((gpointer)&historyServiceComp);
comp_is_registered = TRUE;
}
}
void
clutter_mozheadless_history_deinit ()
{
if (HeadlessGlobalHistory::sHeadlessGlobalHistory)
delete HeadlessGlobalHistory::sHeadlessGlobalHistory;
}
<commit_msg>[history] Use the nsresult from the GError<commit_after>/*
* ClutterMozHeadless; A headless Mozilla renderer
* Copyright (c) 2009, Intel Corporation.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU Lesser General Public License,
* version 2.1, as published by the Free Software Foundation.
*
* This program is distributed in the hope 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.
*
* Authored by Chris Lord <chris@linux.intel.com>
*/
#include <nsIGlobalHistory2.h>
#include <nsWeakReference.h>
#include <nsIGenericFactory.h>
#include <nsIIOService.h>
#include <nsIObserverService.h>
#include <nsIURI.h>
#include <nsNetUtil.h>
#include <nsStringGlue.h>
#include "clutter-mozheadless.h"
#include "clutter-mozheadless-history.h"
#include <moz-headless.h>
#include <mhs/mhs.h>
class HeadlessGlobalHistory : public nsIGlobalHistory2,
public nsSupportsWeakReference
{
public:
HeadlessGlobalHistory();
virtual ~HeadlessGlobalHistory();
static HeadlessGlobalHistory *GetSingleton(void);
static HeadlessGlobalHistory *sHeadlessGlobalHistory;
NS_DECL_ISUPPORTS
NS_DECL_NSIGLOBALHISTORY2
void SendLinkVisitedEvent (nsIURI *aURI);
private:
MhsHistory *mMhsHistory;
};
static void
_link_visited_cb (MhsHistory *history,
const gchar *uri,
HeadlessGlobalHistory *global_history)
{
nsresult rv;
nsCOMPtr<nsIIOService> io_service =
do_GetService (NS_IOSERVICE_CONTRACTID, &rv);
if (!NS_FAILED (rv))
{
nsDependentCString uri_cstring (uri);
nsCOMPtr<nsIURI> ns_uri;
rv = io_service->NewURI (uri_cstring, nsnull, nsnull, getter_AddRefs (ns_uri));
if (!NS_FAILED (rv))
global_history->SendLinkVisitedEvent (ns_uri);
}
}
HeadlessGlobalHistory::HeadlessGlobalHistory(void)
{
mMhsHistory = mhs_history_new ();
g_signal_connect (mMhsHistory, "link-visited",
G_CALLBACK (_link_visited_cb), this);
}
HeadlessGlobalHistory::~HeadlessGlobalHistory()
{
if (mMhsHistory) {
g_signal_handlers_disconnect_by_func (mMhsHistory,
(gpointer)_link_visited_cb,
this);
g_object_unref (mMhsHistory);
mMhsHistory = NULL;
}
if (sHeadlessGlobalHistory == this)
sHeadlessGlobalHistory = nsnull;
}
HeadlessGlobalHistory *HeadlessGlobalHistory::sHeadlessGlobalHistory = nsnull;
HeadlessGlobalHistory *
HeadlessGlobalHistory::GetSingleton(void)
{
if (!sHeadlessGlobalHistory) {
sHeadlessGlobalHistory = new HeadlessGlobalHistory ();
}
return sHeadlessGlobalHistory;
}
NS_IMETHODIMP_(nsrefcnt)
HeadlessGlobalHistory::AddRef ()
{
return 1;
}
NS_IMETHODIMP_(nsrefcnt)
HeadlessGlobalHistory::Release ()
{
return 1;
}
NS_IMPL_QUERY_INTERFACE2(HeadlessGlobalHistory,
nsIGlobalHistory2,
nsISupportsWeakReference)
NS_IMETHODIMP
HeadlessGlobalHistory::AddURI(nsIURI *aURI,
PRBool aRedirect,
PRBool aToplevel,
nsIURI *aReferrer)
{
nsCAutoString uriString, refString;
nsresult rv = aURI->GetSpec(uriString);
if (NS_FAILED(rv))
return rv;
const char *referrer = NULL;
if (aReferrer) {
rv = aReferrer->GetSpec(refString);
if (NS_FAILED(rv))
return rv;
referrer = refString.get();
}
GError *error = NULL;
gboolean result =
mhs_history_add_uri (mMhsHistory,
(const gchar *)uriString.get(),
(gboolean)aRedirect,
(gboolean)aToplevel,
(const gchar *)referrer,
&error);
if (!result)
{
nsresult rv = mhs_error_to_nsresult (error);
g_warning ("Error adding URI: %s", error->message);
g_error_free (error);
return rv;
}
return NS_OK;
}
NS_IMETHODIMP
HeadlessGlobalHistory::IsVisited(nsIURI *aURI, PRBool *_retval)
{
nsCAutoString uriString;
nsresult rv = aURI->GetSpec(uriString);
if (NS_FAILED(rv))
return rv;
GError *error = NULL;
gboolean is_visited = FALSE;
gboolean result =
mhs_history_is_visited (mMhsHistory,
(const gchar *)uriString.get(),
&is_visited,
&error);
if (!result)
{
nsresult rv = mhs_error_to_nsresult (error);
g_warning ("Error checking is-visited: %s", error->message);
g_error_free (error);
return rv;
}
else
*_retval = is_visited;
return NS_OK;
}
NS_IMETHODIMP
HeadlessGlobalHistory::SetPageTitle(nsIURI *aURI, const nsAString &aTitle)
{
nsCAutoString uriString;
nsresult rv = aURI->GetSpec(uriString);
if (NS_FAILED(rv))
return rv;
char *title_utf8 = ToNewUTF8String(aTitle);
GError *error = NULL;
gboolean result =
mhs_history_set_page_title (mMhsHistory,
(const gchar *)uriString.get(),
(const gchar *)title_utf8,
&error);
if (!result)
{
rv = mhs_error_to_nsresult (error);
g_warning ("Error setting page title: %s", error->message);
g_error_free (error);
}
else
rv = NS_OK;
NS_Free (title_utf8);
return rv;
}
void
HeadlessGlobalHistory::SendLinkVisitedEvent (nsIURI *aURI)
{
nsCOMPtr<nsIObserverService> obsService =
do_GetService("@mozilla.org/observer-service;1");
if (obsService)
obsService->NotifyObservers(aURI, NS_LINK_VISITED_EVENT_TOPIC, nsnull);
}
#define HEADLESS_GLOBALHISTORY_CID \
{0x45f4a193, 0xe8ec, 0x4687, {0xa9, 0x29, 0xf8, 0x5c, 0x92, 0x49, 0x40, 0x31}}
NS_GENERIC_FACTORY_SINGLETON_CONSTRUCTOR(HeadlessGlobalHistory, HeadlessGlobalHistory::GetSingleton)
static const nsModuleComponentInfo historyServiceComp = {
"Global history",
HEADLESS_GLOBALHISTORY_CID,
"@mozilla.org/browser/global-history;2",
HeadlessGlobalHistoryConstructor
};
void
clutter_mozheadless_history_init ()
{
static gboolean comp_is_registered = FALSE;
if (!comp_is_registered)
{
moz_headless_register_component ((gpointer)&historyServiceComp);
comp_is_registered = TRUE;
}
}
void
clutter_mozheadless_history_deinit ()
{
if (HeadlessGlobalHistory::sHeadlessGlobalHistory)
delete HeadlessGlobalHistory::sHeadlessGlobalHistory;
}
<|endoftext|>
|
<commit_before>#pragma once
#include <cstddef>
#include <memory>
#include <functional>
#include <ratio>
#include <iterator>
#include <initializer_list>
#include <circular_iterator.hpp>
namespace helene
{
template <class T,
std::size_t Size,
template <class, class, std::size_t> class StoragePolicy>
class sliding_window
: public StoragePolicy<sliding_window<T, Size, StoragePolicy>, T, Size>
{
typedef StoragePolicy<sliding_window<T, Size, StoragePolicy>, T, Size>
storage_policy;
public:
static const std::size_t size = Size;
typedef T value_type;
typedef T& reference;
typedef const T& const_reference;
typedef std::size_t size_type;
typedef std::ptrdiff_t difference_type;
typedef circular_iterator<T*> iterator;
typedef circular_iterator<const T*> const_iterator;
public:
sliding_window()
: storage_policy(),
head_(storage_policy::begin(),
storage_policy::end(),
storage_policy::begin())
{
}
template <class Iterator>
sliding_window(Iterator first, Iterator last) : sliding_window()
{
for(; first != last; ++first, ++head_)
{
*head_ = *first;
}
}
sliding_window(std::initializer_list<T> il)
: sliding_window(il.begin(), il.end())
{
}
sliding_window(const sliding_window& other)
: storage_policy(other),
head_(storage_policy::begin(),
storage_policy::end(),
storage_policy::begin() + other.head_.underlying_position())
{
}
sliding_window&
operator=(const sliding_window& other)
{
std::copy(other.cbegin(), other.cend(), begin());
return *this;
}
public:
void
push_back(const T& value)
{
*head_ = value;
++head_;
}
void
push_back(const T& value, size_type n)
{
std::fill_n(head_, n, value);
head_ += n;
}
void
push_front(const T& value)
{
--head_;
*head_ = value;
}
void
push_front(const T& value, size_type n)
{
std::fill_n(std::make_reverse_iterator(head_), n, value);
head_ -= n;
}
reference
front()
{
return *head_;
}
const_reference
front() const
{
return *head_;
}
reference
back()
{
return *(head_ + Size - 1);
}
const_reference
back() const
{
return *(head_ + Size - 1);
}
reference operator[](size_type n)
{
return head_[n];
}
const_reference operator[](size_type n) const
{
return head_[n];
}
iterator
begin()
{
return head_;
}
iterator
end()
{
return head_ + Size;
}
const_iterator
cbegin() const
{
return head_;
}
const_iterator
cend() const
{
return head_ + Size;
}
bool
operator==(const sliding_window& other) const
{
return std::equal(cbegin(), cend(), other.cbegin());
}
bool
operator!=(const sliding_window& other) const
{
return !operator==(other);
}
private:
iterator head_;
};
template <class Derived, class T, std::size_t Size>
class stack_storage
{
public:
stack_storage() : buffer_{}
{
}
stack_storage(const stack_storage& other)
{
std::copy(std::begin(other.buffer_),
std::end(other.buffer_),
std::begin(buffer_));
}
stack_storage&
operator=(const stack_storage& other)
{
std::copy(std::begin(other.buffer_),
std::end(other.buffer_),
std::begin(buffer_));
return *this;
}
void
swap(stack_storage& other)
{
std::swap(buffer_, other.buffer_);
}
public:
T*
begin()
{
return buffer_;
}
T*
end()
{
return buffer_ + Size;
}
protected:
T buffer_[Size];
};
template <class Derived, class T, std::size_t Size>
class static_heap_storage
{
public:
static_heap_storage() : buffer_(new T[Size]{})
{
}
static_heap_storage(const static_heap_storage& other)
: static_heap_storage()
{
std::copy(
other.buffer_.get(), other.buffer_.get() + Size, buffer_.get());
}
static_heap_storage(static_heap_storage&&) = default;
static_heap_storage&
operator=(const static_heap_storage& other)
{
auto temp = other;
swap(temp);
return *this;
}
static_heap_storage& operator=(static_heap_storage&&) = default;
void
swap(static_heap_storage& other)
{
std::swap(buffer_, other.buffer_);
}
public:
T*
begin()
{
return buffer_.get();
}
T*
end()
{
return buffer_.get() + Size;
}
protected:
std::unique_ptr<T[]> buffer_;
};
template <class T, std::size_t Size>
using stack_sliding_window = sliding_window<T, Size, stack_storage>;
template <class T, std::size_t Size>
using static_heap_sliding_window = sliding_window<T, Size, static_heap_storage>;
namespace detail
{
struct runtime_ratio
{
runtime_ratio() : num(1), den(1)
{
}
template <std::intmax_t Num, std::intmax_t Denom>
constexpr runtime_ratio(std::ratio<Num, Denom>) : num(Num), den(Denom)
{
}
std::intmax_t num;
std::intmax_t den;
};
template <class Numeric>
Numeric operator*(const runtime_ratio& lhs, Numeric rhs)
{
return rhs * static_cast<Numeric>(lhs.num) / static_cast<Numeric>(lhs.den);
}
template <class Numeric>
Numeric operator*(Numeric lhs, const runtime_ratio& rhs)
{
return rhs * lhs;
}
template <class Numeric>
Numeric
operator/(Numeric lhs, const runtime_ratio& rhs)
{
return lhs * static_cast<Numeric>(rhs.den) / static_cast<Numeric>(rhs.num);
}
} // namespace detail
template <class KeyType,
class ValueType,
std::size_t Size,
class Compare = std::less<KeyType>,
class SlidingWindowType = static_heap_sliding_window<ValueType, Size>>
class sliding_window_map
{
public:
typedef ValueType value_type;
typedef ValueType& reference;
typedef const ValueType& const_reference;
typedef typename SlidingWindowType::iterator iterator;
typedef typename SlidingWindowType::const_iterator const_iterator;
typedef typename SlidingWindowType::difference_type difference_type;
typedef typename SlidingWindowType::size_type size_type;
public:
sliding_window_map() : sliding_buffer_(), precision_(), origin_()
{
}
template <std::intmax_t Num, std::intmax_t Denom>
sliding_window_map(std::ratio<Num, Denom>)
: sliding_buffer_(), precision_(std::ratio<Num, Denom>()), origin_()
{
}
sliding_window_map(KeyType origin)
: sliding_buffer_(), precision_(), origin_(origin / precision_)
{
}
template <std::intmax_t Num, std::intmax_t Denom>
sliding_window_map(KeyType origin, std::ratio<Num, Denom>)
: sliding_buffer_(),
precision_(std::ratio<Num, Denom>()),
origin_(origin / precision_)
{
}
std::pair<KeyType, KeyType>
window() const
{
return std::make_pair(static_cast<KeyType>(origin_) * precision_,
static_cast<KeyType>(origin_ + Size) *
precision_);
}
ValueType&
at(KeyType k)
{
const auto index = index_of_key(k);
const Compare c;
if(c(index, 0) || (!c(index, Size)))
{
throw std::out_of_range("Key outside of current window");
}
return sliding_buffer_[index];
}
ValueType& operator[](KeyType k)
{
return sliding_buffer_[k / precision_ - origin_];
}
void
insert_or_assign(KeyType k, const ValueType& v)
{
const auto index = index_of_key(k);
const Compare c;
if(c(index, 0))
{
// below current window
sliding_buffer_.push_front(ValueType(), -index);
sliding_buffer_.front() = v;
origin_ += index * precision_;
}
else if(!c(index, Size))
{
// above current window
sliding_buffer_.push_back(ValueType(), index - Size + 1);
sliding_buffer_.back() = v;
origin_ += (index - Size + 1) * precision_;
}
else
{
// within current window
sliding_buffer_[index] = v;
}
}
iterator
begin()
{
return sliding_buffer_.begin();
}
iterator
end()
{
return sliding_buffer_.end();
}
const_iterator
cbegin()
{
return sliding_buffer_.cbegin();
}
const_iterator
cend()
{
return sliding_buffer_.cend();
}
private:
difference_type
index_of_key(KeyType k)
{
return (k - origin_ * precision_) / precision_;
}
private:
SlidingWindowType sliding_buffer_;
detail::runtime_ratio precision_;
difference_type origin_;
};
} // namespace helene
namespace std
{
template <class Derived, class T, std::size_t Size>
void
swap(helene::stack_storage<Derived, T, Size>& lhs,
helene::stack_storage<Derived, T, Size>& rhs)
{
lhs.swap(rhs);
}
template <class Derived, class T, std::size_t Size>
void
swap(helene::static_heap_storage<Derived, T, Size>& lhs,
helene::static_heap_storage<Derived, T, Size>& rhs)
{
lhs.swap(rhs);
}
} // namespace std
<commit_msg>Const qualify cbegin and cend. modified: include/sliding_window.hpp<commit_after>#pragma once
#include <cstddef>
#include <memory>
#include <functional>
#include <ratio>
#include <iterator>
#include <initializer_list>
#include <circular_iterator.hpp>
namespace helene
{
template <class T,
std::size_t Size,
template <class, class, std::size_t> class StoragePolicy>
class sliding_window
: public StoragePolicy<sliding_window<T, Size, StoragePolicy>, T, Size>
{
typedef StoragePolicy<sliding_window<T, Size, StoragePolicy>, T, Size>
storage_policy;
public:
static const std::size_t size = Size;
typedef T value_type;
typedef T& reference;
typedef const T& const_reference;
typedef std::size_t size_type;
typedef std::ptrdiff_t difference_type;
typedef circular_iterator<T*> iterator;
typedef circular_iterator<const T*> const_iterator;
public:
sliding_window()
: storage_policy(),
head_(storage_policy::begin(),
storage_policy::end(),
storage_policy::begin())
{
}
template <class Iterator>
sliding_window(Iterator first, Iterator last) : sliding_window()
{
for(; first != last; ++first, ++head_)
{
*head_ = *first;
}
}
sliding_window(std::initializer_list<T> il)
: sliding_window(il.begin(), il.end())
{
}
sliding_window(const sliding_window& other)
: storage_policy(other),
head_(storage_policy::begin(),
storage_policy::end(),
storage_policy::begin() + other.head_.underlying_position())
{
}
sliding_window&
operator=(const sliding_window& other)
{
std::copy(other.cbegin(), other.cend(), begin());
return *this;
}
public:
void
push_back(const T& value)
{
*head_ = value;
++head_;
}
void
push_back(const T& value, size_type n)
{
std::fill_n(head_, n, value);
head_ += n;
}
void
push_front(const T& value)
{
--head_;
*head_ = value;
}
void
push_front(const T& value, size_type n)
{
std::fill_n(std::make_reverse_iterator(head_), n, value);
head_ -= n;
}
reference
front()
{
return *head_;
}
const_reference
front() const
{
return *head_;
}
reference
back()
{
return *(head_ + Size - 1);
}
const_reference
back() const
{
return *(head_ + Size - 1);
}
reference operator[](size_type n)
{
return head_[n];
}
const_reference operator[](size_type n) const
{
return head_[n];
}
iterator
begin()
{
return head_;
}
iterator
end()
{
return head_ + Size;
}
const_iterator
cbegin() const
{
return head_;
}
const_iterator
cend() const
{
return head_ + Size;
}
bool
operator==(const sliding_window& other) const
{
return std::equal(cbegin(), cend(), other.cbegin());
}
bool
operator!=(const sliding_window& other) const
{
return !operator==(other);
}
private:
iterator head_;
};
template <class Derived, class T, std::size_t Size>
class stack_storage
{
public:
stack_storage() : buffer_{}
{
}
stack_storage(const stack_storage& other)
{
std::copy(std::begin(other.buffer_),
std::end(other.buffer_),
std::begin(buffer_));
}
stack_storage&
operator=(const stack_storage& other)
{
std::copy(std::begin(other.buffer_),
std::end(other.buffer_),
std::begin(buffer_));
return *this;
}
void
swap(stack_storage& other)
{
std::swap(buffer_, other.buffer_);
}
public:
T*
begin()
{
return buffer_;
}
T*
end()
{
return buffer_ + Size;
}
protected:
T buffer_[Size];
};
template <class Derived, class T, std::size_t Size>
class static_heap_storage
{
public:
static_heap_storage() : buffer_(new T[Size]{})
{
}
static_heap_storage(const static_heap_storage& other)
: static_heap_storage()
{
std::copy(
other.buffer_.get(), other.buffer_.get() + Size, buffer_.get());
}
static_heap_storage(static_heap_storage&&) = default;
static_heap_storage&
operator=(const static_heap_storage& other)
{
auto temp = other;
swap(temp);
return *this;
}
static_heap_storage& operator=(static_heap_storage&&) = default;
void
swap(static_heap_storage& other)
{
std::swap(buffer_, other.buffer_);
}
public:
T*
begin()
{
return buffer_.get();
}
T*
end()
{
return buffer_.get() + Size;
}
protected:
std::unique_ptr<T[]> buffer_;
};
template <class T, std::size_t Size>
using stack_sliding_window = sliding_window<T, Size, stack_storage>;
template <class T, std::size_t Size>
using static_heap_sliding_window = sliding_window<T, Size, static_heap_storage>;
namespace detail
{
struct runtime_ratio
{
runtime_ratio() : num(1), den(1)
{
}
template <std::intmax_t Num, std::intmax_t Denom>
constexpr runtime_ratio(std::ratio<Num, Denom>) : num(Num), den(Denom)
{
}
std::intmax_t num;
std::intmax_t den;
};
template <class Numeric>
Numeric operator*(const runtime_ratio& lhs, Numeric rhs)
{
return rhs * static_cast<Numeric>(lhs.num) / static_cast<Numeric>(lhs.den);
}
template <class Numeric>
Numeric operator*(Numeric lhs, const runtime_ratio& rhs)
{
return rhs * lhs;
}
template <class Numeric>
Numeric
operator/(Numeric lhs, const runtime_ratio& rhs)
{
return lhs * static_cast<Numeric>(rhs.den) / static_cast<Numeric>(rhs.num);
}
} // namespace detail
template <class KeyType,
class ValueType,
std::size_t Size,
class Compare = std::less<KeyType>,
class SlidingWindowType = static_heap_sliding_window<ValueType, Size>>
class sliding_window_map
{
public:
typedef ValueType value_type;
typedef ValueType& reference;
typedef const ValueType& const_reference;
typedef typename SlidingWindowType::iterator iterator;
typedef typename SlidingWindowType::const_iterator const_iterator;
typedef typename SlidingWindowType::difference_type difference_type;
typedef typename SlidingWindowType::size_type size_type;
public:
sliding_window_map() : sliding_buffer_(), precision_(), origin_()
{
}
template <std::intmax_t Num, std::intmax_t Denom>
sliding_window_map(std::ratio<Num, Denom>)
: sliding_buffer_(), precision_(std::ratio<Num, Denom>()), origin_()
{
}
sliding_window_map(KeyType origin)
: sliding_buffer_(), precision_(), origin_(origin / precision_)
{
}
template <std::intmax_t Num, std::intmax_t Denom>
sliding_window_map(KeyType origin, std::ratio<Num, Denom>)
: sliding_buffer_(),
precision_(std::ratio<Num, Denom>()),
origin_(origin / precision_)
{
}
std::pair<KeyType, KeyType>
window() const
{
return std::make_pair(static_cast<KeyType>(origin_) * precision_,
static_cast<KeyType>(origin_ + Size) *
precision_);
}
ValueType&
at(KeyType k)
{
const auto index = index_of_key(k);
const Compare c;
if(c(index, 0) || (!c(index, Size)))
{
throw std::out_of_range("Key outside of current window");
}
return sliding_buffer_[index];
}
ValueType& operator[](KeyType k)
{
return sliding_buffer_[k / precision_ - origin_];
}
void
insert_or_assign(KeyType k, const ValueType& v)
{
const auto index = index_of_key(k);
const Compare c;
if(c(index, 0))
{
// below current window
sliding_buffer_.push_front(ValueType(), -index);
sliding_buffer_.front() = v;
origin_ += index * precision_;
}
else if(!c(index, Size))
{
// above current window
sliding_buffer_.push_back(ValueType(), index - Size + 1);
sliding_buffer_.back() = v;
origin_ += (index - Size + 1) * precision_;
}
else
{
// within current window
sliding_buffer_[index] = v;
}
}
iterator
begin()
{
return sliding_buffer_.begin();
}
iterator
end()
{
return sliding_buffer_.end();
}
const_iterator
cbegin() const
{
return sliding_buffer_.cbegin();
}
const_iterator
cend() const
{
return sliding_buffer_.cend();
}
private:
difference_type
index_of_key(KeyType k)
{
return (k - origin_ * precision_) / precision_;
}
private:
SlidingWindowType sliding_buffer_;
detail::runtime_ratio precision_;
difference_type origin_;
};
} // namespace helene
namespace std
{
template <class Derived, class T, std::size_t Size>
void
swap(helene::stack_storage<Derived, T, Size>& lhs,
helene::stack_storage<Derived, T, Size>& rhs)
{
lhs.swap(rhs);
}
template <class Derived, class T, std::size_t Size>
void
swap(helene::static_heap_storage<Derived, T, Size>& lhs,
helene::static_heap_storage<Derived, T, Size>& rhs)
{
lhs.swap(rhs);
}
} // namespace std
<|endoftext|>
|
<commit_before>#define BOOST_TEST_MODULE forward_models sphere
#include <boost/test/included/unit_test.hpp>
#include "algebra.h"
#include "map.h"
#include "optimization.h"
#include "forward_models/sphere.h"
#include "utility.h"
#include "test_types.h"
#include <iostream>
constexpr double EPS = 1e-9;
constexpr int ntests = 100;
using namespace invlib;
// Use the sphere function forward model to test the equivalence of the
// standard, n-form and m-form when using the Gauss-Newton optimizer.
template
<
typename T
>
void sphere_test(unsigned int n)
{
using RealType = typename T::RealType;
using VectorType = typename T::VectorType;
using MatrixType = typename T::MatrixType;
using Model = Sphere<MatrixType>;
MatrixType Se = random_positive_definite<MatrixType>(1);
MatrixType Sa = random_positive_definite<MatrixType>(n);
VectorType xa = random<VectorType>(n);
VectorType y = random<VectorType>(1);
Model F(n);
MAP<Model, RealType, VectorType, MatrixType,
MatrixType, MatrixType, Formulation::STANDARD> std(F, xa, Sa, Se);
MAP<Model, RealType, VectorType, MatrixType,
MatrixType, MatrixType, Formulation::NFORM> nform(F, xa, Sa, Se);
MAP<Model, RealType, VectorType, MatrixType,
MatrixType, MatrixType, Formulation::MFORM> mform(F, xa, Sa, Se);
GaussNewton<RealType> GN{};
GN.tolerance() = 1e-15; GN.maximum_iterations() = 1000;
VectorType x_std, x_n, x_m;
std.compute(x_std, y, GN);
nform.compute(x_n, y, GN);
mform.compute(x_m, y, GN);
RealType e1, e2;
e1 = maximum_error(x_std, x_m);
e2 = maximum_error(x_std, x_n);
BOOST_TEST((e1 < EPS), "Error STD - NFORM = " << e1);
BOOST_TEST((e2 < EPS), "Error STD - MFORM =" << e2);
// Test inversion using CG solver.
ConjugateGradient cg(1e-12);
GaussNewton<RealType, ConjugateGradient> GN_CG(cg);
GN_CG.tolerance() = 1e-15; GN_CG.maximum_iterations() = 1000;
std.compute(x_std, y, GN_CG);
nform.compute(x_n, y, GN_CG);
mform.compute(x_m, y, GN_CG);
e1 = maximum_error(x_std, x_m);
e2 = maximum_error(x_std, x_n);
BOOST_TEST((e1 < EPS), "Error STD - NFORM CG = " << e1);
BOOST_TEST((e2 < EPS), "Error STD - MFORM CG = " << e2);
}
BOOST_AUTO_TEST_CASE_TEMPLATE(sphere, T, matrix_types)
{
srand(time(NULL));
for (unsigned int i = 0; i < ntests; i++)
{
unsigned int n = 10;
sphere_test<T>(n);
}
}
<commit_msg>Adapted test to new structure of source tree.<commit_after>#define BOOST_TEST_MODULE forward_models sphere
#include <boost/test/included/unit_test.hpp>
#include <iostream>
#include "invlib/algebra.h"
#include "invlib/map.h"
#include "invlib/optimization.h"
#include "forward_models/sphere.h"
#include "utility.h"
#include "test_types.h"
constexpr double EPS = 1e-9;
constexpr int ntests = 100;
using namespace invlib;
// Use the sphere function forward model to test the equivalence of the
// standard, n-form and m-form when using the Gauss-Newton optimizer.
template
<
typename T
>
void sphere_test(unsigned int n)
{
using RealType = typename T::RealType;
using VectorType = typename T::VectorType;
using MatrixType = typename T::MatrixType;
using Model = Sphere<MatrixType>;
MatrixType Se = random_positive_definite<MatrixType>(1);
MatrixType Sa = random_positive_definite<MatrixType>(n);
VectorType xa = random<VectorType>(n);
VectorType y = random<VectorType>(1);
Model F(n);
MAP<Model, RealType, VectorType, MatrixType,
MatrixType, MatrixType, Formulation::STANDARD> std(F, xa, Sa, Se);
MAP<Model, RealType, VectorType, MatrixType,
MatrixType, MatrixType, Formulation::NFORM> nform(F, xa, Sa, Se);
MAP<Model, RealType, VectorType, MatrixType,
MatrixType, MatrixType, Formulation::MFORM> mform(F, xa, Sa, Se);
GaussNewton<RealType> GN{};
GN.tolerance() = 1e-15; GN.maximum_iterations() = 1000;
VectorType x_std, x_n, x_m;
std.compute(x_std, y, GN);
nform.compute(x_n, y, GN);
mform.compute(x_m, y, GN);
RealType e1, e2;
e1 = maximum_error(x_std, x_m);
e2 = maximum_error(x_std, x_n);
BOOST_TEST((e1 < EPS), "Error STD - NFORM = " << e1);
BOOST_TEST((e2 < EPS), "Error STD - MFORM =" << e2);
// Test inversion using CG solver.
ConjugateGradient cg(1e-12);
GaussNewton<RealType, ConjugateGradient> GN_CG(cg);
GN_CG.tolerance() = 1e-15; GN_CG.maximum_iterations() = 1000;
std.compute(x_std, y, GN_CG);
nform.compute(x_n, y, GN_CG);
mform.compute(x_m, y, GN_CG);
e1 = maximum_error(x_std, x_m);
e2 = maximum_error(x_std, x_n);
BOOST_TEST((e1 < EPS), "Error STD - NFORM CG = " << e1);
BOOST_TEST((e2 < EPS), "Error STD - MFORM CG = " << e2);
}
BOOST_AUTO_TEST_CASE_TEMPLATE(sphere, T, matrix_types)
{
srand(time(NULL));
for (unsigned int i = 0; i < ntests; i++)
{
unsigned int n = 10;
sphere_test<T>(n);
}
}
<|endoftext|>
|
<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 "selxSuperElastixFilterCustomComponents.h"
#include "selxItkDisplacementFieldSourceComponent.h"
#include "selxItkDisplacementFieldSinkComponent.h"
#include "selxItkMeshSourceComponent.h"
#include "selxItkMeshSinkComponent.h"
#include "itkMeshFileReader.h"
#include "itkMeshFileWriter.h"
#include "selxDisplacementFieldMeshWarperComponent.h"
#include "gtest/gtest.h"
#include "selxDataManager.h"
namespace selx {
class DisplacementFieldMeshWarperComponentTest : public ::testing::Test {
public:
typedef ItkDisplacementFieldMeshWarperComponent< 2, float, float >::ItkDisplacementFieldType DisplacementFieldType;
typedef DisplacementFieldType::Pointer DisplacementFieldPointer;
typedef itk::ImageFileReader< DisplacementFieldType > DisplacementFieldReaderType;
typedef DisplacementFieldReaderType::Pointer DisplacementFieldReaderPointer;
typedef itk::ImageFileWriter< DisplacementFieldType > DisplacementFieldWriterType;
typedef DisplacementFieldWriterType::Pointer DisplacementFieldWriterPointer;
typedef itk::Mesh< float, 2 > MeshType;
typedef MeshType::Pointer MeshPointer;
typedef itk::MeshFileReader< MeshType > MeshReaderType;
typedef MeshReaderType::Pointer MeshReaderPointer;
typedef itk::MeshFileWriter< MeshType > MeshWriterType;
typedef MeshWriterType::Pointer MeshWriterPointer;
typedef Blueprint::Pointer BlueprintPointer;
typedef TypeList<
ItkDisplacementFieldSourceComponent< 2, float >,
ItkDisplacementFieldSinkComponent< 2, float >,
ItkMeshSourceComponent< 2, float >,
ItkMeshSinkComponent< 2, float >,
ItkDisplacementFieldMeshWarperComponent< 2, float, float > > TestComponents;
typedef SuperElastixFilterCustomComponents< TestComponents > SuperElastixFilterType;
typedef SuperElastixFilterType::Pointer SuperElastixFilterPointer;
DataManager::Pointer dataManager = DataManager::New();
};
TEST_F( DisplacementFieldMeshWarperComponentTest, SinkAndSource )
{
DisplacementFieldPointer displacementField = DisplacementFieldType::New();
displacementField->SetRegions(DisplacementFieldType::Superclass::SizeType({{3, 3}}));
displacementField->Allocate();
DisplacementFieldType::Superclass::IndexType index00, index01, index02,
index10, index11, index12,
index20, index21, index22;
index00[0] = 0; index00[1] = 0;
index01[0] = 0; index01[1] = 1;
index02[0] = 0; index02[1] = 2;
index10[0] = 1; index10[1] = 0;
index11[0] = 1; index11[1] = 1;
index12[0] = 1; index12[1] = 2;
index20[0] = 2; index20[1] = 0;
index21[0] = 2; index21[1] = 1;
index22[0] = 2; index22[1] = 2;
typedef itk::Vector<float, 2> VectorType;
VectorType displacement00, displacement01, displacement10, displacement11, displacementminus11;
displacement00[0] = 0.;
displacement00[1] = 0.;
displacement01[0] = 0.;
displacement01[1] = 1.;
displacement10[0] = 1.;
displacement10[1] = 0.;
displacement11[0] = 1.;
displacement11[1] = 1.;
displacementminus11[0] = -1.;
displacementminus11[1] = -1.;
displacementField->SetPixel(index00, displacement01);
displacementField->SetPixel(index01, displacement10);
displacementField->SetPixel(index02, displacement00);
displacementField->SetPixel(index10, displacement10);
displacementField->SetPixel(index11, displacement11);
displacementField->SetPixel(index12, displacement00);
displacementField->SetPixel(index20, displacement00);
displacementField->SetPixel(index21, displacement00);
displacementField->SetPixel(index22, displacementminus11);
Logger::Pointer logger = Logger::New();
logger->AddStream( "cout", std::cout );
logger->SetLogLevel( LogLevel::TRC );
BlueprintPointer blueprint = Blueprint::New();
using ParameterMapType = Blueprint::ParameterMapType;
ParameterMapType displacementFieldSourceParameters;
displacementFieldSourceParameters[ "NameOfClass" ] = { "ItkDisplacementFieldSourceComponent" };
displacementFieldSourceParameters[ "Dimensionality" ] = { "2" };
blueprint->SetComponent( "DisplacementFieldSource", displacementFieldSourceParameters );
ParameterMapType meshSourceParameters;
meshSourceParameters[ "NameOfClass" ] = { "ItkMeshSourceComponent" };
meshSourceParameters[ "Dimensionality" ] = { "2" };
blueprint->SetComponent( "MeshSource", meshSourceParameters );
ParameterMapType meshSinkParameters;
meshSinkParameters[ "NameOfClass" ] = { "ItkMeshSinkComponent" };
meshSinkParameters[ "Dimensionality" ] = { "2" };
blueprint->SetComponent( "MeshSink", meshSinkParameters );
ParameterMapType displacementFieldMeshWarperParameters;
displacementFieldMeshWarperParameters[ "NameOfClass" ] = { "ItkDisplacementFieldMeshWarperComponent" };
displacementFieldMeshWarperParameters[ "Dimensionality" ] = { "2" };
blueprint->SetComponent( "DisplacementFieldMeshWarper", displacementFieldMeshWarperParameters );
ParameterMapType connection0;
connection0[ "NameOfInterface" ] = { "itkMeshInterface" };
blueprint->SetConnection( "MeshSource", "ItkDisplacementFieldMeshWarperComponent", connection0 );
ParameterMapType connection1;
connection0[ "NameOfInterface" ] = { "itkDisplacementFieldInterface" };
blueprint->SetConnection( "DisplacementFieldSource", "ItkDisplacementFieldMeshWarperComponent", connection1 );
ParameterMapType connection2;
connection0[ "NameOfInterface" ] = { "itkMeshInterface" };
blueprint->SetConnection( "ItkDisplacementFieldMeshWarperComponent", "MeshSink", connection2 );
SuperElastixFilterPointer superElastixFilter = SuperElastixFilterType::New();
superElastixFilter->SetBlueprint(blueprint);
superElastixFilter->SetLogger(logger);
MeshReaderPointer meshReader = MeshReaderType::New();
meshReader->SetFileName( this->dataManager->GetInputFile( "2dSquare.vtk" ) );
superElastixFilter->SetInput( "DisplacementFieldSource", displacementField );
superElastixFilter->SetInput( "MeshSource", meshReader->GetOutput() );
MeshWriterPointer meshWriter = MeshWriterType::New();
meshWriter->SetFileName( this->dataManager->GetOutputFile( "DisplacementFieldMeshWarperComponentTest.SinkAndSource.WarpedMesh.vtk" ) );
meshWriter->SetInput( superElastixFilter->GetOutput< MeshType >( "MeshSink" ) );
meshWriter->Update();
}
} // namespace selx<commit_msg>BUG: Blueprint used wrong component identifiers at connections<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 "selxSuperElastixFilterCustomComponents.h"
#include "selxItkDisplacementFieldSourceComponent.h"
#include "selxItkDisplacementFieldSinkComponent.h"
#include "selxItkMeshSourceComponent.h"
#include "selxItkMeshSinkComponent.h"
#include "itkMeshFileReader.h"
#include "itkMeshFileWriter.h"
#include "selxDisplacementFieldMeshWarperComponent.h"
#include "gtest/gtest.h"
#include "selxDataManager.h"
namespace selx {
class DisplacementFieldMeshWarperComponentTest : public ::testing::Test {
public:
typedef ItkDisplacementFieldMeshWarperComponent< 2, float, float >::ItkDisplacementFieldType DisplacementFieldType;
typedef DisplacementFieldType::Pointer DisplacementFieldPointer;
typedef itk::ImageFileReader< DisplacementFieldType > DisplacementFieldReaderType;
typedef DisplacementFieldReaderType::Pointer DisplacementFieldReaderPointer;
typedef itk::ImageFileWriter< DisplacementFieldType > DisplacementFieldWriterType;
typedef DisplacementFieldWriterType::Pointer DisplacementFieldWriterPointer;
typedef itk::Mesh< float, 2 > MeshType;
typedef MeshType::Pointer MeshPointer;
typedef itk::MeshFileReader< MeshType > MeshReaderType;
typedef MeshReaderType::Pointer MeshReaderPointer;
typedef itk::MeshFileWriter< MeshType > MeshWriterType;
typedef MeshWriterType::Pointer MeshWriterPointer;
typedef Blueprint::Pointer BlueprintPointer;
typedef TypeList<
ItkDisplacementFieldSourceComponent< 2, float >,
ItkDisplacementFieldSinkComponent< 2, float >,
ItkMeshSourceComponent< 2, float >,
ItkMeshSinkComponent< 2, float >,
ItkDisplacementFieldMeshWarperComponent< 2, float, float > > TestComponents;
typedef SuperElastixFilterCustomComponents< TestComponents > SuperElastixFilterType;
typedef SuperElastixFilterType::Pointer SuperElastixFilterPointer;
DataManager::Pointer dataManager = DataManager::New();
};
TEST_F( DisplacementFieldMeshWarperComponentTest, SinkAndSource )
{
DisplacementFieldPointer displacementField = DisplacementFieldType::New();
displacementField->SetRegions(DisplacementFieldType::Superclass::SizeType({{3, 3}}));
displacementField->Allocate();
DisplacementFieldType::Superclass::IndexType index00, index01, index02,
index10, index11, index12,
index20, index21, index22;
index00[0] = 0; index00[1] = 0;
index01[0] = 0; index01[1] = 1;
index02[0] = 0; index02[1] = 2;
index10[0] = 1; index10[1] = 0;
index11[0] = 1; index11[1] = 1;
index12[0] = 1; index12[1] = 2;
index20[0] = 2; index20[1] = 0;
index21[0] = 2; index21[1] = 1;
index22[0] = 2; index22[1] = 2;
typedef itk::Vector<float, 2> VectorType;
VectorType displacement00, displacement01, displacement10, displacement11, displacementminus11;
displacement00[0] = 0.;
displacement00[1] = 0.;
displacement01[0] = 0.;
displacement01[1] = 1.;
displacement10[0] = 1.;
displacement10[1] = 0.;
displacement11[0] = 1.;
displacement11[1] = 1.;
displacementminus11[0] = -1.;
displacementminus11[1] = -1.;
displacementField->SetPixel(index00, displacement01);
displacementField->SetPixel(index01, displacement10);
displacementField->SetPixel(index02, displacement00);
displacementField->SetPixel(index10, displacement10);
displacementField->SetPixel(index11, displacement11);
displacementField->SetPixel(index12, displacement00);
displacementField->SetPixel(index20, displacement00);
displacementField->SetPixel(index21, displacement00);
displacementField->SetPixel(index22, displacementminus11);
Logger::Pointer logger = Logger::New();
logger->AddStream( "cout", std::cout );
logger->SetLogLevel( LogLevel::TRC );
BlueprintPointer blueprint = Blueprint::New();
using ParameterMapType = Blueprint::ParameterMapType;
ParameterMapType displacementFieldSourceParameters;
displacementFieldSourceParameters[ "NameOfClass" ] = { "ItkDisplacementFieldSourceComponent" };
displacementFieldSourceParameters[ "Dimensionality" ] = { "2" };
blueprint->SetComponent( "DisplacementFieldSource", displacementFieldSourceParameters );
ParameterMapType meshSourceParameters;
meshSourceParameters[ "NameOfClass" ] = { "ItkMeshSourceComponent" };
meshSourceParameters[ "Dimensionality" ] = { "2" };
blueprint->SetComponent( "MeshSource", meshSourceParameters );
ParameterMapType meshSinkParameters;
meshSinkParameters[ "NameOfClass" ] = { "ItkMeshSinkComponent" };
meshSinkParameters[ "Dimensionality" ] = { "2" };
blueprint->SetComponent( "MeshSink", meshSinkParameters );
ParameterMapType displacementFieldMeshWarperParameters;
displacementFieldMeshWarperParameters[ "NameOfClass" ] = { "ItkDisplacementFieldMeshWarperComponent" };
displacementFieldMeshWarperParameters[ "Dimensionality" ] = { "2" };
blueprint->SetComponent( "DisplacementFieldMeshWarper", displacementFieldMeshWarperParameters );
ParameterMapType connection0;
connection0[ "NameOfInterface" ] = { "itkMeshInterface" };
blueprint->SetConnection( "MeshSource", "DisplacementFieldMeshWarper", connection0 );
ParameterMapType connection1;
connection0[ "NameOfInterface" ] = { "itkDisplacementFieldInterface" };
blueprint->SetConnection( "DisplacementFieldSource", "DisplacementFieldMeshWarper", connection1 );
ParameterMapType connection2;
connection0[ "NameOfInterface" ] = { "itkMeshInterface" };
blueprint->SetConnection( "DisplacementFieldMeshWarper", "MeshSink", connection2 );
SuperElastixFilterPointer superElastixFilter = SuperElastixFilterType::New();
superElastixFilter->SetBlueprint(blueprint);
superElastixFilter->SetLogger(logger);
MeshReaderPointer meshReader = MeshReaderType::New();
meshReader->SetFileName( this->dataManager->GetInputFile( "2dSquare.vtk" ) );
superElastixFilter->SetInput( "DisplacementFieldSource", displacementField );
superElastixFilter->SetInput( "MeshSource", meshReader->GetOutput() );
MeshWriterPointer meshWriter = MeshWriterType::New();
meshWriter->SetFileName( this->dataManager->GetOutputFile( "DisplacementFieldMeshWarperComponentTest.SinkAndSource.WarpedMesh.vtk" ) );
meshWriter->SetInput( superElastixFilter->GetOutput< MeshType >( "MeshSink" ) );
meshWriter->Update();
}
} // namespace selx<|endoftext|>
|
<commit_before>#pragma once
#ifndef LIGHTPTR_HPP
# define LIGHTPTR_HPP
#include <cassert>
#include <atomic>
#include <memory>
#include <utility>
#include <type_traits>
namespace detail
{
using counter_type = ::std::size_t;
using atomic_type = ::std::atomic<counter_type>;
using deleter_type = void (*)(void*);
template <typename U>
struct ref_type
{
using type = U&;
};
template <>
struct ref_type<void>
{
using type = void;
};
inline void dec_ref(atomic_type* const counter_ptr,
void* const ptr, deleter_type const deleter)
{
if (counter_ptr && (counter_type(1) ==
counter_ptr->fetch_sub(counter_type(1), ::std::memory_order_relaxed)))
{
delete counter_ptr;
deleter(ptr);
}
// else do nothing
}
inline void inc_ref(atomic_type* const counter_ptr)
{
assert(counter_ptr);
counter_ptr->fetch_add(counter_type(1), ::std::memory_order_relaxed);
}
}
template <typename T>
struct light_ptr
{
template <typename U>
struct deletion_type
{
using type = U;
};
template <typename U>
struct deletion_type<U[]>
{
using type = U[];
};
template <typename U, ::std::size_t N>
struct deletion_type<U[N]>
{
using type = U[];
};
template <typename U>
struct remove_array
{
using type = U;
};
template <typename U>
struct remove_array<U[]>
{
using type = U;
};
template <typename U, ::std::size_t N>
struct remove_array<U[N]>
{
using type = U;
};
using counter_type = ::detail::counter_type;
using deleter_type = ::detail::deleter_type;
using element_type = typename remove_array<T>::type;
light_ptr() = default;
explicit light_ptr(element_type* const p,
deleter_type const d = default_deleter)
{
reset(p, d);
}
~light_ptr() { ::detail::dec_ref(counter_ptr_, ptr_, deleter_); }
light_ptr(light_ptr const& other) { *this = other; }
light_ptr(light_ptr&& other) noexcept { *this = ::std::move(other); }
light_ptr& operator=(light_ptr const& rhs)
{
if (*this != rhs)
{
::detail::dec_ref(counter_ptr_, ptr_, deleter_);
counter_ptr_ = rhs.counter_ptr_;
ptr_ = rhs.ptr_;
deleter_ = rhs.deleter_;
::detail::inc_ref(counter_ptr_);
}
// else do nothing
return *this;
}
light_ptr& operator=(light_ptr&& rhs) noexcept
{
if (*this != rhs)
{
counter_ptr_ = rhs.counter_ptr_;
ptr_ = rhs.ptr_;
deleter_ = rhs.deleter_;
rhs.counter_ptr_ = nullptr;
rhs.ptr_ = nullptr;
}
// else do nothing
return *this;
}
bool operator<(light_ptr const& rhs) const noexcept
{
return get() < rhs.get();
}
bool operator==(light_ptr const& rhs) const noexcept
{
return counter_ptr_ == rhs.counter_ptr_;
}
bool operator!=(light_ptr const& rhs) const noexcept
{
return !operator==(rhs);
}
bool operator==(::std::nullptr_t const) const noexcept
{
return !ptr_;
}
bool operator!=(::std::nullptr_t const) const noexcept
{
return !operator==(nullptr);
}
explicit operator bool() const noexcept { return ptr_; }
typename ::detail::ref_type<T>::type
operator*() const noexcept
{
return *static_cast<T*>(static_cast<void*>(ptr_));
}
T* operator->() const noexcept
{
return static_cast<T*>(static_cast<void*>(ptr_));
}
element_type* get() const noexcept { return ptr_; }
void reset() { reset(nullptr); }
void reset(::std::nullptr_t const)
{
::detail::dec_ref(counter_ptr_, ptr_, deleter_);
counter_ptr_ = nullptr;
ptr_ = nullptr;
}
void reset(element_type* const p,
deleter_type const d = default_deleter)
{
::detail::dec_ref(counter_ptr_, ptr_, deleter_);
counter_ptr_ = new ::detail::atomic_type(counter_type(1));
ptr_ = p;
deleter_ = d;
}
void swap(light_ptr& other) noexcept
{
::std::swap(counter_ptr_, other.counter_ptr_);
::std::swap(ptr_, other.ptr_);
::std::swap(deleter_, other.deleter_);
}
bool unique() const noexcept { return counter_type(1) == use_count(); }
counter_type use_count() const noexcept
{
return counter_ptr_ ?
counter_ptr_->load(::std::memory_order_relaxed) :
counter_type{};
}
private:
static void default_deleter(void* const p)
{
::std::default_delete<typename deletion_type<T>::type>()(
static_cast<element_type*>(p));
}
private:
::detail::atomic_type* counter_ptr_{};
element_type* ptr_{};
deleter_type deleter_;
};
template<class T, class ...Args>
inline light_ptr<T> make_light(Args&& ...args)
{
return light_ptr<T>(new T(::std::forward<Args>(args)...));
}
namespace std
{
template <typename T>
struct hash<light_ptr<T> >
{
size_t operator()(light_ptr<T> const& l) const noexcept
{
return hash<typename light_ptr<T>::element_type*>(l.get());
}
};
}
#endif // LIGHTPTR_HPP
<commit_msg>some fixes<commit_after>#pragma once
#ifndef LIGHTPTR_HPP
# define LIGHTPTR_HPP
#include <cassert>
#include <atomic>
#include <memory>
#include <utility>
#include <type_traits>
namespace detail
{
using counter_type = ::std::size_t;
using atomic_type = ::std::atomic<counter_type>;
using deleter_type = void (*)(void*);
template <typename U>
struct ref_type
{
using type = U&;
};
template <>
struct ref_type<void>
{
using type = void;
};
inline void dec_ref(atomic_type* const counter_ptr,
void* const ptr, deleter_type const deleter)
{
if (counter_ptr && (counter_type(1) ==
counter_ptr->fetch_sub(counter_type(1), ::std::memory_order_relaxed)))
{
delete counter_ptr;
deleter(ptr);
}
// else do nothing
}
inline void inc_ref(atomic_type* const counter_ptr)
{
assert(counter_ptr);
counter_ptr->fetch_add(counter_type(1), ::std::memory_order_relaxed);
}
}
template <typename T>
struct light_ptr
{
template <typename U>
struct deletion_type
{
using type = U;
};
template <typename U>
struct deletion_type<U[]>
{
using type = U[];
};
template <typename U, ::std::size_t N>
struct deletion_type<U[N]>
{
using type = U[];
};
template <typename U>
struct remove_array
{
using type = U;
};
template <typename U>
struct remove_array<U[]>
{
using type = U;
};
template <typename U, ::std::size_t N>
struct remove_array<U[N]>
{
using type = U;
};
using counter_type = ::detail::counter_type;
using deleter_type = ::detail::deleter_type;
using element_type = typename remove_array<T>::type;
light_ptr() = default;
explicit light_ptr(element_type* const p,
deleter_type const d = default_deleter)
{
reset(p, d);
}
~light_ptr() { ::detail::dec_ref(counter_ptr_, ptr_, deleter_); }
light_ptr(light_ptr const& other) { *this = other; }
light_ptr(light_ptr&& other) noexcept { *this = ::std::move(other); }
light_ptr& operator=(light_ptr const& rhs)
{
if (*this != rhs)
{
::detail::dec_ref(counter_ptr_, ptr_, deleter_);
counter_ptr_ = rhs.counter_ptr_;
ptr_ = rhs.ptr_;
deleter_ = rhs.deleter_;
::detail::inc_ref(counter_ptr_);
}
// else do nothing
return *this;
}
light_ptr& operator=(light_ptr&& rhs) noexcept
{
if (*this != rhs)
{
counter_ptr_ = rhs.counter_ptr_;
ptr_ = rhs.ptr_;
deleter_ = rhs.deleter_;
rhs.counter_ptr_ = nullptr;
rhs.ptr_ = nullptr;
}
// else do nothing
return *this;
}
bool operator<(light_ptr const& rhs) const noexcept
{
return get() < rhs.get();
}
bool operator==(light_ptr const& rhs) const noexcept
{
return counter_ptr_ == rhs.counter_ptr_;
}
bool operator!=(light_ptr const& rhs) const noexcept
{
return !operator==(rhs);
}
bool operator==(::std::nullptr_t const) const noexcept
{
return ptr_;
}
bool operator!=(::std::nullptr_t const) const noexcept
{
return !ptr_;
}
explicit operator bool() const noexcept { return ptr_; }
typename ::detail::ref_type<T>::type
operator*() const noexcept
{
return *static_cast<T*>(static_cast<void*>(ptr_));
}
T* operator->() const noexcept
{
return static_cast<T*>(static_cast<void*>(ptr_));
}
element_type* get() const noexcept { return ptr_; }
void reset() { reset(nullptr); }
void reset(::std::nullptr_t const)
{
::detail::dec_ref(counter_ptr_, ptr_, deleter_);
counter_ptr_ = nullptr;
ptr_ = nullptr;
}
void reset(element_type* const p,
deleter_type const d = default_deleter)
{
::detail::dec_ref(counter_ptr_, ptr_, deleter_);
counter_ptr_ = new ::detail::atomic_type(counter_type(1));
ptr_ = p;
deleter_ = d;
}
void swap(light_ptr& other) noexcept
{
::std::swap(counter_ptr_, other.counter_ptr_);
::std::swap(ptr_, other.ptr_);
::std::swap(deleter_, other.deleter_);
}
bool unique() const noexcept { return counter_type(1) == use_count(); }
counter_type use_count() const noexcept
{
return counter_ptr_ ?
counter_ptr_->load(::std::memory_order_relaxed) :
counter_type{};
}
private:
static void default_deleter(void* const p)
{
::std::default_delete<typename deletion_type<T>::type>()(
static_cast<element_type*>(p));
}
private:
::detail::atomic_type* counter_ptr_{};
element_type* ptr_{};
deleter_type deleter_;
};
template<class T, class ...Args>
inline light_ptr<T> make_light(Args&& ...args)
{
return light_ptr<T>(new T(::std::forward<Args>(args)...));
}
namespace std
{
template <typename T>
struct hash<light_ptr<T> >
{
size_t operator()(light_ptr<T> const& l) const noexcept
{
return hash<typename light_ptr<T>::element_type*>(l.get());
}
};
}
#endif // LIGHTPTR_HPP
<|endoftext|>
|
<commit_before>extern "C" {
#include "nyara.h"
}
#include <ruby/re.h>
#include <ruby/encoding.h>
#include <vector>
#include <map>
#include "inc/str_intern.h"
struct RouteEntry {
// note on order: scope is supposed to be the last, but when searching, is_sub is checked first
bool is_sub; // = last_prefix.start_with? prefix
char* prefix;
long prefix_len;
regex_t *suffix_re;
VALUE controller;
VALUE id; // symbol
VALUE accept_exts; // {ext => true}
VALUE accept_mimes; // [[m1, m2, ext]]
std::vector<ID> conv;
VALUE scope;
char* suffix; // only for inspect
long suffix_len;
// don't make it destructor, or it could be called twice if on stack
void dealloc() {
if (prefix) {
xfree(prefix);
prefix = NULL;
}
if (suffix_re) {
onig_free(suffix_re);
suffix_re = NULL;
}
if (suffix) {
xfree(suffix);
suffix = NULL;
}
}
};
typedef std::vector<RouteEntry> RouteEntries;
static std::map<enum http_method, RouteEntries*> route_map;
static OnigRegion region; // we can reuse the region without worrying thread safety
static ID id_to_s;
static rb_encoding* u8_enc;
static VALUE str_html;
static VALUE nyara_http_methods;
static bool start_with(const char* a, long a_len, const char* b, long b_len) {
if (b_len > a_len) {
return false;
}
for (size_t i = 0; i < b_len; i++) {
if (a[i] != b[i]) {
return false;
}
}
return true;
}
static enum http_method canonicalize_http_method(VALUE m) {
VALUE method_num;
if (TYPE(m) == T_STRING) {
method_num = rb_hash_aref(nyara_http_methods, m);
} else {
method_num = m;
}
Check_Type(method_num, T_FIXNUM);
return (enum http_method)FIX2INT(method_num);
}
static VALUE ext_clear_route(VALUE req) {
for (auto i = route_map.begin(); i != route_map.end(); ++i) {
RouteEntries* entries = i->second;
for (auto j = entries->begin(); j != entries->end(); ++j) {
j->dealloc();
}
delete entries;
}
route_map.clear();
return Qnil;
}
static VALUE ext_register_route(VALUE self, VALUE v_e) {
// get route entries
enum http_method m = canonicalize_http_method(rb_iv_get(v_e, "@http_method"));
RouteEntries* route_entries;
auto map_iter = route_map.find(m);
if (map_iter == route_map.end()) {
route_entries = new RouteEntries();
route_map[m] = route_entries;
} else {
route_entries = map_iter->second;
}
// prefix
VALUE v_prefix = rb_iv_get(v_e, "@prefix");
long prefix_len = RSTRING_LEN(v_prefix);
char* prefix = ALLOC_N(char, prefix_len);
memcpy(prefix, RSTRING_PTR(v_prefix), prefix_len);
// check if prefix is substring of last entry
bool is_sub = false;
if (route_entries->size()) {
is_sub = start_with(route_entries->rbegin()->prefix, route_entries->rbegin()->prefix_len, prefix, prefix_len);
}
// suffix
VALUE v_suffix = rb_iv_get(v_e, "@suffix");
long suffix_len = RSTRING_LEN(v_suffix);
char* suffix = ALLOC_N(char, suffix_len);
memcpy(suffix, RSTRING_PTR(v_suffix), suffix_len);
regex_t* suffix_re;
OnigErrorInfo err_info;
onig_new(&suffix_re, (const UChar*)suffix, (const UChar*)(suffix + suffix_len),
ONIG_OPTION_NONE, ONIG_ENCODING_ASCII, ONIG_SYNTAX_RUBY, &err_info);
std::vector<ID> _conv;
RouteEntry e;
e.is_sub = is_sub;
e.prefix = prefix;
e.prefix_len = prefix_len;
e.suffix_re = suffix_re;
e.suffix = suffix;
e.suffix_len = suffix_len;
e.controller = rb_iv_get(v_e, "@controller");
e.id = rb_iv_get(v_e, "@id");
e.conv = _conv;
e.scope = rb_iv_get(v_e, "@scope");
// conv
VALUE v_conv = rb_iv_get(v_e, "@conv");
VALUE* conv_ptr = RARRAY_PTR(v_conv);
long conv_len = RARRAY_LEN(v_conv);
if (onig_number_of_captures(suffix_re) != conv_len) {
e.dealloc();
rb_raise(rb_eRuntimeError, "number of captures mismatch");
}
for (long i = 0; i < conv_len; i++) {
ID conv_id = SYM2ID(conv_ptr[i]);
e.conv.push_back(conv_id);
}
// accept
e.accept_exts = rb_iv_get(v_e, "@accept_exts");
e.accept_mimes = rb_iv_get(v_e, "@accept_mimes");
route_entries->push_back(e);
return Qnil;
}
static VALUE ext_list_route(VALUE self) {
// note: prevent leak with init nil
volatile VALUE arr = Qnil;
volatile VALUE e = Qnil;
volatile VALUE prefix = Qnil;
volatile VALUE conv = Qnil;
volatile VALUE route_hash = rb_hash_new();
for (auto j = route_map.begin(); j != route_map.end(); j++) {
RouteEntries* route_entries = j->second;
VALUE arr = rb_ary_new();
rb_hash_aset(route_hash, rb_str_new2(http_method_str(j->first)), arr);
for (auto i = route_entries->begin(); i != route_entries->end(); i++) {
e = rb_ary_new();
rb_ary_push(e, i->is_sub ? Qtrue : Qfalse);
rb_ary_push(e, i->scope);
rb_ary_push(e, rb_str_new(i->prefix, i->prefix_len));
rb_ary_push(e, rb_str_new(i->suffix, i->suffix_len));
rb_ary_push(e, i->controller);
rb_ary_push(e, i->id);
conv = rb_ary_new();
for (size_t j = 0; j < i->conv.size(); j++) {
rb_ary_push(conv, ID2SYM(i->conv[j]));
}
rb_ary_push(e, conv);
rb_ary_push(arr, e);
}
}
return route_hash;
}
static VALUE build_args(const char* suffix, std::vector<ID>& conv) {
volatile VALUE args = rb_ary_new();
volatile VALUE str = rb_str_new2("");
long last_len = 0;
for (size_t j = 0; j < conv.size(); j++) {
const char* capture_ptr = suffix + region.beg[j+1];
long capture_len = region.end[j+1] - region.beg[j+1];
if (conv[j] == id_to_s) {
rb_ary_push(args, rb_enc_str_new(capture_ptr, capture_len, u8_enc));
} else if (capture_len == 0) {
rb_ary_push(args, Qnil);
} else {
if (capture_len > last_len) {
RESIZE_CAPA(str, capture_len);
last_len = capture_len;
}
memcpy(RSTRING_PTR(str), capture_ptr, capture_len);
STR_SET_LEN(str, capture_len);
rb_ary_push(args, rb_funcall(str, conv[j], 0)); // hex, to_i, to_f
}
}
return args;
}
static VALUE extract_ext(const char* s, long len) {
if (s[0] != '.') {
return Qnil;
}
s++;
len--;
for (long i = 0; i < len; i++) {
if (!isalnum(s[i])) {
return Qnil;
}
}
return rb_str_new(s, len);
}
extern "C"
RouteResult nyara_lookup_route(enum http_method method_num, VALUE vpath, VALUE accept_arr) {
RouteResult r = {Qnil, Qnil, Qnil, Qnil};
auto map_iter = route_map.find(method_num);
if (map_iter == route_map.end()) {
return r;
}
RouteEntries* route_entries = map_iter->second;
const char* path = RSTRING_PTR(vpath);
long len = RSTRING_LEN(vpath);
// must iterate all
bool last_matched = false;
auto i = route_entries->begin();
for (; i != route_entries->end(); ++i) {
bool matched;
if (i->is_sub && last_matched) { // save a bit compare
matched = last_matched;
} else {
matched = start_with(path, len, i->prefix, i->prefix_len);
}
last_matched = matched;
if (/* prefix */ matched) {
const char* suffix = path + i->prefix_len;
long suffix_len = len - i->prefix_len;
if (i->suffix_len == 0) {
if (suffix_len) {
r.format = extract_ext(suffix, suffix_len);
if (r.format == Qnil) {
break;
}
}
r.args = rb_ary_new3(1, i->id);
r.controller = i->controller;
break;
} else {
long matched_len = onig_match(i->suffix_re, (const UChar*)suffix, (const UChar*)(suffix + suffix_len),
(const UChar*)suffix, ®ion, 0);
if (matched_len > 0) {
if (matched_len < suffix_len) {
r.format = extract_ext(suffix + matched_len, suffix_len);
if (r.format == Qnil) {
break;
}
}
r.args = build_args(suffix, i->conv);
rb_ary_push(r.args, i->id);
r.controller = i->controller;
break;
}
}
}
}
if (r.controller != Qnil) {
r.scope = i->scope;
if (r.format == Qnil) {
if (i->accept_exts == Qnil) {
r.format = str_html; // not configured, just plain html
} else {
r.format = ext_mime_match(Qnil, accept_arr, i->accept_mimes);
if (r.format == Qnil) {
r.controller = Qnil; // reject if mime mismatch
}
}
} else {
if (i->accept_exts != Qnil) {
if (!RTEST(rb_hash_aref(i->accept_exts, r.format))) {
r.controller = Qnil; // reject if path ext mismatch
}
}
}
}
return r;
}
static VALUE ext_lookup_route(VALUE self, VALUE method, VALUE path, VALUE accept_arr) {
enum http_method method_num = canonicalize_http_method(method);
volatile RouteResult r = nyara_lookup_route(method_num, path, accept_arr);
volatile VALUE a = rb_ary_new();
rb_ary_push(a, r.scope);
rb_ary_push(a, r.controller);
rb_ary_push(a, r.args);
rb_ary_push(a, r.format);
return a;
}
extern "C"
void Init_route(VALUE nyara, VALUE ext) {
nyara_http_methods = rb_const_get(nyara, rb_intern("HTTP_METHODS"));
id_to_s = rb_intern("to_s");
u8_enc = rb_utf8_encoding();
str_html = rb_str_new2("html");
OBJ_FREEZE(str_html);
rb_gc_register_mark_object(str_html);
onig_region_init(®ion);
rb_define_singleton_method(ext, "register_route", RUBY_METHOD_FUNC(ext_register_route), 1);
rb_define_singleton_method(ext, "clear_route", RUBY_METHOD_FUNC(ext_clear_route), 0);
// for test
rb_define_singleton_method(ext, "list_route", RUBY_METHOD_FUNC(ext_list_route), 0);
rb_define_singleton_method(ext, "lookup_route", RUBY_METHOD_FUNC(ext_lookup_route), 3);
}
<commit_msg>fix missing isalnum in linux<commit_after>extern "C" {
#include "nyara.h"
}
#include <ruby/re.h>
#include <ruby/encoding.h>
#include <vector>
#include <map>
#include "inc/str_intern.h"
#ifndef isalnum
#include <cctype>
#endif
struct RouteEntry {
// note on order: scope is supposed to be the last, but when searching, is_sub is checked first
bool is_sub; // = last_prefix.start_with? prefix
char* prefix;
long prefix_len;
regex_t *suffix_re;
VALUE controller;
VALUE id; // symbol
VALUE accept_exts; // {ext => true}
VALUE accept_mimes; // [[m1, m2, ext]]
std::vector<ID> conv;
VALUE scope;
char* suffix; // only for inspect
long suffix_len;
// don't make it destructor, or it could be called twice if on stack
void dealloc() {
if (prefix) {
xfree(prefix);
prefix = NULL;
}
if (suffix_re) {
onig_free(suffix_re);
suffix_re = NULL;
}
if (suffix) {
xfree(suffix);
suffix = NULL;
}
}
};
typedef std::vector<RouteEntry> RouteEntries;
static std::map<enum http_method, RouteEntries*> route_map;
static OnigRegion region; // we can reuse the region without worrying thread safety
static ID id_to_s;
static rb_encoding* u8_enc;
static VALUE str_html;
static VALUE nyara_http_methods;
static bool start_with(const char* a, long a_len, const char* b, long b_len) {
if (b_len > a_len) {
return false;
}
for (size_t i = 0; i < b_len; i++) {
if (a[i] != b[i]) {
return false;
}
}
return true;
}
static enum http_method canonicalize_http_method(VALUE m) {
VALUE method_num;
if (TYPE(m) == T_STRING) {
method_num = rb_hash_aref(nyara_http_methods, m);
} else {
method_num = m;
}
Check_Type(method_num, T_FIXNUM);
return (enum http_method)FIX2INT(method_num);
}
static VALUE ext_clear_route(VALUE req) {
for (auto i = route_map.begin(); i != route_map.end(); ++i) {
RouteEntries* entries = i->second;
for (auto j = entries->begin(); j != entries->end(); ++j) {
j->dealloc();
}
delete entries;
}
route_map.clear();
return Qnil;
}
static VALUE ext_register_route(VALUE self, VALUE v_e) {
// get route entries
enum http_method m = canonicalize_http_method(rb_iv_get(v_e, "@http_method"));
RouteEntries* route_entries;
auto map_iter = route_map.find(m);
if (map_iter == route_map.end()) {
route_entries = new RouteEntries();
route_map[m] = route_entries;
} else {
route_entries = map_iter->second;
}
// prefix
VALUE v_prefix = rb_iv_get(v_e, "@prefix");
long prefix_len = RSTRING_LEN(v_prefix);
char* prefix = ALLOC_N(char, prefix_len);
memcpy(prefix, RSTRING_PTR(v_prefix), prefix_len);
// check if prefix is substring of last entry
bool is_sub = false;
if (route_entries->size()) {
is_sub = start_with(route_entries->rbegin()->prefix, route_entries->rbegin()->prefix_len, prefix, prefix_len);
}
// suffix
VALUE v_suffix = rb_iv_get(v_e, "@suffix");
long suffix_len = RSTRING_LEN(v_suffix);
char* suffix = ALLOC_N(char, suffix_len);
memcpy(suffix, RSTRING_PTR(v_suffix), suffix_len);
regex_t* suffix_re;
OnigErrorInfo err_info;
onig_new(&suffix_re, (const UChar*)suffix, (const UChar*)(suffix + suffix_len),
ONIG_OPTION_NONE, ONIG_ENCODING_ASCII, ONIG_SYNTAX_RUBY, &err_info);
std::vector<ID> _conv;
RouteEntry e;
e.is_sub = is_sub;
e.prefix = prefix;
e.prefix_len = prefix_len;
e.suffix_re = suffix_re;
e.suffix = suffix;
e.suffix_len = suffix_len;
e.controller = rb_iv_get(v_e, "@controller");
e.id = rb_iv_get(v_e, "@id");
e.conv = _conv;
e.scope = rb_iv_get(v_e, "@scope");
// conv
VALUE v_conv = rb_iv_get(v_e, "@conv");
VALUE* conv_ptr = RARRAY_PTR(v_conv);
long conv_len = RARRAY_LEN(v_conv);
if (onig_number_of_captures(suffix_re) != conv_len) {
e.dealloc();
rb_raise(rb_eRuntimeError, "number of captures mismatch");
}
for (long i = 0; i < conv_len; i++) {
ID conv_id = SYM2ID(conv_ptr[i]);
e.conv.push_back(conv_id);
}
// accept
e.accept_exts = rb_iv_get(v_e, "@accept_exts");
e.accept_mimes = rb_iv_get(v_e, "@accept_mimes");
route_entries->push_back(e);
return Qnil;
}
static VALUE ext_list_route(VALUE self) {
// note: prevent leak with init nil
volatile VALUE arr = Qnil;
volatile VALUE e = Qnil;
volatile VALUE prefix = Qnil;
volatile VALUE conv = Qnil;
volatile VALUE route_hash = rb_hash_new();
for (auto j = route_map.begin(); j != route_map.end(); j++) {
RouteEntries* route_entries = j->second;
VALUE arr = rb_ary_new();
rb_hash_aset(route_hash, rb_str_new2(http_method_str(j->first)), arr);
for (auto i = route_entries->begin(); i != route_entries->end(); i++) {
e = rb_ary_new();
rb_ary_push(e, i->is_sub ? Qtrue : Qfalse);
rb_ary_push(e, i->scope);
rb_ary_push(e, rb_str_new(i->prefix, i->prefix_len));
rb_ary_push(e, rb_str_new(i->suffix, i->suffix_len));
rb_ary_push(e, i->controller);
rb_ary_push(e, i->id);
conv = rb_ary_new();
for (size_t j = 0; j < i->conv.size(); j++) {
rb_ary_push(conv, ID2SYM(i->conv[j]));
}
rb_ary_push(e, conv);
rb_ary_push(arr, e);
}
}
return route_hash;
}
static VALUE build_args(const char* suffix, std::vector<ID>& conv) {
volatile VALUE args = rb_ary_new();
volatile VALUE str = rb_str_new2("");
long last_len = 0;
for (size_t j = 0; j < conv.size(); j++) {
const char* capture_ptr = suffix + region.beg[j+1];
long capture_len = region.end[j+1] - region.beg[j+1];
if (conv[j] == id_to_s) {
rb_ary_push(args, rb_enc_str_new(capture_ptr, capture_len, u8_enc));
} else if (capture_len == 0) {
rb_ary_push(args, Qnil);
} else {
if (capture_len > last_len) {
RESIZE_CAPA(str, capture_len);
last_len = capture_len;
}
memcpy(RSTRING_PTR(str), capture_ptr, capture_len);
STR_SET_LEN(str, capture_len);
rb_ary_push(args, rb_funcall(str, conv[j], 0)); // hex, to_i, to_f
}
}
return args;
}
static VALUE extract_ext(const char* s, long len) {
if (s[0] != '.') {
return Qnil;
}
s++;
len--;
for (long i = 0; i < len; i++) {
if (!isalnum(s[i])) {
return Qnil;
}
}
return rb_str_new(s, len);
}
extern "C"
RouteResult nyara_lookup_route(enum http_method method_num, VALUE vpath, VALUE accept_arr) {
RouteResult r = {Qnil, Qnil, Qnil, Qnil};
auto map_iter = route_map.find(method_num);
if (map_iter == route_map.end()) {
return r;
}
RouteEntries* route_entries = map_iter->second;
const char* path = RSTRING_PTR(vpath);
long len = RSTRING_LEN(vpath);
// must iterate all
bool last_matched = false;
auto i = route_entries->begin();
for (; i != route_entries->end(); ++i) {
bool matched;
if (i->is_sub && last_matched) { // save a bit compare
matched = last_matched;
} else {
matched = start_with(path, len, i->prefix, i->prefix_len);
}
last_matched = matched;
if (/* prefix */ matched) {
const char* suffix = path + i->prefix_len;
long suffix_len = len - i->prefix_len;
if (i->suffix_len == 0) {
if (suffix_len) {
r.format = extract_ext(suffix, suffix_len);
if (r.format == Qnil) {
break;
}
}
r.args = rb_ary_new3(1, i->id);
r.controller = i->controller;
break;
} else {
long matched_len = onig_match(i->suffix_re, (const UChar*)suffix, (const UChar*)(suffix + suffix_len),
(const UChar*)suffix, ®ion, 0);
if (matched_len > 0) {
if (matched_len < suffix_len) {
r.format = extract_ext(suffix + matched_len, suffix_len);
if (r.format == Qnil) {
break;
}
}
r.args = build_args(suffix, i->conv);
rb_ary_push(r.args, i->id);
r.controller = i->controller;
break;
}
}
}
}
if (r.controller != Qnil) {
r.scope = i->scope;
if (r.format == Qnil) {
if (i->accept_exts == Qnil) {
r.format = str_html; // not configured, just plain html
} else {
r.format = ext_mime_match(Qnil, accept_arr, i->accept_mimes);
if (r.format == Qnil) {
r.controller = Qnil; // reject if mime mismatch
}
}
} else {
if (i->accept_exts != Qnil) {
if (!RTEST(rb_hash_aref(i->accept_exts, r.format))) {
r.controller = Qnil; // reject if path ext mismatch
}
}
}
}
return r;
}
static VALUE ext_lookup_route(VALUE self, VALUE method, VALUE path, VALUE accept_arr) {
enum http_method method_num = canonicalize_http_method(method);
volatile RouteResult r = nyara_lookup_route(method_num, path, accept_arr);
volatile VALUE a = rb_ary_new();
rb_ary_push(a, r.scope);
rb_ary_push(a, r.controller);
rb_ary_push(a, r.args);
rb_ary_push(a, r.format);
return a;
}
extern "C"
void Init_route(VALUE nyara, VALUE ext) {
nyara_http_methods = rb_const_get(nyara, rb_intern("HTTP_METHODS"));
id_to_s = rb_intern("to_s");
u8_enc = rb_utf8_encoding();
str_html = rb_str_new2("html");
OBJ_FREEZE(str_html);
rb_gc_register_mark_object(str_html);
onig_region_init(®ion);
rb_define_singleton_method(ext, "register_route", RUBY_METHOD_FUNC(ext_register_route), 1);
rb_define_singleton_method(ext, "clear_route", RUBY_METHOD_FUNC(ext_clear_route), 0);
// for test
rb_define_singleton_method(ext, "list_route", RUBY_METHOD_FUNC(ext_list_route), 0);
rb_define_singleton_method(ext, "lookup_route", RUBY_METHOD_FUNC(ext_lookup_route), 3);
}
<|endoftext|>
|
<commit_before>#include <algorithm>
#include <iomanip>
#include <ios>
#include <iostream>
#include <map>
#include <sstream>
#include <string>
#include <vector>
#include <stdint.h>
#include <stdio.h>
namespace {
const char kToplevel[] = "$total$";
const char kOverhead[] = "$overhead$";
const char kIgnore[] = "$ignore$";
struct OpInfo {
std::string op_type;
std::string op_name;
std::string parent_type;
std::string parent_name;
// number of times called
int64_t count;
// ticks used (processor specific, no fixed time interval)
int64_t ticks;
// nsec is actually only measured for $total$;
// it's (approximated) calculated for all others
double nsec;
// percentage of total ticks, [0.0..1.0]
double percent;
// ticks/nsec/percent used by this op alone (not including callees)
int64_t ticks_only;
double nsec_only;
double percent_only;
OpInfo()
: count(0),
ticks(0),
nsec(0.0),
percent(0.0),
ticks_only(0),
nsec_only(0.0),
percent_only(0.0) {}
};
// Outer map is keyed by function name,
// inner map is keyed by op_type + op_name
typedef std::map<std::string, OpInfo> OpInfoMap;
typedef std::map<std::string, OpInfoMap> FuncInfoMap;
std::string qualified_name(const std::string& op_type, const std::string& op_name) {
// Arbitrary, just join type + name
return op_type + ":" + op_name;
}
// How is it posible that there is no string-split function in the C++
// standard library?
std::vector<std::string> Split(const std::string& s, char delim) {
std::vector<std::string> v;
std::istringstream ss(s);
std::string item;
while (std::getline(ss, item, delim)) {
v.push_back(item);
}
return v;
}
bool HasOpt(char** begin, char** end, const std::string& opt) {
return std::find(begin, end, opt) != end;
}
// look for string "opt"; if found, return subsequent string;
// if not found, return empty string.
std::string GetOpt(char** begin, char** end, const std::string& opt) {
char** it = std::find(begin, end, opt);
if (it != end && ++it != end) {
return std::string(*it);
}
return std::string();
}
void ProcessLine(const std::string& s, FuncInfoMap& info, bool accumulate_runs) {
std::vector<std::string> v = Split(s, ' ');
if (v.size() < 8) {
return;
}
// Some environments (e.g. Android logging) will emit a prefix
// for each line; skip the first few words we see before
// deciding to ignore the line.
int first = -1;
for (int i = 0; i < 4; ++i) {
if (v[i] == "halide_profiler") {
first = i;
break;
}
}
if (first < 0) {
return;
}
const std::string& metric = v[first + 1];
const std::string& func_name = v[first + 2];
const std::string& op_type = v[first + 3];
const std::string& op_name = v[first + 4];
const std::string& parent_type = v[first + 5];
const std::string& parent_name = v[first + 6];
if (op_type == kIgnore || op_name == kIgnore) {
return;
}
std::istringstream value_stream(v[first + 7]);
int64_t value;
value_stream >> value;
OpInfoMap& op_info_map = info[func_name];
OpInfo& op_info = op_info_map[qualified_name(op_type, op_name)];
op_info.op_type = op_type;
op_info.op_name = op_name;
op_info.parent_type = parent_type;
op_info.parent_name = parent_name;
if (metric == "count") {
op_info.count = (accumulate_runs ? op_info.count : 0) + value;
} else if (metric == "ticks") {
op_info.ticks = (accumulate_runs ? op_info.ticks : 0) + value;
} else if (metric == "nsec") {
op_info.nsec = (accumulate_runs ? op_info.nsec : 0) + value;
}
}
typedef std::map<std::string, std::vector<OpInfo*> > ChildMap;
int64_t AdjustOverhead(OpInfo& op_info, ChildMap& child_map, double overhead_ticks_avg) {
int64_t overhead_ticks = op_info.count * overhead_ticks_avg;
op_info.ticks_only -= overhead_ticks;
std::string qual_name = qualified_name(op_info.op_type, op_info.op_name);
const std::vector<OpInfo*>& children = child_map[qual_name];
for (std::vector<OpInfo*>::const_iterator it = children.begin(); it != children.end(); ++it) {
OpInfo* c = *it;
int64_t child_overhead = AdjustOverhead(*c, child_map, overhead_ticks_avg);
overhead_ticks += child_overhead;
}
op_info.ticks -= overhead_ticks;
return overhead_ticks;
}
void FinishOpInfo(OpInfoMap& op_info_map, bool adjust_for_overhead) {
std::string toplevel_qual_name = qualified_name(kToplevel, kToplevel);
OpInfo& total = op_info_map[toplevel_qual_name];
total.percent = 1.0;
double ticks_per_nsec = (double)total.ticks / (double)total.nsec;
// Note that overhead (if present) is measured outside the rest
// of the "total", so it should not be included (or subtracted from)
// the total.
double overhead_ticks_avg = 0;
std::string overhead_qual_name = qualified_name(kOverhead, kOverhead);
OpInfoMap::iterator it = op_info_map.find(overhead_qual_name);
if (it != op_info_map.end()) {
OpInfo overhead = it->second;
overhead_ticks_avg = (double)overhead.ticks / (double)overhead.count;
op_info_map.erase(it);
}
ChildMap child_map;
for (OpInfoMap::iterator o = op_info_map.begin(); o != op_info_map.end(); ++o) {
OpInfo& op_info = o->second;
std::string parent_qual_name = qualified_name(op_info.parent_type, op_info.parent_name);
child_map[parent_qual_name].push_back(&op_info);
}
for (OpInfoMap::iterator o = op_info_map.begin(); o != op_info_map.end(); ++o) {
OpInfo& op_info = o->second;
op_info.ticks_only = op_info.ticks;
const std::vector<OpInfo*>& children = child_map[o->first];
for (std::vector<OpInfo*>::const_iterator it = children.begin(); it != children.end(); ++it) {
OpInfo* c = *it;
op_info.ticks_only -= c->ticks;
}
}
if (adjust_for_overhead) {
// Adjust values to account for profiling overhead
AdjustOverhead(total, child_map, overhead_ticks_avg);
}
// Calc the derived fields
for (OpInfoMap::iterator o = op_info_map.begin(); o != op_info_map.end(); ++o) {
OpInfo& op_info = o->second;
op_info.nsec = op_info.ticks / ticks_per_nsec;
op_info.nsec_only = op_info.ticks_only / ticks_per_nsec;
op_info.percent = (double)op_info.ticks / (double)total.ticks;
op_info.percent_only = (double)op_info.ticks_only / (double)total.ticks;
}
}
template <typename CmpFunc>
std::vector<OpInfo> SortOpInfo(const OpInfoMap& op_info_map, CmpFunc cmp) {
std::vector<OpInfo> v;
for (OpInfoMap::const_iterator o = op_info_map.begin(); o != op_info_map.end(); ++o) {
v.push_back(o->second);
}
// Note: using reverse iterators to get a descending sort
std::sort(v.rbegin(), v.rend(), cmp);
return v;
}
bool by_count(const OpInfo& a, const OpInfo& b) { return a.count < b.count; }
bool by_ticks(const OpInfo& a, const OpInfo& b) { return a.ticks < b.ticks; }
bool by_ticks_only(const OpInfo& a, const OpInfo& b) { return a.ticks_only < b.ticks_only; }
} // namespace
int main(int argc, char** argv) {
if (HasOpt(argv, argv + argc, "-h")) {
printf("HalideProf [-f funcname] [-sort c|t|to] [-top N] [-overhead=0|1] [-accumulate=[0|1]] < profiledata\n");
return 0;
}
std::string func_name_filter = GetOpt(argv, argv + argc, "-f");
bool (*sort_by_func)(const OpInfo& a, const OpInfo& b);
std::string sort_by = GetOpt(argv, argv + argc, "-sort");
if (sort_by.empty() || sort_by == "to") {
sort_by_func = by_ticks_only;
} else if (sort_by == "t") {
sort_by_func = by_ticks;
} else if (sort_by == "c") {
sort_by_func = by_count;
} else {
std::cerr << "Unknown value for -sort: " << sort_by << "\n";
exit(-1);
}
int32_t top_n = 10;
std::string top_n_str = GetOpt(argv, argv + argc, "-top");
if (!top_n_str.empty()) {
std::istringstream(top_n_str) >> top_n;
}
// It's rare that you wouldn't want to try to adjust the times
// to minimize the effect profiling overhead, but just in case,
// allow -overhead 0
int32_t adjust_for_overhead = 1;
std::string adjust_for_overhead_str = GetOpt(argv, argv + argc, "-overhead");
if (!adjust_for_overhead_str.empty()) {
std::istringstream(adjust_for_overhead_str) >> adjust_for_overhead;
}
int32_t accumulate_runs = 0;
std::string accumulate_runs_str = GetOpt(argv, argv + argc, "-accumulate");
if (!accumulate_runs_str.empty()) {
std::istringstream(accumulate_runs_str) >> accumulate_runs;
}
FuncInfoMap func_info_map;
std::string line;
while (std::getline(std::cin, line)) {
ProcessLine(line, func_info_map, accumulate_runs);
}
for (FuncInfoMap::iterator f = func_info_map.begin(); f != func_info_map.end(); ++f) {
FinishOpInfo(f->second, adjust_for_overhead != 0);
}
for (FuncInfoMap::iterator f = func_info_map.begin(); f != func_info_map.end(); ++f) {
const std::string& func_name = f->first;
if (!func_name_filter.empty() && func_name_filter != func_name) {
continue;
}
std::cout << "Func: " << func_name << "\n";
std::cout << "--------------------------\n";
std::cout
<< std::setw(10) << std::left << "op_type"
<< std::setw(40) << std::left << "op_name"
<< std::setw(16) << std::right << "count"
<< std::setw(16) << "ticks-cum"
<< std::setw(12) << "msec-cum"
<< std::setw(8) << std::fixed << "%-cum"
<< std::setw(16) << "ticks-only"
<< std::setw(12) << "msec-only"
<< std::setw(8) << std::fixed << "%-only"
<< "\n";
std::vector<OpInfo> op_info = SortOpInfo(f->second, sort_by_func);
for (std::vector<OpInfo>::const_iterator o = op_info.begin(); o != op_info.end(); ++o) {
const OpInfo& op_info = *o;
std::cout
<< std::setw(10) << std::left << op_info.op_type
<< std::setw(40) << std::left << op_info.op_name
<< std::setw(16) << std::right << op_info.count
<< std::setw(16) << op_info.ticks
<< std::setw(12) << std::setprecision(2) << std::fixed << (op_info.nsec / 1000000.0)
<< std::setw(8) << std::setprecision(2) << std::fixed << (op_info.percent * 100.0)
<< std::setw(16) << op_info.ticks_only
<< std::setw(12) << std::setprecision(2) << std::fixed << (op_info.nsec_only / 1000000.0)
<< std::setw(8) << std::setprecision(2) << std::fixed << (op_info.percent_only * 100.0)
<< "\n";
if (--top_n <= 0) {
break;
}
}
}
}
<commit_msg>Adjusted overhead adjustment<commit_after>#include <algorithm>
#include <iomanip>
#include <ios>
#include <iostream>
#include <map>
#include <sstream>
#include <string>
#include <vector>
#include <stdint.h>
#include <stdio.h>
namespace {
const char kToplevel[] = "$total$";
const char kOverhead[] = "$overhead$";
const char kIgnore[] = "$ignore$";
struct OpInfo {
std::string op_type;
std::string op_name;
std::string parent_type;
std::string parent_name;
// number of times called
int64_t count;
// ticks used (processor specific, no fixed time interval)
int64_t ticks;
// nsec is actually only measured for $total$;
// it's (approximated) calculated for all others
double nsec;
// percentage of total ticks, [0.0..1.0]
double percent;
// ticks/nsec/percent used by this op alone (not including callees)
int64_t ticks_only;
double nsec_only;
double percent_only;
OpInfo()
: count(0),
ticks(0),
nsec(0.0),
percent(0.0),
ticks_only(0),
nsec_only(0.0),
percent_only(0.0) {}
};
// Outer map is keyed by function name,
// inner map is keyed by op_type + op_name
typedef std::map<std::string, OpInfo> OpInfoMap;
typedef std::map<std::string, OpInfoMap> FuncInfoMap;
std::string qualified_name(const std::string& op_type, const std::string& op_name) {
// Arbitrary, just join type + name
return op_type + ":" + op_name;
}
// How is it posible that there is no string-split function in the C++
// standard library?
std::vector<std::string> Split(const std::string& s, char delim) {
std::vector<std::string> v;
std::istringstream ss(s);
std::string item;
while (std::getline(ss, item, delim)) {
v.push_back(item);
}
return v;
}
bool HasOpt(char** begin, char** end, const std::string& opt) {
return std::find(begin, end, opt) != end;
}
// look for string "opt"; if found, return subsequent string;
// if not found, return empty string.
std::string GetOpt(char** begin, char** end, const std::string& opt) {
char** it = std::find(begin, end, opt);
if (it != end && ++it != end) {
return std::string(*it);
}
return std::string();
}
void ProcessLine(const std::string& s, FuncInfoMap& info, bool accumulate_runs) {
std::vector<std::string> v = Split(s, ' ');
if (v.size() < 8) {
return;
}
// Some environments (e.g. Android logging) will emit a prefix
// for each line; skip the first few words we see before
// deciding to ignore the line.
int first = -1;
for (int i = 0; i < 4; ++i) {
if (v[i] == "halide_profiler") {
first = i;
break;
}
}
if (first < 0) {
return;
}
const std::string& metric = v[first + 1];
const std::string& func_name = v[first + 2];
const std::string& op_type = v[first + 3];
const std::string& op_name = v[first + 4];
const std::string& parent_type = v[first + 5];
const std::string& parent_name = v[first + 6];
if (op_type == kIgnore || op_name == kIgnore) {
return;
}
std::istringstream value_stream(v[first + 7]);
int64_t value;
value_stream >> value;
OpInfoMap& op_info_map = info[func_name];
OpInfo& op_info = op_info_map[qualified_name(op_type, op_name)];
op_info.op_type = op_type;
op_info.op_name = op_name;
op_info.parent_type = parent_type;
op_info.parent_name = parent_name;
if (metric == "count") {
op_info.count = (accumulate_runs ? op_info.count : 0) + value;
} else if (metric == "ticks") {
op_info.ticks = (accumulate_runs ? op_info.ticks : 0) + value;
} else if (metric == "nsec") {
op_info.nsec = (accumulate_runs ? op_info.nsec : 0) + value;
}
}
typedef std::map<std::string, std::vector<OpInfo*> > ChildMap;
int64_t AdjustOverhead(OpInfo& op_info, ChildMap& child_map, double overhead_ticks_avg) {
int64_t overhead_ticks = op_info.count * overhead_ticks_avg;
op_info.ticks_only -= overhead_ticks;
std::string qual_name = qualified_name(op_info.op_type, op_info.op_name);
const std::vector<OpInfo*>& children = child_map[qual_name];
for (std::vector<OpInfo*>::const_iterator it = children.begin(); it != children.end(); ++it) {
OpInfo* c = *it;
int64_t child_overhead = AdjustOverhead(*c, child_map, overhead_ticks_avg);
overhead_ticks += child_overhead;
}
op_info.ticks -= overhead_ticks;
return overhead_ticks;
}
void FinishOpInfo(OpInfoMap& op_info_map, bool adjust_for_overhead) {
std::string toplevel_qual_name = qualified_name(kToplevel, kToplevel);
OpInfo& total = op_info_map[toplevel_qual_name];
total.percent = 1.0;
double ticks_per_nsec = (double)total.ticks / (double)total.nsec;
// Note that overhead (if present) is measured outside the rest
// of the "total", so it should not be included (or subtracted from)
// the total.
double overhead_ticks_avg = 0;
std::string overhead_qual_name = qualified_name(kOverhead, kOverhead);
OpInfoMap::iterator it = op_info_map.find(overhead_qual_name);
if (it != op_info_map.end()) {
OpInfo overhead = it->second;
overhead_ticks_avg = (double)overhead.ticks / ((double)overhead.count * 2.0);
op_info_map.erase(it);
}
ChildMap child_map;
for (OpInfoMap::iterator o = op_info_map.begin(); o != op_info_map.end(); ++o) {
OpInfo& op_info = o->second;
std::string parent_qual_name = qualified_name(op_info.parent_type, op_info.parent_name);
child_map[parent_qual_name].push_back(&op_info);
}
for (OpInfoMap::iterator o = op_info_map.begin(); o != op_info_map.end(); ++o) {
OpInfo& op_info = o->second;
op_info.ticks_only = op_info.ticks;
const std::vector<OpInfo*>& children = child_map[o->first];
for (std::vector<OpInfo*>::const_iterator it = children.begin(); it != children.end(); ++it) {
OpInfo* c = *it;
op_info.ticks_only -= c->ticks;
}
}
if (adjust_for_overhead) {
// Adjust values to account for profiling overhead
AdjustOverhead(total, child_map, overhead_ticks_avg);
}
// Calc the derived fields
for (OpInfoMap::iterator o = op_info_map.begin(); o != op_info_map.end(); ++o) {
OpInfo& op_info = o->second;
op_info.nsec = op_info.ticks / ticks_per_nsec;
op_info.nsec_only = op_info.ticks_only / ticks_per_nsec;
op_info.percent = (double)op_info.ticks / (double)total.ticks;
op_info.percent_only = (double)op_info.ticks_only / (double)total.ticks;
}
}
template <typename CmpFunc>
std::vector<OpInfo> SortOpInfo(const OpInfoMap& op_info_map, CmpFunc cmp) {
std::vector<OpInfo> v;
for (OpInfoMap::const_iterator o = op_info_map.begin(); o != op_info_map.end(); ++o) {
v.push_back(o->second);
}
// Note: using reverse iterators to get a descending sort
std::sort(v.rbegin(), v.rend(), cmp);
return v;
}
bool by_count(const OpInfo& a, const OpInfo& b) { return a.count < b.count; }
bool by_ticks(const OpInfo& a, const OpInfo& b) { return a.ticks < b.ticks; }
bool by_ticks_only(const OpInfo& a, const OpInfo& b) { return a.ticks_only < b.ticks_only; }
} // namespace
int main(int argc, char** argv) {
if (HasOpt(argv, argv + argc, "-h")) {
printf("HalideProf [-f funcname] [-sort c|t|to] [-top N] [-overhead=0|1] [-accumulate=[0|1]] < profiledata\n");
return 0;
}
std::string func_name_filter = GetOpt(argv, argv + argc, "-f");
bool (*sort_by_func)(const OpInfo& a, const OpInfo& b);
std::string sort_by = GetOpt(argv, argv + argc, "-sort");
if (sort_by.empty() || sort_by == "to") {
sort_by_func = by_ticks_only;
} else if (sort_by == "t") {
sort_by_func = by_ticks;
} else if (sort_by == "c") {
sort_by_func = by_count;
} else {
std::cerr << "Unknown value for -sort: " << sort_by << "\n";
exit(-1);
}
int32_t top_n = 10;
std::string top_n_str = GetOpt(argv, argv + argc, "-top");
if (!top_n_str.empty()) {
std::istringstream(top_n_str) >> top_n;
}
// It's rare that you wouldn't want to try to adjust the times
// to minimize the effect profiling overhead, but just in case,
// allow -overhead 0
int32_t adjust_for_overhead = 1;
std::string adjust_for_overhead_str = GetOpt(argv, argv + argc, "-overhead");
if (!adjust_for_overhead_str.empty()) {
std::istringstream(adjust_for_overhead_str) >> adjust_for_overhead;
}
int32_t accumulate_runs = 0;
std::string accumulate_runs_str = GetOpt(argv, argv + argc, "-accumulate");
if (!accumulate_runs_str.empty()) {
std::istringstream(accumulate_runs_str) >> accumulate_runs;
}
FuncInfoMap func_info_map;
std::string line;
while (std::getline(std::cin, line)) {
ProcessLine(line, func_info_map, accumulate_runs);
}
for (FuncInfoMap::iterator f = func_info_map.begin(); f != func_info_map.end(); ++f) {
FinishOpInfo(f->second, adjust_for_overhead != 0);
}
for (FuncInfoMap::iterator f = func_info_map.begin(); f != func_info_map.end(); ++f) {
const std::string& func_name = f->first;
if (!func_name_filter.empty() && func_name_filter != func_name) {
continue;
}
std::cout << "Func: " << func_name << "\n";
std::cout << "--------------------------\n";
std::cout
<< std::setw(10) << std::left << "op_type"
<< std::setw(40) << std::left << "op_name"
<< std::setw(16) << std::right << "count"
<< std::setw(16) << "ticks-cum"
<< std::setw(12) << "msec-cum"
<< std::setw(8) << std::fixed << "%-cum"
<< std::setw(16) << "ticks-only"
<< std::setw(12) << "msec-only"
<< std::setw(8) << std::fixed << "%-only"
<< "\n";
std::vector<OpInfo> op_info = SortOpInfo(f->second, sort_by_func);
for (std::vector<OpInfo>::const_iterator o = op_info.begin(); o != op_info.end(); ++o) {
const OpInfo& op_info = *o;
std::cout
<< std::setw(10) << std::left << op_info.op_type
<< std::setw(40) << std::left << op_info.op_name
<< std::setw(16) << std::right << op_info.count
<< std::setw(16) << op_info.ticks
<< std::setw(12) << std::setprecision(2) << std::fixed << (op_info.nsec / 1000000.0)
<< std::setw(8) << std::setprecision(2) << std::fixed << (op_info.percent * 100.0)
<< std::setw(16) << op_info.ticks_only
<< std::setw(12) << std::setprecision(2) << std::fixed << (op_info.nsec_only / 1000000.0)
<< std::setw(8) << std::setprecision(2) << std::fixed << (op_info.percent_only * 100.0)
<< "\n";
if (--top_n <= 0) {
break;
}
}
}
}
<|endoftext|>
|
<commit_before>#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
bool socketError = false;
int DDV_Listen(int port){
int s = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(port);//port 8888
inet_pton(AF_INET, "0.0.0.0", &addr.sin_addr);//listen on all interfaces
int ret = bind(s, (sockaddr*)&addr, sizeof(addr));//bind to all interfaces, chosen port
if (ret == 0){
ret = listen(s, 100);//start listening, backlog of 100 allowed
if (ret == 0){
return s;
}else{
printf("Listen failed! Error: %s\n", strerror(errno));
close(s);
return 0;
}
}else{
printf("Binding failed! Error: %s\n", strerror(errno));
close(s);
return 0;
}
}
int DDV_Accept(int sock){
return accept(sock, 0, 0);
}
bool DDV_write(void * buffer, int width, int count, int sock){
bool r = (send(sock, buffer, width*count, 0) == width*count);
if (!r){socketError = true}
return r;
}
bool DDV_read(void * buffer, int width, int count, int sock){
bool r = (recv(sock, buffer, width*count, 0) == width*count);
if (!r){socketError = true}
return r;
}
<commit_msg>Nog een poging...<commit_after>#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
bool socketError = false;
int DDV_Listen(int port){
int s = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(port);//port 8888
inet_pton(AF_INET, "0.0.0.0", &addr.sin_addr);//listen on all interfaces
int ret = bind(s, (sockaddr*)&addr, sizeof(addr));//bind to all interfaces, chosen port
if (ret == 0){
ret = listen(s, 100);//start listening, backlog of 100 allowed
if (ret == 0){
return s;
}else{
printf("Listen failed! Error: %s\n", strerror(errno));
close(s);
return 0;
}
}else{
printf("Binding failed! Error: %s\n", strerror(errno));
close(s);
return 0;
}
}
int DDV_Accept(int sock){
return accept(sock, 0, 0);
}
bool DDV_write(void * buffer, int width, int count, int sock){
bool r = (send(sock, buffer, width*count, 0) == width*count);
if (!r){socketError = true;}
return r;
}
bool DDV_read(void * buffer, int width, int count, int sock){
bool r = (recv(sock, buffer, width*count, 0) == width*count);
if (!r){socketError = true;}
return r;
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2014 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "include/core/SkExecutor.h"
#include "include/gpu/GrContextOptions.h"
#include "tools/flags/CommonFlags.h"
DEFINE_int(gpuThreads,
2,
"Create this many extra threads to assist with GPU work, "
"including software path rendering. Defaults to two.");
static DEFINE_bool(cachePathMasks, true,
"Allows path mask textures to be cached in GPU configs.");
static DEFINE_bool(allPathsVolatile, false,
"Causes all GPU paths to be processed as if 'setIsVolatile' had been called.");
static DEFINE_bool(gs, true, "Enables support for geometry shaders (if hw allows).");
static DEFINE_bool(hwtess, false, "Enables support for tessellation shaders (if hw allows.).");
static DEFINE_int(maxTessellationSegments, 0,
"Overrides the max number of tessellation segments supported by the caps.");
static DEFINE_bool(alwaysHwTess, false,
"Always try to use hardware tessellation, regardless of how small a path may be.");
static DEFINE_string(pr, "",
"Set of enabled gpu path renderers. Defined as a list of: "
"[~]none [~]dashline [~]ccpr [~]aahairline [~]aaconvex [~]aalinearizing "
"[~]small [~]tri [~]tess [~]all");
static DEFINE_int(internalSamples, 4, "Number of samples for internal draws that use MSAA.");
static DEFINE_bool(disableDriverCorrectnessWorkarounds, false,
"Disables all GPU driver correctness workarounds");
static DEFINE_bool(dontReduceOpsTaskSplitting, false,
"Don't reorder tasks to reduce render passes");
static DEFINE_int(gpuResourceCacheLimit, -1,
"Maximum number of bytes to use for budgeted GPU resources. "
"Default is -1, which means GrResourceCache::kDefaultMaxSize.");
static GpuPathRenderers get_named_pathrenderers_flags(const char* name) {
if (!strcmp(name, "none")) {
return GpuPathRenderers::kNone;
} else if (!strcmp(name, "dashline")) {
return GpuPathRenderers::kDashLine;
} else if (!strcmp(name, "ccpr")) {
return GpuPathRenderers::kCoverageCounting;
} else if (!strcmp(name, "aahairline")) {
return GpuPathRenderers::kAAHairline;
} else if (!strcmp(name, "aaconvex")) {
return GpuPathRenderers::kAAConvex;
} else if (!strcmp(name, "aalinearizing")) {
return GpuPathRenderers::kAALinearizing;
} else if (!strcmp(name, "small")) {
return GpuPathRenderers::kSmall;
} else if (!strcmp(name, "tri")) {
return GpuPathRenderers::kTriangulating;
} else if (!strcmp(name, "tess")) {
return GpuPathRenderers::kTessellation;
} else if (!strcmp(name, "default")) {
return GpuPathRenderers::kDefault;
}
SK_ABORT("error: unknown named path renderer \"%s\"\n", name);
}
static GpuPathRenderers collect_gpu_path_renderers_from_flags() {
if (FLAGS_pr.isEmpty()) {
return GpuPathRenderers::kDefault;
}
GpuPathRenderers gpuPathRenderers = ('~' == FLAGS_pr[0][0])
? GpuPathRenderers::kDefault
: GpuPathRenderers::kNone;
for (int i = 0; i < FLAGS_pr.count(); ++i) {
const char* name = FLAGS_pr[i];
if (name[0] == '~') {
gpuPathRenderers &= ~get_named_pathrenderers_flags(&name[1]);
} else {
gpuPathRenderers |= get_named_pathrenderers_flags(name);
}
}
return gpuPathRenderers;
}
void SetCtxOptionsFromCommonFlags(GrContextOptions* ctxOptions) {
static std::unique_ptr<SkExecutor> gGpuExecutor = (0 != FLAGS_gpuThreads)
? SkExecutor::MakeFIFOThreadPool(FLAGS_gpuThreads)
: nullptr;
ctxOptions->fExecutor = gGpuExecutor.get();
ctxOptions->fAllowPathMaskCaching = FLAGS_cachePathMasks;
ctxOptions->fAllPathsVolatile = FLAGS_allPathsVolatile;
ctxOptions->fSuppressGeometryShaders = !FLAGS_gs;
ctxOptions->fEnableExperimentalHardwareTessellation = FLAGS_hwtess;
ctxOptions->fMaxTessellationSegmentsOverride = FLAGS_maxTessellationSegments;
ctxOptions->fAlwaysPreferHardwareTessellation = FLAGS_alwaysHwTess;
ctxOptions->fGpuPathRenderers = collect_gpu_path_renderers_from_flags();
ctxOptions->fInternalMultisampleCount = FLAGS_internalSamples;
ctxOptions->fDisableDriverCorrectnessWorkarounds = FLAGS_disableDriverCorrectnessWorkarounds;
ctxOptions->fResourceCacheLimitOverride = FLAGS_gpuResourceCacheLimit;
ctxOptions->fReduceOpsTaskSplitting = GrContextOptions::Enable::kNo;
}
<commit_msg>Revert "Temporarily disable reordering on bots again"<commit_after>/*
* Copyright 2014 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "include/core/SkExecutor.h"
#include "include/gpu/GrContextOptions.h"
#include "tools/flags/CommonFlags.h"
DEFINE_int(gpuThreads,
2,
"Create this many extra threads to assist with GPU work, "
"including software path rendering. Defaults to two.");
static DEFINE_bool(cachePathMasks, true,
"Allows path mask textures to be cached in GPU configs.");
static DEFINE_bool(allPathsVolatile, false,
"Causes all GPU paths to be processed as if 'setIsVolatile' had been called.");
static DEFINE_bool(gs, true, "Enables support for geometry shaders (if hw allows).");
static DEFINE_bool(hwtess, false, "Enables support for tessellation shaders (if hw allows.).");
static DEFINE_int(maxTessellationSegments, 0,
"Overrides the max number of tessellation segments supported by the caps.");
static DEFINE_bool(alwaysHwTess, false,
"Always try to use hardware tessellation, regardless of how small a path may be.");
static DEFINE_string(pr, "",
"Set of enabled gpu path renderers. Defined as a list of: "
"[~]none [~]dashline [~]ccpr [~]aahairline [~]aaconvex [~]aalinearizing "
"[~]small [~]tri [~]tess [~]all");
static DEFINE_int(internalSamples, 4, "Number of samples for internal draws that use MSAA.");
static DEFINE_bool(disableDriverCorrectnessWorkarounds, false,
"Disables all GPU driver correctness workarounds");
static DEFINE_bool(dontReduceOpsTaskSplitting, false,
"Don't reorder tasks to reduce render passes");
static DEFINE_int(gpuResourceCacheLimit, -1,
"Maximum number of bytes to use for budgeted GPU resources. "
"Default is -1, which means GrResourceCache::kDefaultMaxSize.");
static GpuPathRenderers get_named_pathrenderers_flags(const char* name) {
if (!strcmp(name, "none")) {
return GpuPathRenderers::kNone;
} else if (!strcmp(name, "dashline")) {
return GpuPathRenderers::kDashLine;
} else if (!strcmp(name, "ccpr")) {
return GpuPathRenderers::kCoverageCounting;
} else if (!strcmp(name, "aahairline")) {
return GpuPathRenderers::kAAHairline;
} else if (!strcmp(name, "aaconvex")) {
return GpuPathRenderers::kAAConvex;
} else if (!strcmp(name, "aalinearizing")) {
return GpuPathRenderers::kAALinearizing;
} else if (!strcmp(name, "small")) {
return GpuPathRenderers::kSmall;
} else if (!strcmp(name, "tri")) {
return GpuPathRenderers::kTriangulating;
} else if (!strcmp(name, "tess")) {
return GpuPathRenderers::kTessellation;
} else if (!strcmp(name, "default")) {
return GpuPathRenderers::kDefault;
}
SK_ABORT("error: unknown named path renderer \"%s\"\n", name);
}
static GpuPathRenderers collect_gpu_path_renderers_from_flags() {
if (FLAGS_pr.isEmpty()) {
return GpuPathRenderers::kDefault;
}
GpuPathRenderers gpuPathRenderers = ('~' == FLAGS_pr[0][0])
? GpuPathRenderers::kDefault
: GpuPathRenderers::kNone;
for (int i = 0; i < FLAGS_pr.count(); ++i) {
const char* name = FLAGS_pr[i];
if (name[0] == '~') {
gpuPathRenderers &= ~get_named_pathrenderers_flags(&name[1]);
} else {
gpuPathRenderers |= get_named_pathrenderers_flags(name);
}
}
return gpuPathRenderers;
}
void SetCtxOptionsFromCommonFlags(GrContextOptions* ctxOptions) {
static std::unique_ptr<SkExecutor> gGpuExecutor = (0 != FLAGS_gpuThreads)
? SkExecutor::MakeFIFOThreadPool(FLAGS_gpuThreads)
: nullptr;
ctxOptions->fExecutor = gGpuExecutor.get();
ctxOptions->fAllowPathMaskCaching = FLAGS_cachePathMasks;
ctxOptions->fAllPathsVolatile = FLAGS_allPathsVolatile;
ctxOptions->fSuppressGeometryShaders = !FLAGS_gs;
ctxOptions->fEnableExperimentalHardwareTessellation = FLAGS_hwtess;
ctxOptions->fMaxTessellationSegmentsOverride = FLAGS_maxTessellationSegments;
ctxOptions->fAlwaysPreferHardwareTessellation = FLAGS_alwaysHwTess;
ctxOptions->fGpuPathRenderers = collect_gpu_path_renderers_from_flags();
ctxOptions->fInternalMultisampleCount = FLAGS_internalSamples;
ctxOptions->fDisableDriverCorrectnessWorkarounds = FLAGS_disableDriverCorrectnessWorkarounds;
ctxOptions->fResourceCacheLimitOverride = FLAGS_gpuResourceCacheLimit;
if (FLAGS_dontReduceOpsTaskSplitting) {
ctxOptions->fReduceOpsTaskSplitting = GrContextOptions::Enable::kNo;
} else {
ctxOptions->fReduceOpsTaskSplitting = GrContextOptions::Enable::kYes;
}
}
<|endoftext|>
|
<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// 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 <net/inet4>
#include <common.cxx>
using namespace std::string_literals;
extern lest::tests & specification();
CASE("MAC addresses can be compared")
{
const net::Ethernet::addr host_mac_address {0,240,34,255,45,11};
const net::Ethernet::addr host_mac_address_hex {0x00,0xf0,0x22,0xff,0x2d,0x0b};
const net::Ethernet::addr gateway_mac_address {0xb8,0xe8,0x56,0x4a,0x75,0x6e};
EXPECT_NOT(host_mac_address == gateway_mac_address);
EXPECT(host_mac_address == host_mac_address_hex);
}
CASE("MAC address string representation prints leading zeros")
{
const net::Ethernet::addr host_mac_address {0,240,34,255,45,11};
auto mac_address_string = host_mac_address.str();
EXPECT_NOT(mac_address_string == "0:f0:22:ff:2d:b");
EXPECT(mac_address_string == "00:f0:22:ff:2d:0b");
}
<commit_msg>test: Reduced include scope a bit<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// 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 <hw/mac_addr.hpp>
#include <common.cxx>
using namespace std::string_literals;
extern lest::tests & specification();
CASE("MAC addresses can be compared")
{
const hw::MAC_addr host_mac_address {0,240,34,255,45,11};
const hw::MAC_addr host_mac_address_hex {0x00,0xf0,0x22,0xff,0x2d,0x0b};
const hw::MAC_addr gateway_mac_address {0xb8,0xe8,0x56,0x4a,0x75,0x6e};
EXPECT_NOT(host_mac_address == gateway_mac_address);
EXPECT(host_mac_address == host_mac_address_hex);
}
CASE("MAC address string representation prints leading zeros")
{
const hw::MAC_addr host_mac_address {0,240,34,255,45,11};
auto mac_address_string = host_mac_address.str();
EXPECT_NOT(mac_address_string == "0:f0:22:ff:2d:b");
EXPECT(mac_address_string == "00:f0:22:ff:2d:0b");
}
<|endoftext|>
|
<commit_before>//===-- IOStream.cpp --------------------------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "IOStream.h"
#if defined(_WIN32)
#include <io.h>
#else
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>
#endif
#include <fstream>
#include <string>
#include <vector>
using namespace lldb_vscode;
StreamDescriptor::StreamDescriptor() {}
StreamDescriptor::StreamDescriptor(StreamDescriptor &&other) {
*this = std::move(other);
}
StreamDescriptor::~StreamDescriptor() {
if (!m_close)
return;
if (m_is_socket)
#if defined(_WIN32)
::closesocket(m_socket);
#else
::close(m_socket);
#endif
else
::close(m_fd);
}
StreamDescriptor &StreamDescriptor::operator=(StreamDescriptor &&other) {
m_close = other.m_close;
other.m_close = false;
m_is_socket = other.m_is_socket;
if (m_is_socket)
m_socket = other.m_socket;
else
m_fd = other.m_fd;
return *this;
}
StreamDescriptor StreamDescriptor::from_socket(SOCKET s, bool close) {
StreamDescriptor sd;
sd.m_is_socket = true;
sd.m_socket = s;
sd.m_close = close;
return sd;
}
StreamDescriptor StreamDescriptor::from_file(int fd, bool close) {
StreamDescriptor sd;
sd.m_is_socket = false;
sd.m_fd = fd;
sd.m_close = close;
return sd;
}
bool OutputStream::write_full(llvm::StringRef str) {
while (!str.empty()) {
int bytes_written = 0;
if (descriptor.m_is_socket)
bytes_written = ::send(descriptor.m_socket, str.data(), str.size(), 0);
else
bytes_written = ::write(descriptor.m_fd, str.data(), str.size());
if (bytes_written < 0) {
if (errno == EINTR || errno == EAGAIN)
continue;
return false;
}
str = str.drop_front(bytes_written);
}
return true;
}
bool InputStream::read_full(std::ofstream *log, size_t length,
std::string &text) {
std::string data;
data.resize(length);
char *ptr = &data[0];
while (length != 0) {
size_t bytes_read = 0;
if (descriptor.m_is_socket)
bytes_read = ::recv(descriptor.m_socket, ptr, length, 0);
else
bytes_read = ::read(descriptor.m_fd, ptr, length);
if (bytes_read < 0) {
int reason = 0;
#if defined(_WIN32)
if (descriptor.m_is_socket)
reason = WSAGetLastError();
else
reason = errno;
#else
reason = errno;
if (reason == EINTR || reason == EAGAIN)
continue;
#endif
if (log)
*log << "Error " << reason << " reading from input file.\n";
return false;
}
assert(bytes_read <= length);
ptr += bytes_read;
length -= bytes_read;
}
text += data;
return true;
}
bool InputStream::read_line(std::ofstream *log, std::string &line) {
line.clear();
while (true) {
if (!read_full(log, 1, line))
return false;
if (llvm::StringRef(line).endswith("\r\n"))
break;
}
line.erase(line.size() - 2);
return true;
}
bool InputStream::read_expected(std::ofstream *log, llvm::StringRef expected) {
std::string result;
if (!read_full(log, expected.size(), result))
return false;
if (expected != result) {
if (log)
*log << "Warning: Expected '" << expected.str() << "', got '" << result
<< "\n";
}
return true;
}
<commit_msg>[lldb-vscode] Fix warning<commit_after>//===-- IOStream.cpp --------------------------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "IOStream.h"
#if defined(_WIN32)
#include <io.h>
#else
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>
#endif
#include <fstream>
#include <string>
#include <vector>
using namespace lldb_vscode;
StreamDescriptor::StreamDescriptor() {}
StreamDescriptor::StreamDescriptor(StreamDescriptor &&other) {
*this = std::move(other);
}
StreamDescriptor::~StreamDescriptor() {
if (!m_close)
return;
if (m_is_socket)
#if defined(_WIN32)
::closesocket(m_socket);
#else
::close(m_socket);
#endif
else
::close(m_fd);
}
StreamDescriptor &StreamDescriptor::operator=(StreamDescriptor &&other) {
m_close = other.m_close;
other.m_close = false;
m_is_socket = other.m_is_socket;
if (m_is_socket)
m_socket = other.m_socket;
else
m_fd = other.m_fd;
return *this;
}
StreamDescriptor StreamDescriptor::from_socket(SOCKET s, bool close) {
StreamDescriptor sd;
sd.m_is_socket = true;
sd.m_socket = s;
sd.m_close = close;
return sd;
}
StreamDescriptor StreamDescriptor::from_file(int fd, bool close) {
StreamDescriptor sd;
sd.m_is_socket = false;
sd.m_fd = fd;
sd.m_close = close;
return sd;
}
bool OutputStream::write_full(llvm::StringRef str) {
while (!str.empty()) {
int bytes_written = 0;
if (descriptor.m_is_socket)
bytes_written = ::send(descriptor.m_socket, str.data(), str.size(), 0);
else
bytes_written = ::write(descriptor.m_fd, str.data(), str.size());
if (bytes_written < 0) {
if (errno == EINTR || errno == EAGAIN)
continue;
return false;
}
str = str.drop_front(bytes_written);
}
return true;
}
bool InputStream::read_full(std::ofstream *log, size_t length,
std::string &text) {
std::string data;
data.resize(length);
char *ptr = &data[0];
while (length != 0) {
int bytes_read = 0;
if (descriptor.m_is_socket)
bytes_read = ::recv(descriptor.m_socket, ptr, length, 0);
else
bytes_read = ::read(descriptor.m_fd, ptr, length);
if (bytes_read < 0) {
int reason = 0;
#if defined(_WIN32)
if (descriptor.m_is_socket)
reason = WSAGetLastError();
else
reason = errno;
#else
reason = errno;
if (reason == EINTR || reason == EAGAIN)
continue;
#endif
if (log)
*log << "Error " << reason << " reading from input file.\n";
return false;
}
assert(bytes_read >= 0 && (size_t)bytes_read <= length);
ptr += bytes_read;
length -= bytes_read;
}
text += data;
return true;
}
bool InputStream::read_line(std::ofstream *log, std::string &line) {
line.clear();
while (true) {
if (!read_full(log, 1, line))
return false;
if (llvm::StringRef(line).endswith("\r\n"))
break;
}
line.erase(line.size() - 2);
return true;
}
bool InputStream::read_expected(std::ofstream *log, llvm::StringRef expected) {
std::string result;
if (!read_full(log, expected.size(), result))
return false;
if (expected != result) {
if (log)
*log << "Warning: Expected '" << expected.str() << "', got '" << result
<< "\n";
}
return true;
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: wrap_itkImageSource.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software 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.
=========================================================================*/
#include "itkImage.h"
#include "itkImageToImageFilter.h"
#ifdef CABLE_CONFIGURATION
#include "itkCSwigImages.h"
#include "itkCSwigMacros.h"
namespace _cable_
{
const char* const group = ITK_WRAP_GROUP(itkImageSource);
namespace wrappers
{
ITK_WRAP_OBJECT1(ImageSource, image::F2 , itkImageSourceF2 );
ITK_WRAP_OBJECT1(ImageSource, image::D2 , itkImageSourceD2 );
ITK_WRAP_OBJECT1(ImageSource, image::UC2, itkImageSourceUC2);
ITK_WRAP_OBJECT1(ImageSource, image::US2, itkImageSourceUS2);
ITK_WRAP_OBJECT1(ImageSource, image::UI2, itkImageSourceUI2);
ITK_WRAP_OBJECT1(ImageSource, image::UL2, itkImageSourceUL2);
ITK_WRAP_OBJECT1(ImageSource, image::SC2, itkImageSourceSC2);
ITK_WRAP_OBJECT1(ImageSource, image::SS2, itkImageSourceSS2);
ITK_WRAP_OBJECT1(ImageSource, image::SI2, itkImageSourceSI2);
ITK_WRAP_OBJECT1(ImageSource, image::F3 , itkImageSourceF3 );
ITK_WRAP_OBJECT1(ImageSource, image::D3 , itkImageSourceD3 );
ITK_WRAP_OBJECT1(ImageSource, image::UC3, itkImageSourceUC3);
ITK_WRAP_OBJECT1(ImageSource, image::US3, itkImageSourceUS3);
ITK_WRAP_OBJECT1(ImageSource, image::UI3, itkImageSourceUI3);
ITK_WRAP_OBJECT1(ImageSource, image::UL3, itkImageSourceUL3);
ITK_WRAP_OBJECT1(ImageSource, image::SC3, itkImageSourceSC3);
ITK_WRAP_OBJECT1(ImageSource, image::SS3, itkImageSourceSS3);
ITK_WRAP_OBJECT1(ImageSource, image::SI3, itkImageSourceSI3);
}
}
#endif
<commit_msg>ENH: Adding wrapping for output images of Vector and CovariantVectors 2D.3D.<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: wrap_itkImageSource.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software 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.
=========================================================================*/
#include "itkImage.h"
#include "itkImageToImageFilter.h"
#ifdef CABLE_CONFIGURATION
#include "itkCSwigImages.h"
#include "itkCSwigMacros.h"
namespace _cable_
{
const char* const group = ITK_WRAP_GROUP(itkImageSource);
namespace wrappers
{
ITK_WRAP_OBJECT1(ImageSource, image::F2 , itkImageSourceF2 );
ITK_WRAP_OBJECT1(ImageSource, image::D2 , itkImageSourceD2 );
ITK_WRAP_OBJECT1(ImageSource, image::UC2, itkImageSourceUC2);
ITK_WRAP_OBJECT1(ImageSource, image::US2, itkImageSourceUS2);
ITK_WRAP_OBJECT1(ImageSource, image::UI2, itkImageSourceUI2);
ITK_WRAP_OBJECT1(ImageSource, image::UL2, itkImageSourceUL2);
ITK_WRAP_OBJECT1(ImageSource, image::SC2, itkImageSourceSC2);
ITK_WRAP_OBJECT1(ImageSource, image::SS2, itkImageSourceSS2);
ITK_WRAP_OBJECT1(ImageSource, image::SI2, itkImageSourceSI2);
ITK_WRAP_OBJECT1(ImageSource, image::VF2 , itkImageSourceVF2 );
ITK_WRAP_OBJECT1(ImageSource, image::CVF2 , itkImageSourceCVF2 );
ITK_WRAP_OBJECT1(ImageSource, image::F3 , itkImageSourceF3 );
ITK_WRAP_OBJECT1(ImageSource, image::D3 , itkImageSourceD3 );
ITK_WRAP_OBJECT1(ImageSource, image::UC3, itkImageSourceUC3);
ITK_WRAP_OBJECT1(ImageSource, image::US3, itkImageSourceUS3);
ITK_WRAP_OBJECT1(ImageSource, image::UI3, itkImageSourceUI3);
ITK_WRAP_OBJECT1(ImageSource, image::UL3, itkImageSourceUL3);
ITK_WRAP_OBJECT1(ImageSource, image::SC3, itkImageSourceSC3);
ITK_WRAP_OBJECT1(ImageSource, image::SS3, itkImageSourceSS3);
ITK_WRAP_OBJECT1(ImageSource, image::SI3, itkImageSourceSI3);
ITK_WRAP_OBJECT1(ImageSource, image::VF3 , itkImageSourceVF3 );
ITK_WRAP_OBJECT1(ImageSource, image::CVF3 , itkImageSourceCVF3 );
}
}
#endif
<|endoftext|>
|
<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <string>
#include <iostream>
#include <cstring>
#include <signal.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include "clientCommands.cpp"
void closeSocket(int atmSocket) {
printf("Closing \n");
fflush(stdout);
close(atmSocket);
exit(1);
}
int main(int argc, char *argv[]){
// Check for arguments (port number is provided)
if(argc != 2){
printf("Run ./ATMClient <proxy-port-number>\n");
return -1;
}
//socket setup
unsigned int proxyPortNo = atoi(argv[1]);
int atmSocket = socket(AF_INET, SOCK_STREAM, 0);
if(atmSocket == -1){
printf("Did not connect to socket\n");
return -1;
}
//Close sock on Ctrl-C
signal(SIGINT, closeSocket);
sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(proxyPortNo);
addr.sin_addr.s_addr = INADDR_ANY;
if(0 != connect(atmSocket, reinterpret_cast<sockaddr*>(&addr), sizeof(addr))){
printf("Did not connect to socket\n");
return -1;
}
// Initial message
int messageNumber = 1;
// TODO: implement message number
// std::string number= std::to_string(messageNumber);
// messageNumber++;
char mess[256];
strcpy(mess, "init");
int n = write(atmSocket, mess, strlen(mess)+1);
if (n < 0) error("ERROR something is wrong");
char buf[256];
n = read(atmSocket,buf,255);
if (n < 0) error("ERROR reading from socket");
//input loop
bool loggedin = false;
std::string sessionKey;
std::string input;
printf("atm ~ : ");
while(1){
getline(std::cin, input);
// fgets(buf, 255, stdin);
// buf[strlen(buf)-1] = '\0'; //trim off trailing newline
// std::string input(buf);
int index = 0;
if (input.length() == 0) continue;
std::string command = advanceCommand(input, index);
if(command.compare("exit") == 0){
closeSocket(atmSocket);
}
if(loggedin){
// Login in
if(command.compare("balance") == 0){
advanceSpaces(input, index);
std::cout << "Obtaining Balance..." << std::endl;
balance(sessionKey, atmSocket);
}
else if(command.compare("withdraw") == 0){
advanceSpaces(input, index);
std::string amountString = advanceCommand(input, index);
float amount = atof(amountString.c_str());
std::cout << amount << std::endl;
}
else if(command.compare("transfer") == 0){
advanceSpaces(input, index);
std::string amountString = advanceCommand(input, index);
float amount = atof(amountString.c_str());
advanceSpaces(input, index);
std::string username = advanceCommand(input, index);
std::cout << username << std::endl;
}
else if(command.compare("logout") == 0){
advanceSpaces(input, index);
closeSocket(atmSocket);
std::cout << "Logging Out..." << std::endl;
exit(0);
}
else{
std::cout << "You suck man" << std::endl;
}
}
else{
// Login in
if(command.compare("login") == 0){
advanceSpaces(input, index);
std::string username = advanceCommand(input, index);
std::cout << username << std::endl;
std::string ans = login(username, atmSocket);
if(ans != "broken"){
sessionKey = ans;
loggedin = true;
}
}
}
printf("atm ~ : ");
}
//cleanup
close(atmSocket);
return 0;
}
<commit_msg> withdraw<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <string>
#include <iostream>
#include <cstring>
#include <signal.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include "clientCommands.cpp"
void closeSocket(int atmSocket) {
printf("Closing \n");
fflush(stdout);
close(atmSocket);
exit(1);
}
int main(int argc, char *argv[]){
// Check for arguments (port number is provided)
if(argc != 2){
printf("Run ./ATMClient <proxy-port-number>\n");
return -1;
}
//socket setup
unsigned int proxyPortNo = atoi(argv[1]);
int atmSocket = socket(AF_INET, SOCK_STREAM, 0);
if(atmSocket == -1){
printf("Did not connect to socket\n");
return -1;
}
//Close sock on Ctrl-C
signal(SIGINT, closeSocket);
sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(proxyPortNo);
addr.sin_addr.s_addr = INADDR_ANY;
if(0 != connect(atmSocket, reinterpret_cast<sockaddr*>(&addr), sizeof(addr))){
printf("Did not connect to socket\n");
return -1;
}
// Initial message
int messageNumber = 1;
// TODO: implement message number
// std::string number= std::to_string(messageNumber);
// messageNumber++;
char mess[256];
strcpy(mess, "init");
int n = write(atmSocket, mess, strlen(mess)+1);
if (n < 0) error("ERROR something is wrong");
char buf[256];
n = read(atmSocket,buf,255);
if (n < 0) error("ERROR reading from socket");
//input loop
bool loggedin = false;
std::string sessionKey;
std::string input;
printf("atm ~ : ");
while(1){
getline(std::cin, input);
// fgets(buf, 255, stdin);
// buf[strlen(buf)-1] = '\0'; //trim off trailing newline
// std::string input(buf);
int index = 0;
if (input.length() == 0) continue;
std::string command = advanceCommand(input, index);
if(command.compare("exit") == 0){
closeSocket(atmSocket);
}
if(loggedin){
// Login in
if(command.compare("balance") == 0){
advanceSpaces(input, index);
std::cout << "Obtaining Balance..." << std::endl;
balance(sessionKey, atmSocket);
}
else if(command.compare("withdraw") == 0){
advanceSpaces(input, index);
std::string amountString = advanceCommand(input, index);
float amount = atof(amountString.c_str());
withdraw(sessionKey, amountString, atmSocket){
}
else if(command.compare("transfer") == 0){
advanceSpaces(input, index);
std::string amountString = advanceCommand(input, index);
float amount = atof(amountString.c_str());
advanceSpaces(input, index);
std::string username = advanceCommand(input, index);
std::cout << username << std::endl;
}
else if(command.compare("logout") == 0){
advanceSpaces(input, index);
closeSocket(atmSocket);
std::cout << "Logging Out..." << std::endl;
exit(0);
}
else{
std::cout << "You suck man" << std::endl;
}
}
else{
// Login in
if(command.compare("login") == 0){
advanceSpaces(input, index);
std::string username = advanceCommand(input, index);
std::cout << username << std::endl;
std::string ans = login(username, atmSocket);
if(ans != "broken"){
sessionKey = ans;
loggedin = true;
}
}
}
printf("atm ~ : ");
}
//cleanup
close(atmSocket);
return 0;
}
<|endoftext|>
|
<commit_before><commit_msg>ByteString->rtl::OString<commit_after><|endoftext|>
|
<commit_before><commit_msg>WaE: unreferenced formal parameter<commit_after><|endoftext|>
|
<commit_before>/*
* ApiClient.cpp
*/
#include "ApiClient.h"
ApiClient::ApiClient()
{
request_buffer.reserve(BUFF_SIZE);
}
unsigned int ApiClient::request()
{
return 0;
//return runShellCommand(request_buffer);
}
unsigned int ApiClient::get(const __FlashStringHelper *url)
{
return request();
}
unsigned int ApiClient::get(const String &url)
{
return request();
}
unsigned int ApiClient::get(const char *url)
{
return request();
}
unsigned int ApiClient::post(const __FlashStringHelper *url, const __FlashStringHelper *data)
{
request_buffer = F("curl -X POST ");
request_buffer += F("-H \"Authorization: ");
addAuthorizationHeader();
request_buffer += F("\" ");
request_buffer += F("-H \"Content-Type: ");
addContentTypeHeader();
request_buffer += F("\" ");
request_buffer += F("-d '");
request_buffer += data;
request_buffer += F("' ");
request_buffer += url;
return request();
}
unsigned int ApiClient::post(const String &url, const String &data)
{
request_buffer = F("curl -X POST ");
request_buffer += F("-H \"Authorization: ");
addAuthorizationHeader();
request_buffer += F("\" ");
request_buffer += F("-H \"Content-Type: ");
addContentTypeHeader();
request_buffer += F("\" ");
request_buffer += F("-d '");
request_buffer += data;
request_buffer += F("' ");
request_buffer += url;
return request();
}
unsigned int ApiClient::post(const char *url, const char *data)
{
request_buffer = F("curl -X POST ");
request_buffer += F("-H \"Authorization: ");
addAuthorizationHeader();
request_buffer += F("\" ");
request_buffer += F("-H \"Content-Type: ");
addContentTypeHeader();
request_buffer += F("\" ");
request_buffer += F("-d '");
request_buffer += data;
request_buffer += F("' ");
request_buffer += url;
return request();
}
void ApiClient::setAuthorizationHeader(StringPointer auth_header)
{
this->auth_header = auth_header;
}
void ApiClient::setAuthorizationHeader(const __FlashStringHelper *auth_header)
{
this->auth_header.u.flashstring_ptr = auth_header;
this->auth_header.type = POINTER_UNION_TYPE_FLASHSTRING;
}
void ApiClient::setAuthorizationHeader(const String *auth_header)
{
this->auth_header.u.string_ptr = auth_header;
this->auth_header.type = POINTER_UNION_TYPE_STRING;
}
void ApiClient::setAuthorizationHeader(const char *auth_header)
{
this->auth_header.u.char_ptr = auth_header;
this->auth_header.type = POINTER_UNION_TYPE_CHAR;
}
void ApiClient::getAuthorizationHeader()
{
switch(auth_header.type) {
case POINTER_UNION_TYPE_FLASHSTRING:
Serial.println(auth_header.u.flashstring_ptr);
break;
case POINTER_UNION_TYPE_STRING:
Serial.println(*auth_header.u.string_ptr);
break;
case POINTER_UNION_TYPE_CHAR:
Serial.println(auth_header.u.char_ptr);
break;
default:
break;
}
}
void ApiClient::addAuthorizationHeader()
{
switch(auth_header.type) {
case POINTER_UNION_TYPE_FLASHSTRING:
request_buffer += auth_header.u.flashstring_ptr;
break;
case POINTER_UNION_TYPE_STRING:
request_buffer += *auth_header.u.string_ptr;
break;
case POINTER_UNION_TYPE_CHAR:
request_buffer += auth_header.u.char_ptr;
break;
default:
break;
}
}
void ApiClient::setContentTypeHeader(const __FlashStringHelper *contenttype_header)
{
this->contenttype_header.u.flashstring_ptr = contenttype_header;
this->contenttype_header.type = POINTER_UNION_TYPE_FLASHSTRING;
}
void ApiClient::setContentTypeHeader(const String *contenttype_header)
{
this->contenttype_header.u.string_ptr = contenttype_header;
this->contenttype_header.type = POINTER_UNION_TYPE_STRING;
}
void ApiClient::setContentTypeHeader(const char *contenttype_header)
{
this->contenttype_header.u.char_ptr = contenttype_header;
this->contenttype_header.type = POINTER_UNION_TYPE_CHAR;
}
void ApiClient::getContentTypeHeader()
{
switch(contenttype_header.type) {
case POINTER_UNION_TYPE_FLASHSTRING:
Serial.println(contenttype_header.u.flashstring_ptr);
break;
case POINTER_UNION_TYPE_STRING:
Serial.println(*contenttype_header.u.string_ptr);
break;
case POINTER_UNION_TYPE_CHAR:
Serial.println(contenttype_header.u.char_ptr);
break;
default:
break;
}
}
void ApiClient::addContentTypeHeader()
{
switch(contenttype_header.type) {
case POINTER_UNION_TYPE_FLASHSTRING:
request_buffer += contenttype_header.u.flashstring_ptr;
break;
case POINTER_UNION_TYPE_STRING:
request_buffer += *contenttype_header.u.string_ptr;
break;
case POINTER_UNION_TYPE_CHAR:
request_buffer += contenttype_header.u.char_ptr;
break;
default:
break;
}
}
void ApiClient::setUserAgentHeader(const __FlashStringHelper *useragent_header)
{
this->useragent_header.u.flashstring_ptr = useragent_header;
this->useragent_header.type = POINTER_UNION_TYPE_FLASHSTRING;
}
void ApiClient::setUserAgentHeader(const String *useragent_header)
{
this->useragent_header.u.string_ptr = useragent_header;
this->useragent_header.type = POINTER_UNION_TYPE_STRING;
}
void ApiClient::setUserAgentHeader(const char *useragent_header)
{
this->useragent_header.u.char_ptr = useragent_header;
this->useragent_header.type = POINTER_UNION_TYPE_CHAR;
}
void ApiClient::getUserAgentHeader()
{
switch(useragent_header.type) {
case POINTER_UNION_TYPE_FLASHSTRING:
Serial.println(useragent_header.u.flashstring_ptr);
break;
case POINTER_UNION_TYPE_STRING:
Serial.println(*useragent_header.u.string_ptr);
break;
case POINTER_UNION_TYPE_CHAR:
Serial.println(useragent_header.u.char_ptr);
break;
default:
break;
}
}
void ApiClient::addUserAgentHeader()
{
switch(useragent_header.type) {
case POINTER_UNION_TYPE_FLASHSTRING:
request_buffer += useragent_header.u.flashstring_ptr;
break;
case POINTER_UNION_TYPE_STRING:
request_buffer += *useragent_header.u.string_ptr;
break;
case POINTER_UNION_TYPE_CHAR:
request_buffer += useragent_header.u.char_ptr;
break;
default:
break;
}
}
void ApiClient::printRequest()
{
Serial.println(request_buffer);
}
<commit_msg>Enabled posting to the API.<commit_after>/*
* ApiClient.cpp
*/
#include "ApiClient.h"
ApiClient::ApiClient()
{
request_buffer.reserve(BUFF_SIZE);
}
unsigned int ApiClient::request()
{
return runShellCommand(request_buffer);
}
unsigned int ApiClient::get(const __FlashStringHelper *url)
{
return request();
}
unsigned int ApiClient::get(const String &url)
{
return request();
}
unsigned int ApiClient::get(const char *url)
{
return request();
}
unsigned int ApiClient::post(const __FlashStringHelper *url, const __FlashStringHelper *data)
{
request_buffer = F("curl -X POST ");
request_buffer += F("-H \"Authorization: ");
addAuthorizationHeader();
request_buffer += F("\" ");
request_buffer += F("-H \"Content-Type: ");
addContentTypeHeader();
request_buffer += F("\" ");
request_buffer += F("-d '");
request_buffer += data;
request_buffer += F("' ");
request_buffer += url;
return request();
}
unsigned int ApiClient::post(const String &url, const String &data)
{
request_buffer = F("curl -X POST ");
request_buffer += F("-H \"Authorization: ");
addAuthorizationHeader();
request_buffer += F("\" ");
request_buffer += F("-H \"Content-Type: ");
addContentTypeHeader();
request_buffer += F("\" ");
request_buffer += F("-d '");
request_buffer += data;
request_buffer += F("' ");
request_buffer += url;
return request();
}
unsigned int ApiClient::post(const char *url, const char *data)
{
request_buffer = F("curl -X POST ");
request_buffer += F("-H \"Authorization: ");
addAuthorizationHeader();
request_buffer += F("\" ");
request_buffer += F("-H \"Content-Type: ");
addContentTypeHeader();
request_buffer += F("\" ");
request_buffer += F("-d '");
request_buffer += data;
request_buffer += F("' ");
request_buffer += url;
return request();
}
void ApiClient::setAuthorizationHeader(StringPointer auth_header)
{
this->auth_header = auth_header;
}
void ApiClient::setAuthorizationHeader(const __FlashStringHelper *auth_header)
{
this->auth_header.u.flashstring_ptr = auth_header;
this->auth_header.type = POINTER_UNION_TYPE_FLASHSTRING;
}
void ApiClient::setAuthorizationHeader(const String *auth_header)
{
this->auth_header.u.string_ptr = auth_header;
this->auth_header.type = POINTER_UNION_TYPE_STRING;
}
void ApiClient::setAuthorizationHeader(const char *auth_header)
{
this->auth_header.u.char_ptr = auth_header;
this->auth_header.type = POINTER_UNION_TYPE_CHAR;
}
void ApiClient::getAuthorizationHeader()
{
switch(auth_header.type) {
case POINTER_UNION_TYPE_FLASHSTRING:
Serial.println(auth_header.u.flashstring_ptr);
break;
case POINTER_UNION_TYPE_STRING:
Serial.println(*auth_header.u.string_ptr);
break;
case POINTER_UNION_TYPE_CHAR:
Serial.println(auth_header.u.char_ptr);
break;
default:
break;
}
}
void ApiClient::addAuthorizationHeader()
{
switch(auth_header.type) {
case POINTER_UNION_TYPE_FLASHSTRING:
request_buffer += auth_header.u.flashstring_ptr;
break;
case POINTER_UNION_TYPE_STRING:
request_buffer += *auth_header.u.string_ptr;
break;
case POINTER_UNION_TYPE_CHAR:
request_buffer += auth_header.u.char_ptr;
break;
default:
break;
}
}
void ApiClient::setContentTypeHeader(const __FlashStringHelper *contenttype_header)
{
this->contenttype_header.u.flashstring_ptr = contenttype_header;
this->contenttype_header.type = POINTER_UNION_TYPE_FLASHSTRING;
}
void ApiClient::setContentTypeHeader(const String *contenttype_header)
{
this->contenttype_header.u.string_ptr = contenttype_header;
this->contenttype_header.type = POINTER_UNION_TYPE_STRING;
}
void ApiClient::setContentTypeHeader(const char *contenttype_header)
{
this->contenttype_header.u.char_ptr = contenttype_header;
this->contenttype_header.type = POINTER_UNION_TYPE_CHAR;
}
void ApiClient::getContentTypeHeader()
{
switch(contenttype_header.type) {
case POINTER_UNION_TYPE_FLASHSTRING:
Serial.println(contenttype_header.u.flashstring_ptr);
break;
case POINTER_UNION_TYPE_STRING:
Serial.println(*contenttype_header.u.string_ptr);
break;
case POINTER_UNION_TYPE_CHAR:
Serial.println(contenttype_header.u.char_ptr);
break;
default:
break;
}
}
void ApiClient::addContentTypeHeader()
{
switch(contenttype_header.type) {
case POINTER_UNION_TYPE_FLASHSTRING:
request_buffer += contenttype_header.u.flashstring_ptr;
break;
case POINTER_UNION_TYPE_STRING:
request_buffer += *contenttype_header.u.string_ptr;
break;
case POINTER_UNION_TYPE_CHAR:
request_buffer += contenttype_header.u.char_ptr;
break;
default:
break;
}
}
void ApiClient::setUserAgentHeader(const __FlashStringHelper *useragent_header)
{
this->useragent_header.u.flashstring_ptr = useragent_header;
this->useragent_header.type = POINTER_UNION_TYPE_FLASHSTRING;
}
void ApiClient::setUserAgentHeader(const String *useragent_header)
{
this->useragent_header.u.string_ptr = useragent_header;
this->useragent_header.type = POINTER_UNION_TYPE_STRING;
}
void ApiClient::setUserAgentHeader(const char *useragent_header)
{
this->useragent_header.u.char_ptr = useragent_header;
this->useragent_header.type = POINTER_UNION_TYPE_CHAR;
}
void ApiClient::getUserAgentHeader()
{
switch(useragent_header.type) {
case POINTER_UNION_TYPE_FLASHSTRING:
Serial.println(useragent_header.u.flashstring_ptr);
break;
case POINTER_UNION_TYPE_STRING:
Serial.println(*useragent_header.u.string_ptr);
break;
case POINTER_UNION_TYPE_CHAR:
Serial.println(useragent_header.u.char_ptr);
break;
default:
break;
}
}
void ApiClient::addUserAgentHeader()
{
switch(useragent_header.type) {
case POINTER_UNION_TYPE_FLASHSTRING:
request_buffer += useragent_header.u.flashstring_ptr;
break;
case POINTER_UNION_TYPE_STRING:
request_buffer += *useragent_header.u.string_ptr;
break;
case POINTER_UNION_TYPE_CHAR:
request_buffer += useragent_header.u.char_ptr;
break;
default:
break;
}
}
void ApiClient::printRequest()
{
Serial.println(request_buffer);
}
<|endoftext|>
|
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/usr/diag/prdf/common/framework/register/prdfHomRegisterAccess.C $ */
/* */
/* IBM CONFIDENTIAL */
/* */
/* COPYRIGHT International Business Machines Corp. 2002,2013 */
/* */
/* p1 */
/* */
/* Object Code Only (OCO) source materials */
/* Licensed Internal Code Source Materials */
/* IBM HostBoot Licensed Internal Code */
/* */
/* The source code for this program is not published or otherwise */
/* divested of its trade secrets, irrespective of what has been */
/* deposited with the U.S. Copyright Office. */
/* */
/* Origin: 30 */
/* */
/* IBM_PROLOG_END_TAG */
/**
@file prdfHomRegisterAccess.C
@brief definition of HomRegisterAccess
*/
//----------------------------------------------------------------------
// Includes
//----------------------------------------------------------------------
#define prdfHomRegisterAccess_C
#ifdef __HOSTBOOT_MODULE
#include <ecmdDataBufferBase.H>
#include <fapi.H>
#include <errlmanager.H>
#include <devicefw/userif.H>
#include <targeting/common/targetservice.H>
#else
#include <ecmdDataBuffer.H>
#include <hwsvScanScom.H>
#include <chicservlib.H>
#include <hwsvExecutionService.H>
#endif
#include <prdfHomRegisterAccess.H>
#include <prdf_service_codes.H>
#include <iipbits.h>
#include <iipglobl.h>
#include <prdfMain.H>
#include <prdfPlatServices.H>
#undef prdfHomRegisterAccess_C
namespace PRDF
{
//----------------------------------------------------------------------
// User Types
//----------------------------------------------------------------------
//----------------------------------------------------------------------
// Constants
//----------------------------------------------------------------------
//----------------------------------------------------------------------
// Macros
//----------------------------------------------------------------------
//----------------------------------------------------------------------
// Internal Function Prototypes
//----------------------------------------------------------------------
//----------------------------------------------------------------------
// Global Variables
//----------------------------------------------------------------------
//------------------------------------------------------------------------------
// Member Function Specifications
//------------------------------------------------------------------------------
ScomService& getScomService()
{
return PRDF_GET_SINGLETON(theScomService);
}
ScomService::ScomService() :
iv_ScomAccessor(NULL)
{
PRDF_DTRAC("ScomService() initializing default iv_ScomAccessor");
iv_ScomAccessor = new ScomAccessor();
}
ScomService::~ScomService()
{
if(NULL != iv_ScomAccessor)
{
PRDF_DTRAC("~ScomService() deleting iv_ScomAccessor");
delete iv_ScomAccessor;
iv_ScomAccessor = NULL;
}
}
void ScomService::setScomAccessor(ScomAccessor & i_ScomAccessor)
{
PRDF_DTRAC("ScomService::setScomAccessor() setting new scom accessor");
if(NULL != iv_ScomAccessor)
{
PRDF_TRAC("ScomService::setScomAccessor() deleting old iv_ScomAccessor");
delete iv_ScomAccessor;
iv_ScomAccessor = NULL;
}
iv_ScomAccessor = &i_ScomAccessor;
}
uint32_t ScomService::Access(TARGETING::TargetHandle_t i_target,
BIT_STRING_CLASS & bs,
uint64_t registerId,
MopRegisterAccess::Operation operation) const
{
PRDF_DENTER("ScomService::Access()");
uint32_t rc = iv_ScomAccessor->Access(i_target,
bs,
registerId,
operation);
PRDF_DEXIT("ScomService::Access(): rc=%d", rc);
return rc;
}
uint32_t ScomAccessor::Access(TARGETING::TargetHandle_t i_target,
BIT_STRING_CLASS & bs,
uint64_t registerId,
MopRegisterAccess::Operation operation) const
{
PRDF_DENTER("ScomAccessor::Access()");
uint32_t rc = SUCCESS;
errlHndl_t errH = NULL;
uint32_t bsize = bs.GetLength();
uint32_t l_ecmdRc = ECMD_DBUF_SUCCESS;
if(i_target != NULL)
{
#ifdef __HOSTBOOT_MODULE
ecmdDataBufferBase buffer(bsize);
uint64_t l_data = 0;
size_t l_size = sizeof(uint64_t);
#else
ecmdDataBuffer buffer(bsize);
#endif
switch (operation)
{
case MopRegisterAccess::WRITE:
for(unsigned int i = 0; i < bsize; ++i)
{
if(bs.IsSet(i)) buffer.setBit(i);
}
// FIXME: If register is in a EX chiplet, need to also update
// PORE image ????
#ifdef __HOSTBOOT_MODULE
l_data = buffer.getDoubleWord(0);
errH = deviceWrite( i_target,
&l_data,
l_size,
DEVICE_SCOM_ADDRESS(registerId));
#else
errH = HWSV::hwsvPutScom(i_target, registerId, buffer);
#endif
break;
case MopRegisterAccess::READ:
bs.Pattern(0x00000000); // clear all bits
#ifdef __HOSTBOOT_MODULE
errH = deviceRead( i_target, &l_data, l_size,
DEVICE_SCOM_ADDRESS(registerId) );
l_ecmdRc = buffer.setDoubleWord(0, l_data);
#else
errH = HWSV::hwsvGetScom(i_target, registerId, buffer);
#endif
for(unsigned int i = 0; i < bsize; ++i)
{
if(buffer.isBitSet(i)) bs.Set(i);
}
break;
default:
PRDF_ERR("ScomAccessor::Access() unsuppported scom op: 0x%08X", operation);
break;
} // end switch operation
}
else // Invalid target
{
/*@
* @errortype
* @subsys EPUB_FIRMWARE_SP
* @reasoncode PRDF_CODE_FAIL
* @moduleid PRDF_HOM_SCOM
* @userdata1 PRD Return code = SCR_ACCESS_FAILED
* @userdata2 The invalid ID causing the fail
* @devdesc Access SCOM failed due to NULL target handle
* @procedure EPUB_PRC_SP_CODE
*/
// create an error log
PRDF_CREATE_ERRL(errH,
ERRL_SEV_PREDICTIVE, // error on diagnostic
ERRL_ETYPE_NOT_APPLICABLE,
SRCI_MACH_CHECK,
SRCI_NO_ATTR,
PRDF_HOM_SCOM, // module id
FSP_DEFAULT_REFCODE, // refcode What do we use???
PRDF_CODE_FAIL, // Reason code
SCR_ACCESS_FAILED, // user data word 1
PlatServices::getHuid(i_target), // user data word 2
0x0000, // user data word 3
0x0000 // user data word 4
);
}
if(errH)
{
rc = PRD_SCANCOM_FAILURE;
PRDF_ADD_SW_ERR(errH, rc, PRDF_HOM_SCOM, __LINE__);
PRDF_ADD_PROCEDURE_CALLOUT(errH, SRCI_PRIORITY_MED, EPUB_PRC_SP_CODE);
bool l_isAbort = false;
PRDF_ABORTING(l_isAbort);
if (!l_isAbort)
{
PRDF_COMMIT_ERRL(errH, ERRL_ACTION_SA|ERRL_ACTION_REPORT);
}
else
{
delete errH;
errH = NULL;
}
}
if (l_ecmdRc != ECMD_DBUF_SUCCESS)
{
PRDF_ERR( "ScomAccessor::Access ecmdDataBuffer "
"operation failed with ecmd_rc = 0x%.8X", l_ecmdRc );
/*@
* @errortype
* @subsys EPUB_FIRMWARE_SP
* @reasoncode PRDF_ECMD_DATA_BUFFER_FAIL
* @moduleid PRDF_HOM_SCOM
* @userdata1 ecmdDataBuffer return code
* @userdata2 Chip HUID
* @userdata3 unused
* @userdata4 unused
* @devdesc Low-level data buffer support returned a failure. Probable firmware error.
* @procedure EPUB_PRC_SP_CODE
*/
errlHndl_t ecmd_rc_errl = NULL;
PRDF_CREATE_ERRL(ecmd_rc_errl,
ERRL_SEV_PREDICTIVE, // error on diagnosticERRL_ETYPE_NOT_APPLICABLE
ERRL_ETYPE_NOT_APPLICABLE,
SRCI_MACH_CHECK, // B1xx src
SRCI_NO_ATTR,
PRDF_HOM_SCOM, // module id
FSP_DEFAULT_REFCODE, // refcode
PRDF_ECMD_DATA_BUFFER_FAIL, // Reason code - see prdf_service_codes.H
l_ecmdRc, // user data word 1
PlatServices::getHuid(i_target), // user data word 2
0, // user data word 3
0 // user data word 4
);
PRDF_ADD_PROCEDURE_CALLOUT(ecmd_rc_errl, SRCI_PRIORITY_MED, EPUB_PRC_SP_CODE);
PRDF_COMMIT_ERRL(ecmd_rc_errl, ERRL_ACTION_REPORT);
rc = FAIL;
}
PRDF_DEXIT("ScomAccessor::Access(): rc=%d", rc);
return rc;
}
//------------------------------------------------------------------------------
uint32_t HomRegisterAccessScom::Access( BIT_STRING_CLASS & bs,
uint64_t registerId,
Operation operation) const
{
PRDF_DENTER("HomRegisterAccessScom::Access()");
uint32_t rc = getScomService().Access(iv_ptargetHandle,
bs,
registerId,
operation);
PRDF_DEXIT("HomRegisterAccessScom::Access() rc=%d", rc);
return rc;
}
//------------------------------------------------------------------------------
HomRegisterAccessScan::HomRegisterAccessScan(
TARGETING::TargetHandle_t i_ptargetHandle,
ScanRingField * start, ScanRingField * end )
: MopRegisterAccess(), iv_punitHandle(i_ptargetHandle)
{
iv_aliasIds.reserve(end-start);
while(start != end)
{
iv_aliasIds.push_back(*start);
++start;
}
}
//------------------------------------------------------------------------------
uint32_t HomRegisterAccessScan::Access(BIT_STRING_CLASS & bs,
uint64_t registerId,
Operation operation) const
{
uint32_t rc = SUCCESS;
errlHndl_t errH = NULL;
HUID l_chipHUID = PlatServices::getHuid(iv_punitHandle);
if(operation == MopRegisterAccess::READ)
{
if(iv_punitHandle != NULL)
{
#ifdef __HOSTBOOT_MODULE
ecmdDataBufferBase buf(bs.GetLength());
#else
ecmdDataBuffer buf(bs.GetLength());
#endif
uint32_t curbit = 0;
bs.Pattern(0x00000000); // clear desination bit string
for(AliasIdList::const_iterator i = iv_aliasIds.begin(); i != iv_aliasIds.end(); ++i)
{
for(uint32_t j = 0; j != i->length; ++j)
{
if(buf.isBitSet(j)) bs.Set(j+curbit);
}
curbit += i->length;
}
}
else
{
/*@
* @errortype
* @subsys EPUB_FIRMWARE_SP
* @reasoncode PRDF_CODE_FAIL
* @moduleid PRDF_HOM_SCAN
* @userdata1 PRD Return code = SCR_ACCESS_FAILED
* @userdata2 The invalid ID causing the fail
* @userdata3 Code location = 0x0001
* @devdesc Access Scan failed due to an invalid function unit
* @procedure EPUB_PRC_SP_CODE
*/
// create an error log
PRDF_CREATE_ERRL(errH,
ERRL_SEV_PREDICTIVE, // error on diagnostic
ERRL_ETYPE_NOT_APPLICABLE,
SRCI_MACH_CHECK,
SRCI_NO_ATTR,
PRDF_HOM_SCAN, // module id
FSP_DEFAULT_REFCODE, // refcode What do we use???
PRDF_CODE_FAIL, // Reason code
SCR_ACCESS_FAILED, // user data word 1
l_chipHUID, // user data word 2
0x0001, // user data word 3
0x0000 // user data word 4
);
}
}
// PRD does not ever expect to write scan rings - create an error log
else
{
PRDF_ERR( "HomRegisterAccessScan::Access "
"only scan read is supported. Invalid Scan Op: 0x%.8X", operation );
/*@
* @errortype
* @subsys EPUB_FIRMWARE_SP
* @reasoncode PRDF_UNSUPPORTED_SCAN_WRITE
* @moduleid PRDF_HOM_SCAN
* @userdata1 PRD Return code = SCR_ACCESS_FAILED
* @userdata2 The ID for the scan
* @userdata3 Code location = 0x0002
* @devdesc Access Scan failed. PRD does not ever expect to write scan rings.
* @procedure EPUB_PRC_SP_CODE
*/
// create an error log
PRDF_CREATE_ERRL(errH,
ERRL_SEV_PREDICTIVE, // error on diagnostic
ERRL_ETYPE_NOT_APPLICABLE,
SRCI_MACH_CHECK,
SRCI_NO_ATTR,
PRDF_HOM_SCAN, // module id
FSP_DEFAULT_REFCODE, // refcode What do we use???
PRDF_UNSUPPORTED_SCAN_WRITE, // Reason code
SCR_ACCESS_FAILED, // user data word 1
l_chipHUID, // user data word 2
0x0002, // user data word 3
0x0000 // user data word 4
);
}
if(errH)
{
rc = PRD_SCANCOM_FAILURE;
PRDF_ADD_SW_ERR(errH, rc, PRDF_HOM_SCAN, __LINE__);
PRDF_ADD_PROCEDURE_CALLOUT(errH, SRCI_PRIORITY_MED, EPUB_PRC_SP_CODE);
bool l_isAbort = false;
PRDF_ABORTING(l_isAbort);
if (!l_isAbort)
{
PRDF_COMMIT_ERRL(errH, ERRL_ACTION_SA|ERRL_ACTION_REPORT);
}
else
{
delete errH;
errH = NULL;
}
}
return rc;
}
} // End namespace PRDF
<commit_msg>PRD: changed include for HWSV SCOM code<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/usr/diag/prdf/common/framework/register/prdfHomRegisterAccess.C $ */
/* */
/* IBM CONFIDENTIAL */
/* */
/* COPYRIGHT International Business Machines Corp. 2002,2013 */
/* */
/* p1 */
/* */
/* Object Code Only (OCO) source materials */
/* Licensed Internal Code Source Materials */
/* IBM HostBoot Licensed Internal Code */
/* */
/* The source code for this program is not published or otherwise */
/* divested of its trade secrets, irrespective of what has been */
/* deposited with the U.S. Copyright Office. */
/* */
/* Origin: 30 */
/* */
/* IBM_PROLOG_END_TAG */
/**
@file prdfHomRegisterAccess.C
@brief definition of HomRegisterAccess
*/
//----------------------------------------------------------------------
// Includes
//----------------------------------------------------------------------
#define prdfHomRegisterAccess_C
#ifdef __HOSTBOOT_MODULE
#include <ecmdDataBufferBase.H>
#include <fapi.H>
#include <errlmanager.H>
#include <devicefw/userif.H>
#include <targeting/common/targetservice.H>
#else
#include <ecmdDataBuffer.H>
#include <hwcoScanScom.H>
#include <chicservlib.H>
#include <hwsvExecutionService.H>
#endif
#include <prdfHomRegisterAccess.H>
#include <prdf_service_codes.H>
#include <iipbits.h>
#include <iipglobl.h>
#include <prdfMain.H>
#include <prdfPlatServices.H>
#undef prdfHomRegisterAccess_C
namespace PRDF
{
//----------------------------------------------------------------------
// User Types
//----------------------------------------------------------------------
//----------------------------------------------------------------------
// Constants
//----------------------------------------------------------------------
//----------------------------------------------------------------------
// Macros
//----------------------------------------------------------------------
//----------------------------------------------------------------------
// Internal Function Prototypes
//----------------------------------------------------------------------
//----------------------------------------------------------------------
// Global Variables
//----------------------------------------------------------------------
//------------------------------------------------------------------------------
// Member Function Specifications
//------------------------------------------------------------------------------
ScomService& getScomService()
{
return PRDF_GET_SINGLETON(theScomService);
}
ScomService::ScomService() :
iv_ScomAccessor(NULL)
{
PRDF_DTRAC("ScomService() initializing default iv_ScomAccessor");
iv_ScomAccessor = new ScomAccessor();
}
ScomService::~ScomService()
{
if(NULL != iv_ScomAccessor)
{
PRDF_DTRAC("~ScomService() deleting iv_ScomAccessor");
delete iv_ScomAccessor;
iv_ScomAccessor = NULL;
}
}
void ScomService::setScomAccessor(ScomAccessor & i_ScomAccessor)
{
PRDF_DTRAC("ScomService::setScomAccessor() setting new scom accessor");
if(NULL != iv_ScomAccessor)
{
PRDF_TRAC("ScomService::setScomAccessor() deleting old iv_ScomAccessor");
delete iv_ScomAccessor;
iv_ScomAccessor = NULL;
}
iv_ScomAccessor = &i_ScomAccessor;
}
uint32_t ScomService::Access(TARGETING::TargetHandle_t i_target,
BIT_STRING_CLASS & bs,
uint64_t registerId,
MopRegisterAccess::Operation operation) const
{
PRDF_DENTER("ScomService::Access()");
uint32_t rc = iv_ScomAccessor->Access(i_target,
bs,
registerId,
operation);
PRDF_DEXIT("ScomService::Access(): rc=%d", rc);
return rc;
}
uint32_t ScomAccessor::Access(TARGETING::TargetHandle_t i_target,
BIT_STRING_CLASS & bs,
uint64_t registerId,
MopRegisterAccess::Operation operation) const
{
PRDF_DENTER("ScomAccessor::Access()");
uint32_t rc = SUCCESS;
errlHndl_t errH = NULL;
uint32_t bsize = bs.GetLength();
uint32_t l_ecmdRc = ECMD_DBUF_SUCCESS;
if(i_target != NULL)
{
#ifdef __HOSTBOOT_MODULE
ecmdDataBufferBase buffer(bsize);
uint64_t l_data = 0;
size_t l_size = sizeof(uint64_t);
#else
ecmdDataBuffer buffer(bsize);
#endif
switch (operation)
{
case MopRegisterAccess::WRITE:
for(unsigned int i = 0; i < bsize; ++i)
{
if(bs.IsSet(i)) buffer.setBit(i);
}
// FIXME: If register is in a EX chiplet, need to also update
// PORE image ????
#ifdef __HOSTBOOT_MODULE
l_data = buffer.getDoubleWord(0);
errH = deviceWrite( i_target,
&l_data,
l_size,
DEVICE_SCOM_ADDRESS(registerId));
#else
errH = HWSV::hwsvPutScom(i_target, registerId, buffer);
#endif
break;
case MopRegisterAccess::READ:
bs.Pattern(0x00000000); // clear all bits
#ifdef __HOSTBOOT_MODULE
errH = deviceRead( i_target, &l_data, l_size,
DEVICE_SCOM_ADDRESS(registerId) );
l_ecmdRc = buffer.setDoubleWord(0, l_data);
#else
errH = HWSV::hwsvGetScom(i_target, registerId, buffer);
#endif
for(unsigned int i = 0; i < bsize; ++i)
{
if(buffer.isBitSet(i)) bs.Set(i);
}
break;
default:
PRDF_ERR("ScomAccessor::Access() unsuppported scom op: 0x%08X", operation);
break;
} // end switch operation
}
else // Invalid target
{
/*@
* @errortype
* @subsys EPUB_FIRMWARE_SP
* @reasoncode PRDF_CODE_FAIL
* @moduleid PRDF_HOM_SCOM
* @userdata1 PRD Return code = SCR_ACCESS_FAILED
* @userdata2 The invalid ID causing the fail
* @devdesc Access SCOM failed due to NULL target handle
* @procedure EPUB_PRC_SP_CODE
*/
// create an error log
PRDF_CREATE_ERRL(errH,
ERRL_SEV_PREDICTIVE, // error on diagnostic
ERRL_ETYPE_NOT_APPLICABLE,
SRCI_MACH_CHECK,
SRCI_NO_ATTR,
PRDF_HOM_SCOM, // module id
FSP_DEFAULT_REFCODE, // refcode What do we use???
PRDF_CODE_FAIL, // Reason code
SCR_ACCESS_FAILED, // user data word 1
PlatServices::getHuid(i_target), // user data word 2
0x0000, // user data word 3
0x0000 // user data word 4
);
}
if(errH)
{
rc = PRD_SCANCOM_FAILURE;
PRDF_ADD_SW_ERR(errH, rc, PRDF_HOM_SCOM, __LINE__);
PRDF_ADD_PROCEDURE_CALLOUT(errH, SRCI_PRIORITY_MED, EPUB_PRC_SP_CODE);
bool l_isAbort = false;
PRDF_ABORTING(l_isAbort);
if (!l_isAbort)
{
PRDF_COMMIT_ERRL(errH, ERRL_ACTION_SA|ERRL_ACTION_REPORT);
}
else
{
delete errH;
errH = NULL;
}
}
if (l_ecmdRc != ECMD_DBUF_SUCCESS)
{
PRDF_ERR( "ScomAccessor::Access ecmdDataBuffer "
"operation failed with ecmd_rc = 0x%.8X", l_ecmdRc );
/*@
* @errortype
* @subsys EPUB_FIRMWARE_SP
* @reasoncode PRDF_ECMD_DATA_BUFFER_FAIL
* @moduleid PRDF_HOM_SCOM
* @userdata1 ecmdDataBuffer return code
* @userdata2 Chip HUID
* @userdata3 unused
* @userdata4 unused
* @devdesc Low-level data buffer support returned a failure. Probable firmware error.
* @procedure EPUB_PRC_SP_CODE
*/
errlHndl_t ecmd_rc_errl = NULL;
PRDF_CREATE_ERRL(ecmd_rc_errl,
ERRL_SEV_PREDICTIVE, // error on diagnosticERRL_ETYPE_NOT_APPLICABLE
ERRL_ETYPE_NOT_APPLICABLE,
SRCI_MACH_CHECK, // B1xx src
SRCI_NO_ATTR,
PRDF_HOM_SCOM, // module id
FSP_DEFAULT_REFCODE, // refcode
PRDF_ECMD_DATA_BUFFER_FAIL, // Reason code - see prdf_service_codes.H
l_ecmdRc, // user data word 1
PlatServices::getHuid(i_target), // user data word 2
0, // user data word 3
0 // user data word 4
);
PRDF_ADD_PROCEDURE_CALLOUT(ecmd_rc_errl, SRCI_PRIORITY_MED, EPUB_PRC_SP_CODE);
PRDF_COMMIT_ERRL(ecmd_rc_errl, ERRL_ACTION_REPORT);
rc = FAIL;
}
PRDF_DEXIT("ScomAccessor::Access(): rc=%d", rc);
return rc;
}
//------------------------------------------------------------------------------
uint32_t HomRegisterAccessScom::Access( BIT_STRING_CLASS & bs,
uint64_t registerId,
Operation operation) const
{
PRDF_DENTER("HomRegisterAccessScom::Access()");
uint32_t rc = getScomService().Access(iv_ptargetHandle,
bs,
registerId,
operation);
PRDF_DEXIT("HomRegisterAccessScom::Access() rc=%d", rc);
return rc;
}
//------------------------------------------------------------------------------
HomRegisterAccessScan::HomRegisterAccessScan(
TARGETING::TargetHandle_t i_ptargetHandle,
ScanRingField * start, ScanRingField * end )
: MopRegisterAccess(), iv_punitHandle(i_ptargetHandle)
{
iv_aliasIds.reserve(end-start);
while(start != end)
{
iv_aliasIds.push_back(*start);
++start;
}
}
//------------------------------------------------------------------------------
uint32_t HomRegisterAccessScan::Access(BIT_STRING_CLASS & bs,
uint64_t registerId,
Operation operation) const
{
uint32_t rc = SUCCESS;
errlHndl_t errH = NULL;
HUID l_chipHUID = PlatServices::getHuid(iv_punitHandle);
if(operation == MopRegisterAccess::READ)
{
if(iv_punitHandle != NULL)
{
#ifdef __HOSTBOOT_MODULE
ecmdDataBufferBase buf(bs.GetLength());
#else
ecmdDataBuffer buf(bs.GetLength());
#endif
uint32_t curbit = 0;
bs.Pattern(0x00000000); // clear desination bit string
for(AliasIdList::const_iterator i = iv_aliasIds.begin(); i != iv_aliasIds.end(); ++i)
{
for(uint32_t j = 0; j != i->length; ++j)
{
if(buf.isBitSet(j)) bs.Set(j+curbit);
}
curbit += i->length;
}
}
else
{
/*@
* @errortype
* @subsys EPUB_FIRMWARE_SP
* @reasoncode PRDF_CODE_FAIL
* @moduleid PRDF_HOM_SCAN
* @userdata1 PRD Return code = SCR_ACCESS_FAILED
* @userdata2 The invalid ID causing the fail
* @userdata3 Code location = 0x0001
* @devdesc Access Scan failed due to an invalid function unit
* @procedure EPUB_PRC_SP_CODE
*/
// create an error log
PRDF_CREATE_ERRL(errH,
ERRL_SEV_PREDICTIVE, // error on diagnostic
ERRL_ETYPE_NOT_APPLICABLE,
SRCI_MACH_CHECK,
SRCI_NO_ATTR,
PRDF_HOM_SCAN, // module id
FSP_DEFAULT_REFCODE, // refcode What do we use???
PRDF_CODE_FAIL, // Reason code
SCR_ACCESS_FAILED, // user data word 1
l_chipHUID, // user data word 2
0x0001, // user data word 3
0x0000 // user data word 4
);
}
}
// PRD does not ever expect to write scan rings - create an error log
else
{
PRDF_ERR( "HomRegisterAccessScan::Access "
"only scan read is supported. Invalid Scan Op: 0x%.8X", operation );
/*@
* @errortype
* @subsys EPUB_FIRMWARE_SP
* @reasoncode PRDF_UNSUPPORTED_SCAN_WRITE
* @moduleid PRDF_HOM_SCAN
* @userdata1 PRD Return code = SCR_ACCESS_FAILED
* @userdata2 The ID for the scan
* @userdata3 Code location = 0x0002
* @devdesc Access Scan failed. PRD does not ever expect to write scan rings.
* @procedure EPUB_PRC_SP_CODE
*/
// create an error log
PRDF_CREATE_ERRL(errH,
ERRL_SEV_PREDICTIVE, // error on diagnostic
ERRL_ETYPE_NOT_APPLICABLE,
SRCI_MACH_CHECK,
SRCI_NO_ATTR,
PRDF_HOM_SCAN, // module id
FSP_DEFAULT_REFCODE, // refcode What do we use???
PRDF_UNSUPPORTED_SCAN_WRITE, // Reason code
SCR_ACCESS_FAILED, // user data word 1
l_chipHUID, // user data word 2
0x0002, // user data word 3
0x0000 // user data word 4
);
}
if(errH)
{
rc = PRD_SCANCOM_FAILURE;
PRDF_ADD_SW_ERR(errH, rc, PRDF_HOM_SCAN, __LINE__);
PRDF_ADD_PROCEDURE_CALLOUT(errH, SRCI_PRIORITY_MED, EPUB_PRC_SP_CODE);
bool l_isAbort = false;
PRDF_ABORTING(l_isAbort);
if (!l_isAbort)
{
PRDF_COMMIT_ERRL(errH, ERRL_ACTION_SA|ERRL_ACTION_REPORT);
}
else
{
delete errH;
errH = NULL;
}
}
return rc;
}
} // End namespace PRDF
<|endoftext|>
|
<commit_before>//======================================================================
//-----------------------------------------------------------------------
/**
* @file record_property_tests.cpp
* @brief iutest RecordProperty 対応テスト
*
* @author t.shirayanagi
* @par copyright
* Copyright (C) 2013-2018, Takazumi Shirayanagi\n
* This software is released under the new BSD License,
* see LICENSE
*/
//-----------------------------------------------------------------------
//======================================================================
//======================================================================
// include
#include "iutest.hpp"
#include "../include/iutest_spi.hpp"
#if !IUTEST_HAS_ASSERTION_RETURN
void CheckProperty_(const ::iutest::TestResult* tr, const char* key, const char* value)
{
if( tr != NULL )
{
IUTEST_ASSERT_EQ(1, tr->test_property_count());
IUTEST_EXPECT_STREQ(key, tr->GetTestProperty(0).key());
IUTEST_EXPECT_STREQ(value, tr->GetTestProperty(0).value());
}
}
#endif
bool CheckProperty(const ::iutest::TestResult* tr, const char* key, const char* value)
{
#if IUTEST_USE_THROW_ON_ASSERTION_FAILURE
try {
#endif
#if IUTEST_HAS_ASSERTION_RETURN
if( tr != NULL )
{
IUTEST_ASSERT_EQ(1, tr->test_property_count()) << ::iutest::AssertionReturn<bool>(false);
IUTEST_EXPECT_STREQ(key, tr->GetTestProperty(0).key()) << ::iutest::AssertionReturn<bool>(false);
IUTEST_EXPECT_STREQ(value, tr->GetTestProperty(0).value()) << ::iutest::AssertionReturn<bool>(false);
}
#else
CheckProperty_(tr, key, value);
#endif
#if IUTEST_USE_THROW_ON_ASSERTION_FAILURE
} catch(...) {}
#endif
return ::iutest::UnitTest::GetInstance()->Passed();
}
class RecordTest : public ::iutest::Test
{
public:
static void SetUpTestCase()
{
RecordProperty("foo", "A");
#if !defined(IUTEST_USE_GTEST)
// ban list
IUTEST_EXPECT_NONFATAL_FAILURE( RecordProperty("name" , "A"), "Reserved key");
IUTEST_EXPECT_NONFATAL_FAILURE( RecordProperty("tests" , "A"), "Reserved key");
IUTEST_EXPECT_NONFATAL_FAILURE( RecordProperty("failures" , "A"), "Reserved key");
IUTEST_EXPECT_NONFATAL_FAILURE( RecordProperty("disabled" , "A"), "Reserved key");
IUTEST_EXPECT_NONFATAL_FAILURE( RecordProperty("skip" , "A"), "Reserved key");
IUTEST_EXPECT_NONFATAL_FAILURE( RecordProperty("errors" , "A"), "Reserved key");
IUTEST_EXPECT_NONFATAL_FAILURE( RecordProperty("time" , "A"), "Reserved key");
#endif
CheckProperty(::iuutil::GetCurrentTestCaseAdHocResult(), "foo", "A");
}
};
IUTEST_F(RecordTest, A)
{
RecordProperty("hoge", "B");
#if !defined(IUTEST_USE_GTEST)
// ban list
IUTEST_EXPECT_NONFATAL_FAILURE( RecordProperty("name" , "B"), "Reserved key");
IUTEST_EXPECT_NONFATAL_FAILURE( RecordProperty("status" , "B"), "Reserved key");
IUTEST_EXPECT_NONFATAL_FAILURE( RecordProperty("time" , "B"), "Reserved key");
IUTEST_EXPECT_NONFATAL_FAILURE( RecordProperty("classname" , "B"), "Reserved key");
IUTEST_EXPECT_NONFATAL_FAILURE( RecordProperty("type_param" , "B"), "Reserved key");
IUTEST_EXPECT_NONFATAL_FAILURE( RecordProperty("value_param", "B"), "Reserved key");
#endif
CheckProperty(::iuutil::GetCurrentTestResult(), "hoge", "B");
// overwrite
RecordProperty("hoge", "b");
CheckProperty(::iuutil::GetCurrentTestResult(), "hoge", "b");
}
#ifdef UNICODE
int wmain(int argc, wchar_t* argv[])
#else
int main(int argc, char* argv[])
#endif
{
IUTEST_INIT(&argc, argv);
::iutest::Test::RecordProperty("bar", "C");
#if !defined(IUTEST_USE_GTEST)
// ban list
IUTEST_EXPECT_NONFATAL_FAILURE( ::iutest::Test::RecordProperty("name" , "C"), "Reserved key");
IUTEST_EXPECT_NONFATAL_FAILURE( ::iutest::Test::RecordProperty("tests" , "C"), "Reserved key");
IUTEST_EXPECT_NONFATAL_FAILURE( ::iutest::Test::RecordProperty("failures" , "C"), "Reserved key");
IUTEST_EXPECT_NONFATAL_FAILURE( ::iutest::Test::RecordProperty("disabled" , "C"), "Reserved key");
IUTEST_EXPECT_NONFATAL_FAILURE( ::iutest::Test::RecordProperty("skip" , "C"), "Reserved key");
IUTEST_EXPECT_NONFATAL_FAILURE( ::iutest::Test::RecordProperty("errors" , "C"), "Reserved key");
IUTEST_EXPECT_NONFATAL_FAILURE( ::iutest::Test::RecordProperty("time" , "C"), "Reserved key");
IUTEST_EXPECT_NONFATAL_FAILURE( ::iutest::Test::RecordProperty("timestamp" , "C"), "Reserved key");
IUTEST_EXPECT_NONFATAL_FAILURE( ::iutest::Test::RecordProperty("random_seed", "C"), "Reserved key");
#endif
{
const int ret = IUTEST_RUN_ALL_TESTS();
if( ret != 0 ) return 1;
#if !defined(IUTEST_NO_RECORDPROPERTY_OUTSIDE_TESTMETHOD_LIFESPAN)
if( !CheckProperty(iuutil::GetAdHocTestResult(), "bar", "C") )
{
printf("ad hoc test result is not recorded");
return 1;
}
#endif
}
#if !defined(IUTEST_NO_RECORDPROPERTY_OUTSIDE_TESTMETHOD_LIFESPAN)
{
const int ret = IUTEST_RUN_ALL_TESTS();
if( ret != 0 ) return 1;
if( !CheckProperty(iuutil::GetAdHocTestResult(), "bar", "C") )
{
printf("ad hoc test result is cleared?");
return 1;
}
}
{
IUTEST_INIT(&argc, argv);
const int ret = IUTEST_RUN_ALL_TESTS();
if( ret != 0 ) return 1;
if( CheckProperty(iuutil::GetAdHocTestResult(), "bar", "C") )
{
printf("ad hoc test result is not cleared?");
return 1;
}
}
#endif
printf("*** Successful ***\n");
return 0;
}
<commit_msg>fix test #56<commit_after>//======================================================================
//-----------------------------------------------------------------------
/**
* @file record_property_tests.cpp
* @brief iutest RecordProperty 対応テスト
*
* @author t.shirayanagi
* @par copyright
* Copyright (C) 2013-2018, Takazumi Shirayanagi\n
* This software is released under the new BSD License,
* see LICENSE
*/
//-----------------------------------------------------------------------
//======================================================================
//======================================================================
// include
#include "iutest.hpp"
#include "../include/iutest_spi.hpp"
#if !IUTEST_HAS_ASSERTION_RETURN
void CheckProperty_(const ::iutest::TestResult* tr, const char* key, const char* value)
{
if( tr != NULL )
{
IUTEST_ASSERT_EQ(1, tr->test_property_count());
IUTEST_EXPECT_STREQ(key, tr->GetTestProperty(0).key());
IUTEST_EXPECT_STREQ(value, tr->GetTestProperty(0).value());
}
}
#endif
bool CheckProperty(const ::iutest::TestResult* tr, const char* key, const char* value)
{
#if IUTEST_USE_THROW_ON_ASSERTION_FAILURE
try {
#endif
#if IUTEST_HAS_ASSERTION_RETURN
if( tr != NULL )
{
IUTEST_ASSERT_EQ(1, tr->test_property_count()) << ::iutest::AssertionReturn<bool>(false);
IUTEST_EXPECT_STREQ(key, tr->GetTestProperty(0).key()) << ::iutest::AssertionReturn<bool>(false);
IUTEST_EXPECT_STREQ(value, tr->GetTestProperty(0).value()) << ::iutest::AssertionReturn<bool>(false);
}
#else
CheckProperty_(tr, key, value);
#endif
#if IUTEST_USE_THROW_ON_ASSERTION_FAILURE
} catch(...) {}
#endif
return ::iutest::UnitTest::GetInstance()->Passed();
}
class RecordTest : public ::iutest::Test
{
public:
static void SetUpTestCase()
{
RecordProperty("foo", "A");
#if !defined(IUTEST_USE_GTEST)
// ban list
IUTEST_EXPECT_NONFATAL_FAILURE( RecordProperty("name" , "A"), "Reserved key");
IUTEST_EXPECT_NONFATAL_FAILURE( RecordProperty("tests" , "A"), "Reserved key");
IUTEST_EXPECT_NONFATAL_FAILURE( RecordProperty("failures" , "A"), "Reserved key");
IUTEST_EXPECT_NONFATAL_FAILURE( RecordProperty("disabled" , "A"), "Reserved key");
IUTEST_EXPECT_NONFATAL_FAILURE( RecordProperty("skip" , "A"), "Reserved key");
IUTEST_EXPECT_NONFATAL_FAILURE( RecordProperty("errors" , "A"), "Reserved key");
IUTEST_EXPECT_NONFATAL_FAILURE( RecordProperty("time" , "A"), "Reserved key");
#endif
CheckProperty(::iuutil::GetCurrentTestCaseAdHocResult(), "foo", "A");
}
};
IUTEST_F(RecordTest, A)
{
RecordProperty("hoge", "B");
#if !defined(IUTEST_USE_GTEST)
// ban list
IUTEST_EXPECT_NONFATAL_FAILURE( RecordProperty("name" , "B"), "Reserved key");
IUTEST_EXPECT_NONFATAL_FAILURE( RecordProperty("status" , "B"), "Reserved key");
IUTEST_EXPECT_NONFATAL_FAILURE( RecordProperty("time" , "B"), "Reserved key");
IUTEST_EXPECT_NONFATAL_FAILURE( RecordProperty("classname" , "B"), "Reserved key");
IUTEST_EXPECT_NONFATAL_FAILURE( RecordProperty("type_param" , "B"), "Reserved key");
IUTEST_EXPECT_NONFATAL_FAILURE( RecordProperty("value_param", "B"), "Reserved key");
#endif
CheckProperty(::iuutil::GetCurrentTestResult(), "hoge", "B");
// overwrite
RecordProperty("hoge", "b");
CheckProperty(::iuutil::GetCurrentTestResult(), "hoge", "b");
}
#ifdef UNICODE
int wmain(int argc, wchar_t* argv[])
#else
int main(int argc, char* argv[])
#endif
{
IUTEST_INIT(&argc, argv);
::iutest::Test::RecordProperty("bar", "C");
#if !defined(IUTEST_USE_GTEST)
// ban list
IUTEST_EXPECT_NONFATAL_FAILURE( ::iutest::Test::RecordProperty("name" , "C"), "Reserved key");
IUTEST_EXPECT_NONFATAL_FAILURE( ::iutest::Test::RecordProperty("tests" , "C"), "Reserved key");
IUTEST_EXPECT_NONFATAL_FAILURE( ::iutest::Test::RecordProperty("failures" , "C"), "Reserved key");
IUTEST_EXPECT_NONFATAL_FAILURE( ::iutest::Test::RecordProperty("disabled" , "C"), "Reserved key");
IUTEST_EXPECT_NONFATAL_FAILURE( ::iutest::Test::RecordProperty("skip" , "C"), "Reserved key");
IUTEST_EXPECT_NONFATAL_FAILURE( ::iutest::Test::RecordProperty("errors" , "C"), "Reserved key");
IUTEST_EXPECT_NONFATAL_FAILURE( ::iutest::Test::RecordProperty("time" , "C"), "Reserved key");
IUTEST_EXPECT_NONFATAL_FAILURE( ::iutest::Test::RecordProperty("timestamp" , "C"), "Reserved key");
IUTEST_EXPECT_NONFATAL_FAILURE( ::iutest::Test::RecordProperty("random_seed", "C"), "Reserved key");
#endif
{
const int ret = IUTEST_RUN_ALL_TESTS();
if( ret != 0 ) return 1;
#if !defined(IUTEST_NO_RECORDPROPERTY_OUTSIDE_TESTMETHOD_LIFESPAN)
if( !CheckProperty(iuutil::GetAdHocTestResult(), "bar", "C") )
{
printf("ad hoc test result is not recorded\n");
return 1;
}
#endif
}
#if !defined(IUTEST_NO_RECORDPROPERTY_OUTSIDE_TESTMETHOD_LIFESPAN)
{
const int ret = IUTEST_RUN_ALL_TESTS();
if( ret != 0 ) return 1;
if( !CheckProperty(iuutil::GetAdHocTestResult(), "bar", "C") )
{
printf("ad hoc test result is cleared?\n");
return 1;
}
}
{
IUTEST_INIT(&argc, argv);
const int ret = IUTEST_RUN_ALL_TESTS();
if( ret != 0 ) return 1;
#if !defined(IUTEST_USE_GTEST)
if( CheckProperty(iuutil::GetAdHocTestResult(), "bar", "C") )
{
printf("ad hoc test result is not cleared?\n");
return 1;
}
#else
if( !CheckProperty(iuutil::GetAdHocTestResult(), "bar", "C") )
{
printf("ad hoc test result is cleared? (iutest expect)\n");
return 1;
}
#endif
}
#endif
printf("*** Successful ***\n");
return 0;
}
<|endoftext|>
|
<commit_before>#include <unistd.h>
#include <process.hpp>
#include <iostream>
#include <climits>
#include <cstdlib>
#include <stdexcept>
#include <glog/logging.h>
#include <boost/lexical_cast.hpp>
#include "fatal.hpp"
#include "master_detector.hpp"
#include "messages.hpp"
using namespace nexus;
using namespace nexus::internal;
using boost::lexical_cast;
MasterDetector::MasterDetector(const string &_servers, const string &_znode,
const PID &_pid, bool _contend)
: servers(_servers), znode(_znode), pid(_pid), contend(_contend)
{
zk = new ZooKeeper(servers, 10000, this);
}
MasterDetector::~MasterDetector()
{
if (zk != NULL)
delete zk;
}
void MasterDetector::process(ZooKeeper *zk, int type, int state,
const string &path)
{
int ret;
string result;
static const string delimiter = "/";
if ((state == ZOO_CONNECTED_STATE) && (type == ZOO_SESSION_EVENT)) {
// Create directory path znodes as necessary.
size_t index = znode.find(delimiter, 0);
while (index < string::npos) {
index = znode.find(delimiter, index+1);
string prefix = znode.substr(0, index);
ret = zk->create(prefix, "", ZOO_OPEN_ACL_UNSAFE, // ZOO_CREATOR_ALL_ACL, // needs authentication
0, &result);
if (ret != ZOK && ret != ZNODEEXISTS)
fatal("failed to create ZooKeeper znode! (%s)", zk->error(ret));
}
// Wierdness in ZooKeeper timing, let's check that everything is created.
ret = zk->get(znode, false, &result, NULL);
if (ret != ZOK)
fatal("ZooKeeper not responding correctly (%s). "
"Make sure ZooKeeper is running on: %s",
zk->error(ret), servers.c_str());
if (contend) {
// We use the contend with the pid given in constructor.
ret = zk->create(znode, pid, ZOO_OPEN_ACL_UNSAFE, // ZOO_CREATOR_ALL_ACL, // needs authentication
ZOO_SEQUENCE | ZOO_EPHEMERAL, &result);
if (ret != ZOK)
fatal("ZooKeeper not responding correctly (%s). "
"Make sure ZooKeeper is running on: %s",
zk->error(ret), servers.c_str());
setMySeq(result);
LOG(INFO) << "Created ephemeral/sequence:" << getMySeq();
const string &s =
Tuple<Process>::tupleToString(Tuple<Process>::pack<GOT_MASTER_SEQ>(getMySeq()));
Process::post(pid, GOT_MASTER_SEQ, s.data(), s.size());
}
detectMaster();
} else if ((state == ZOO_CONNECTED_STATE) && (type == ZOO_CHILD_EVENT)) {
detectMaster();
} else {
LOG(INFO) << "Unimplemented watch event: (state is "
<< state << " and type is " << type << ")";
}
}
void MasterDetector::detectMaster()
{
vector<string> results;
int ret = zk->getChildren(znode, true, &results);
if (ret != ZOK)
LOG(ERROR) << "failed to get masters: " << zk->error(ret);
else
LOG(INFO) << "found " << results.size() << " registered masters";
string masterSeq;
long min = LONG_MAX;
foreach (const string &result, results) {
int i = lexical_cast<int>(result);
if (i < min) {
min = i;
masterSeq = result;
}
}
// No master present (lost or possibly hasn't come up yet).
if (masterSeq.empty()) {
const string &s =
Tuple<Process>::tupleToString(Tuple<Process>::pack<NO_MASTER_DETECTED>());
Process::post(pid, NO_MASTER_DETECTED, s.data(), s.size());
} else if (masterSeq != currentMasterSeq) {
currentMasterSeq = masterSeq;
currentMasterPID = lookupMasterPID(masterSeq);
// While trying to get the master PID, master might have crashed,
// so PID might be empty.
if (currentMasterPID == PID()) {
const string &s =
Tuple<Process>::tupleToString(Tuple<Process>::pack<NO_MASTER_DETECTED>());
Process::post(pid, NO_MASTER_DETECTED, s.data(), s.size());
} else {
const string &s =
Tuple<Process>::tupleToString(Tuple<Process>::pack<NEW_MASTER_DETECTED>(currentMasterSeq, currentMasterPID));
Process::post(pid, NEW_MASTER_DETECTED, s.data(), s.size());
}
}
}
PID MasterDetector::lookupMasterPID(const string &seq) const
{
CHECK(!seq.empty());
int ret;
string result;
ret = zk->get(znode + seq, false, &result, NULL);
if (ret != ZOK)
LOG(ERROR) << "failed to fetch new master pid: " << zk->error(ret);
else
LOG(INFO) << "got new master pid: " << result;
// TODO(benh): Automatic cast!
return make_pid(result.c_str());
}
string MasterDetector::getCurrentMasterSeq() const {
return currentMasterSeq;
}
PID MasterDetector::getCurrentMasterPID() const {
return currentMasterPID;
}
<commit_msg>Another bug in the new FT port. Slash was missing after the /nxmaster znode making the master id parser go nuts.<commit_after>#include <unistd.h>
#include <process.hpp>
#include <iostream>
#include <climits>
#include <cstdlib>
#include <stdexcept>
#include <glog/logging.h>
#include <boost/lexical_cast.hpp>
#include "fatal.hpp"
#include "master_detector.hpp"
#include "messages.hpp"
using namespace nexus;
using namespace nexus::internal;
using boost::lexical_cast;
MasterDetector::MasterDetector(const string &_servers, const string &_znode,
const PID &_pid, bool _contend)
: servers(_servers), znode(_znode), pid(_pid), contend(_contend)
{
zk = new ZooKeeper(servers, 10000, this);
}
MasterDetector::~MasterDetector()
{
if (zk != NULL)
delete zk;
}
void MasterDetector::process(ZooKeeper *zk, int type, int state,
const string &path)
{
int ret;
string result;
static const string delimiter = "/";
if ((state == ZOO_CONNECTED_STATE) && (type == ZOO_SESSION_EVENT)) {
// Create directory path znodes as necessary.
size_t index = znode.find(delimiter, 0);
while (index < string::npos) {
index = znode.find(delimiter, index+1);
string prefix = znode.substr(0, index);
ret = zk->create(prefix, "", ZOO_OPEN_ACL_UNSAFE, // ZOO_CREATOR_ALL_ACL, // needs authentication
0, &result);
if (ret != ZOK && ret != ZNODEEXISTS)
fatal("failed to create ZooKeeper znode! (%s)", zk->error(ret));
}
// Wierdness in ZooKeeper timing, let's check that everything is created.
ret = zk->get(znode, false, &result, NULL);
if (ret != ZOK)
fatal("ZooKeeper not responding correctly (%s). "
"Make sure ZooKeeper is running on: %s",
zk->error(ret), servers.c_str());
if (contend) {
// We use the contend with the pid given in constructor.
ret = zk->create(znode, pid, ZOO_OPEN_ACL_UNSAFE, // ZOO_CREATOR_ALL_ACL, // needs authentication
ZOO_SEQUENCE | ZOO_EPHEMERAL, &result);
if (ret != ZOK)
fatal("ZooKeeper not responding correctly (%s). "
"Make sure ZooKeeper is running on: %s",
zk->error(ret), servers.c_str());
setMySeq(result);
LOG(INFO) << "Created ephemeral/sequence:" << getMySeq();
const string &s =
Tuple<Process>::tupleToString(Tuple<Process>::pack<GOT_MASTER_SEQ>(getMySeq()));
Process::post(pid, GOT_MASTER_SEQ, s.data(), s.size());
}
detectMaster();
} else if ((state == ZOO_CONNECTED_STATE) && (type == ZOO_CHILD_EVENT)) {
detectMaster();
} else {
LOG(INFO) << "Unimplemented watch event: (state is "
<< state << " and type is " << type << ")";
}
}
void MasterDetector::detectMaster()
{
vector<string> results;
int ret = zk->getChildren(znode, true, &results);
if (ret != ZOK)
LOG(ERROR) << "failed to get masters: " << zk->error(ret);
else
LOG(INFO) << "found " << results.size() << " registered masters";
string masterSeq;
long min = LONG_MAX;
foreach (const string &result, results) {
int i = lexical_cast<int>(result);
if (i < min) {
min = i;
masterSeq = result;
}
}
// No master present (lost or possibly hasn't come up yet).
if (masterSeq.empty()) {
const string &s =
Tuple<Process>::tupleToString(Tuple<Process>::pack<NO_MASTER_DETECTED>());
Process::post(pid, NO_MASTER_DETECTED, s.data(), s.size());
} else if (masterSeq != currentMasterSeq) {
currentMasterSeq = masterSeq;
currentMasterPID = lookupMasterPID(masterSeq);
// While trying to get the master PID, master might have crashed,
// so PID might be empty.
if (currentMasterPID == PID()) {
const string &s =
Tuple<Process>::tupleToString(Tuple<Process>::pack<NO_MASTER_DETECTED>());
Process::post(pid, NO_MASTER_DETECTED, s.data(), s.size());
} else {
const string &s =
Tuple<Process>::tupleToString(Tuple<Process>::pack<NEW_MASTER_DETECTED>(currentMasterSeq, currentMasterPID));
Process::post(pid, NEW_MASTER_DETECTED, s.data(), s.size());
}
}
}
PID MasterDetector::lookupMasterPID(const string &seq) const
{
CHECK(!seq.empty());
int ret;
string result;
ret = zk->get(znode + "/" + seq, false, &result, NULL);
if (ret != ZOK)
LOG(ERROR) << "failed to fetch new master pid: " << zk->error(ret);
else
LOG(INFO) << "got new master pid: " << result;
// TODO(benh): Automatic cast!
return make_pid(result.c_str());
}
string MasterDetector::getCurrentMasterSeq() const {
return currentMasterSeq;
}
PID MasterDetector::getCurrentMasterPID() const {
return currentMasterPID;
}
<|endoftext|>
|
<commit_before>//
// Z80AllRAM.cpp
// Clock Signal
//
// Created by Thomas Harte on 16/05/2017.
// Copyright © 2017 Thomas Harte. All rights reserved.
//
#include "Z80AllRAM.hpp"
#include <algorithm>
using namespace CPU::Z80;
AllRAMProcessor::AllRAMProcessor() : ::CPU::AllRAMProcessor(65536) {}
int AllRAMProcessor::perform_machine_cycle(const MachineCycle *cycle) {
switch(cycle->operation) {
case BusOperation::ReadOpcode:
printf("! ");
check_address_for_trap(*cycle->address);
case BusOperation::Read:
printf("r %04x [%02x] AF:%04x BC:%04x DE:%04x HL:%04x SP:%04x\n", *cycle->address, memory_[*cycle->address], get_value_of_register(CPU::Z80::Register::AF), get_value_of_register(CPU::Z80::Register::BC), get_value_of_register(CPU::Z80::Register::DE), get_value_of_register(CPU::Z80::Register::HL), get_value_of_register(CPU::Z80::Register::StackPointer));
*cycle->value = memory_[*cycle->address];
break;
case BusOperation::Write:
printf("w %04x\n", *cycle->address);
memory_[*cycle->address] = *cycle->value;
break;
case BusOperation::Internal:
break;
default:
printf("???\n");
break;
}
return 0;
}
<commit_msg>This logging has outlived its usefulness for now.<commit_after>//
// Z80AllRAM.cpp
// Clock Signal
//
// Created by Thomas Harte on 16/05/2017.
// Copyright © 2017 Thomas Harte. All rights reserved.
//
#include "Z80AllRAM.hpp"
#include <algorithm>
using namespace CPU::Z80;
AllRAMProcessor::AllRAMProcessor() : ::CPU::AllRAMProcessor(65536) {}
int AllRAMProcessor::perform_machine_cycle(const MachineCycle *cycle) {
switch(cycle->operation) {
case BusOperation::ReadOpcode:
// printf("! ");
check_address_for_trap(*cycle->address);
case BusOperation::Read:
// printf("r %04x [%02x] AF:%04x BC:%04x DE:%04x HL:%04x SP:%04x\n", *cycle->address, memory_[*cycle->address], get_value_of_register(CPU::Z80::Register::AF), get_value_of_register(CPU::Z80::Register::BC), get_value_of_register(CPU::Z80::Register::DE), get_value_of_register(CPU::Z80::Register::HL), get_value_of_register(CPU::Z80::Register::StackPointer));
*cycle->value = memory_[*cycle->address];
break;
case BusOperation::Write:
// printf("w %04x\n", *cycle->address);
memory_[*cycle->address] = *cycle->value;
break;
case BusOperation::Internal:
break;
default:
printf("???\n");
break;
}
return 0;
}
<|endoftext|>
|
<commit_before>// Ylikuutio - A 3D game and simulation engine.
//
// Copyright (C) 2015-2021 Antti Nuortimo.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
#ifndef __YLIKUUTIO_ONTOLOGY_FRAMEBUFFER_MODULE_HPP_INCLUDED
#define __YLIKUUTIO_ONTOLOGY_FRAMEBUFFER_MODULE_HPP_INCLUDED
#include "code/ylikuutio/opengl/ylikuutio_glew.hpp" // GLfloat, GLuint etc.
// Include standard headers
#include <stdint.h> // uint32_t etc.
namespace yli::ontology
{
struct FramebufferModuleStruct;
class FramebufferModule
{
public:
// constructor.
FramebufferModule(const yli::ontology::FramebufferModuleStruct& framebuffer_module_struct);
FramebufferModule(const FramebufferModule&) = delete; // Delete copy constructor.
FramebufferModule &operator=(const FramebufferModule&) = delete; // Delete copy assignment.
// destructor.
~FramebufferModule();
void create_framebuffer_object();
void bind() const;
bool get_is_initialized() const;
void initialize(const float red, const float green, const float blue, const float alpha);
// This method returns current `texture_width`.
uint32_t get_texture_width() const;
// This method sets `texture_width`.
void set_texture_width(const uint32_t texture_width);
// This method returns current `texture_height`.
uint32_t get_texture_height() const;
// This method sets `texture_height`.
void set_texture_height(const uint32_t texture_height);
bool get_in_use() const;
private:
uint32_t texture_width;
uint32_t texture_height;
GLuint framebuffer { 0 };
GLuint texture { 0 };
GLuint renderbuffer { 0 };
bool in_use;
bool is_initialized { false };
};
}
#endif
<commit_msg>`FramebufferModule`: make 1 parameter constructor `explicit`.<commit_after>// Ylikuutio - A 3D game and simulation engine.
//
// Copyright (C) 2015-2021 Antti Nuortimo.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
#ifndef __YLIKUUTIO_ONTOLOGY_FRAMEBUFFER_MODULE_HPP_INCLUDED
#define __YLIKUUTIO_ONTOLOGY_FRAMEBUFFER_MODULE_HPP_INCLUDED
#include "code/ylikuutio/opengl/ylikuutio_glew.hpp" // GLfloat, GLuint etc.
// Include standard headers
#include <stdint.h> // uint32_t etc.
namespace yli::ontology
{
struct FramebufferModuleStruct;
class FramebufferModule
{
public:
// constructor.
explicit FramebufferModule(const yli::ontology::FramebufferModuleStruct& framebuffer_module_struct);
FramebufferModule(const FramebufferModule&) = delete; // Delete copy constructor.
FramebufferModule &operator=(const FramebufferModule&) = delete; // Delete copy assignment.
// destructor.
~FramebufferModule();
void create_framebuffer_object();
void bind() const;
bool get_is_initialized() const;
void initialize(const float red, const float green, const float blue, const float alpha);
// This method returns current `texture_width`.
uint32_t get_texture_width() const;
// This method sets `texture_width`.
void set_texture_width(const uint32_t texture_width);
// This method returns current `texture_height`.
uint32_t get_texture_height() const;
// This method sets `texture_height`.
void set_texture_height(const uint32_t texture_height);
bool get_in_use() const;
private:
uint32_t texture_width;
uint32_t texture_height;
GLuint framebuffer { 0 };
GLuint texture { 0 };
GLuint renderbuffer { 0 };
bool in_use;
bool is_initialized { false };
};
}
#endif
<|endoftext|>
|
<commit_before>#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/time.h>
#include <util.h>
#include <FtdiLink.hh>
#include <Proto.hh>
class Handler : public ProtoHandler {
private:
uint8_t status;
bool done;
public:
virtual ~Handler() {}
void resetDone(void) {
done = false;
}
bool isDone(void) {
return done;
}
uint8_t getStatus(void) {
return status;
}
virtual void relay(uint8_t idx, uint8_t state) {
}
virtual void light(uint8_t idx, uint8_t val) {
}
virtual void dpot(uint8_t idx, uint8_t val) {
}
virtual void resp(struct proto_packet *pkt) {
switch (pkt->cmd) {
case PROTO_CMD_GET_STATUS:
case PROTO_CMD_SWITCH_QUERY:
case PROTO_CMD_ADC_QUERY_LO:
case PROTO_CMD_ADC_QUERY_HI:
status = pkt->val;
done = true;
break;
}
}
};
void usage(void)
{
fprintf(stderr,
"usage: sender (<command> <args>*)*\n"
"\n"
"commands:\n"
" get_status <addr>\n"
" get_switch <addr>\n"
" get_adc <addr> <idx>\n"
" set_relay <addr> <val>\n"
" clear_relay <addr> <val>\n"
" set_dpot <addr> <idx> <val>\n"
" set_addr <addr> <new_addr>\n");
}
bool get_uint8(char *s, uint8_t *val)
{
char *endp;
long v;
v = strtol(s, &endp, 0);
if (endp == NULL || endp == s)
return false;
if (v < 0 || v > 0xff)
return false;
*val = v & 0xff;
return true;
}
void do_read(Proto *p, Handler *h, uint8_t addr)
{
printf("do_read(0x%02x) =", addr);
h->resetDone();
p->getStatus(addr);
p->flush();
while (!h->isDone()) {
p->waitForMsg(100);
}
printf("0x%02x\n", h->getStatus());
}
void do_write(Proto *p, uint8_t addr)
{
printf("do_write(0x%02x)\n", addr);
p->setRelay(addr, 0x0);
}
static uint8_t addrs[] = {
0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99,
};
#define SEEEP 100000
int main(int argc, char *argv[])
{
FtdiLink link(0x0403, 0x6010, INTERFACE_A);
Handler h;
Proto p(&link, &h, NULL, 0, 0, true);
unsigned int i;
while (1) {
for (i = 0; i < ARRAY_SIZE(addrs); i++) {
p.updateRelay(addrs[i], 0x1);
p.flush();
usleep(100000);
p.updateRelay(addrs[i], 0x2);
p.flush();
usleep(100000);
if (addrs[i] == 0x99)
continue;
p.updateRelay(addrs[i], 0x4);
p.flush();
usleep(100000);
}
}
return 0;
}
<commit_msg>take sprakle poofers out of poofertest.cc and add define for delay<commit_after>#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/time.h>
#include <util.h>
#include <FtdiLink.hh>
#include <Proto.hh>
class Handler : public ProtoHandler {
private:
uint8_t status;
bool done;
public:
virtual ~Handler() {}
void resetDone(void) {
done = false;
}
bool isDone(void) {
return done;
}
uint8_t getStatus(void) {
return status;
}
virtual void relay(uint8_t idx, uint8_t state) {
}
virtual void light(uint8_t idx, uint8_t val) {
}
virtual void dpot(uint8_t idx, uint8_t val) {
}
virtual void resp(struct proto_packet *pkt) {
switch (pkt->cmd) {
case PROTO_CMD_GET_STATUS:
case PROTO_CMD_SWITCH_QUERY:
case PROTO_CMD_ADC_QUERY_LO:
case PROTO_CMD_ADC_QUERY_HI:
status = pkt->val;
done = true;
break;
}
}
};
void usage(void)
{
fprintf(stderr,
"usage: sender (<command> <args>*)*\n"
"\n"
"commands:\n"
" get_status <addr>\n"
" get_switch <addr>\n"
" get_adc <addr> <idx>\n"
" set_relay <addr> <val>\n"
" clear_relay <addr> <val>\n"
" set_dpot <addr> <idx> <val>\n"
" set_addr <addr> <new_addr>\n");
}
bool get_uint8(char *s, uint8_t *val)
{
char *endp;
long v;
v = strtol(s, &endp, 0);
if (endp == NULL || endp == s)
return false;
if (v < 0 || v > 0xff)
return false;
*val = v & 0xff;
return true;
}
void do_read(Proto *p, Handler *h, uint8_t addr)
{
printf("do_read(0x%02x) =", addr);
h->resetDone();
p->getStatus(addr);
p->flush();
while (!h->isDone()) {
p->waitForMsg(100);
}
printf("0x%02x\n", h->getStatus());
}
void do_write(Proto *p, uint8_t addr)
{
printf("do_write(0x%02x)\n", addr);
p->setRelay(addr, 0x0);
}
static uint8_t addrs[] = {
0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,// 0x98, 0x99,
};
#define SLEEP 100000
int main(int argc, char *argv[])
{
FtdiLink link(0x0403, 0x6010, INTERFACE_A);
Handler h;
Proto p(&link, &h, NULL, 0, 0, true);
unsigned int i;
while (1) {
for (i = 0; i < ARRAY_SIZE(addrs); i++) {
p.updateRelay(addrs[i], 0x1);
p.flush();
usleep(SLEEP);
p.updateRelay(addrs[i], 0x2);
p.flush();
usleep(SLEEP);
if (addrs[i] == 0x99)
continue;
p.updateRelay(addrs[i], 0x4);
p.flush();
usleep(SLEEP);
}
}
return 0;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2007, Mathieu Champlon
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met :
*
* . Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* . Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* . Neither the name of the copyright holders nor the names of the
* 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 THE COPYRIGHT
* OWNERS 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 <xeumeuleu/xml.hpp>
#ifdef _MSC_VER
# pragma warning( push, 0 )
#endif
#include <boost/date_time/posix_time/posix_time.hpp>
#ifdef _MSC_VER
# pragma warning( pop )
#endif
#include <iostream>
using namespace boost::posix_time;
namespace
{
// const int FILES = 100000;
// const int NODES = 1;
const int FILES = 1;
const int NODES = 1000000;
}
int main()
{
const ptime start = microsec_clock::local_time();
for( int file = 0; file < FILES; ++file )
{
xml::xofstream xos( "bench.xml" );
xos << xml::start( "root" );
for( int node = 0; node < NODES; ++node )
xos << xml::start( "element" )
<< 12.f
<< xml::attribute( "id", 27.f )
<< xml::end;
}
const time_duration duration = microsec_clock::local_time() - start;
std::cout << "duration : " << duration << std::endl;
return EXIT_SUCCESS;
}
<commit_msg>Updated benchmark to also compute reads<commit_after>/*
* Copyright (c) 2007, Mathieu Champlon
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met :
*
* . Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* . Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* . Neither the name of the copyright holders nor the names of the
* 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 THE COPYRIGHT
* OWNERS 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 <xeumeuleu/xml.hpp>
#ifdef _MSC_VER
# pragma warning( push, 0 )
#endif
#include <boost/date_time/posix_time/posix_time.hpp>
#ifdef _MSC_VER
# pragma warning( pop )
#endif
#include <iostream>
using namespace boost::posix_time;
namespace
{
// const int FILES = 100000;
// const int NODES = 1;
const int FILES = 1;
const int NODES = 1000000;
}
int main()
{
const ptime start = microsec_clock::local_time();
for( int file = 0; file < FILES; ++file )
{
{
xml::xofstream xos( "bench.xml" );
xos << xml::start( "root" );
for( int node = 0; node < NODES; ++node )
xos << xml::start( "element" )
<< 12.f
<< xml::attribute( "id", 27.f )
<< xml::end;
}
{
xml::xifstream xis( "bench.xml" );
xis >> xml::start( "root" );
float value;
for( int node = 0; node < NODES; ++node )
xis >> xml::start( "element" )
>> value
>> xml::attribute( "id", value )
>> xml::end;
}
}
const time_duration duration = microsec_clock::local_time() - start;
std::cout << "duration : " << duration << std::endl;
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>// RUN: clang-tidy -checks='-*,modernize-use-override' %s.nonexistent.cpp -- | FileCheck -check-prefix=CHECK1 -implicit-check-not='{{warning:|error:}}' %s
// RUN: clang-tidy -checks='-*,clang-diagnostic-*,google-explicit-constructor' %s -- -fan-unknown-option | FileCheck -check-prefix=CHECK2 -implicit-check-not='{{warning:|error:}}' %s
// RUN: clang-tidy -checks='-*,google-explicit-constructor,clang-diagnostic-literal-conversion' %s -- -fan-unknown-option | FileCheck -check-prefix=CHECK3 -implicit-check-not='{{warning:|error:}}' %s
// RUN: clang-tidy -checks='-*,modernize-use-override,clang-diagnostic-macro-redefined' %s -- -DMACRO_FROM_COMMAND_LINE | FileCheck -check-prefix=CHECK4 -implicit-check-not='{{warning:|error:}}' %s
// CHECK1: error: error reading '{{.*}}.nonexistent.cpp' [clang-diagnostic-error]
// CHECK2: error: unknown argument: '-fan-unknown-option' [clang-diagnostic-error]
// CHECK3: error: unknown argument: '-fan-unknown-option' [clang-diagnostic-error]
// CHECK2: :[[@LINE+2]]:9: warning: implicit conversion from 'double' to 'int' changes value from 1.5 to 1 [clang-diagnostic-literal-conversion]
// CHECK3: :[[@LINE+1]]:9: warning: implicit conversion from 'double' to 'int' changes value
int a = 1.5;
// CHECK2: :[[@LINE+2]]:11: warning: single-argument constructors must be marked explicit
// CHECK3: :[[@LINE+1]]:11: warning: single-argument constructors must be marked explicit
class A { A(int) {} };
#define MACRO_FROM_COMMAND_LINE
// CHECK4: :[[@LINE-1]]:9: warning: 'MACRO_FROM_COMMAND_LINE' macro redefined
<commit_msg>Modify test so that it looks for patterns in stderr as well<commit_after>// RUN: clang-tidy -checks='-*,modernize-use-override' %s.nonexistent.cpp -- | FileCheck -check-prefix=CHECK1 -implicit-check-not='{{warning:|error:}}' %s
// RUN: clang-tidy -checks='-*,clang-diagnostic-*,google-explicit-constructor' %s -- -fan-unknown-option 2>&1 | FileCheck -check-prefix=CHECK2 -implicit-check-not='{{warning:|error:}}' %s
// RUN: clang-tidy -checks='-*,google-explicit-constructor,clang-diagnostic-literal-conversion' %s -- -fan-unknown-option 2>&1 | FileCheck -check-prefix=CHECK3 -implicit-check-not='{{warning:|error:}}' %s
// RUN: clang-tidy -checks='-*,modernize-use-override,clang-diagnostic-macro-redefined' %s -- -DMACRO_FROM_COMMAND_LINE | FileCheck -check-prefix=CHECK4 -implicit-check-not='{{warning:|error:}}' %s
// CHECK1: error: error reading '{{.*}}.nonexistent.cpp' [clang-diagnostic-error]
// CHECK2: error: unknown argument: '-fan-unknown-option'
// CHECK3: error: unknown argument: '-fan-unknown-option'
// CHECK2: :[[@LINE+2]]:9: warning: implicit conversion from 'double' to 'int' changes value from 1.5 to 1 [clang-diagnostic-literal-conversion]
// CHECK3: :[[@LINE+1]]:9: warning: implicit conversion from 'double' to 'int' changes value
int a = 1.5;
// CHECK2: :[[@LINE+2]]:11: warning: single-argument constructors must be marked explicit
// CHECK3: :[[@LINE+1]]:11: warning: single-argument constructors must be marked explicit
class A { A(int) {} };
#define MACRO_FROM_COMMAND_LINE
// CHECK4: :[[@LINE-1]]:9: warning: 'MACRO_FROM_COMMAND_LINE' macro redefined
<|endoftext|>
|
<commit_before>class Solution {
public:
/**
* @param s: a string
* @return: an integer
*/
std::map<char, int> mapCtoSub;
int lengthOfLongestSubstring(string s) {
// write your code here
int i,j,k;
}
};<commit_msg>solving 384<commit_after>class Solution {
public:
/**
* @param s: a string
* @return: an integer
*/
std::map<char, int> mapCtoSub;
int lengthOfLongestSubstring(string s) {
// write your code here
int i,j,k,l_s=s.size();
int max_len=0;
for (char c='a';c<='z';c++)
mapCtoSub[c]=-1;
for (i=0,j=0;j++;j<=){
if (mapCtoSub[s[j]]>-1) i=max(i,mapCtoSub[s[j]]);
int tmp_len=j-i;
}
}
};<|endoftext|>
|
<commit_before>#include "keyconmode_select.h"
void Keyconmode_select::Change_to_keyconmode() {
if (*menue_var == this_menue_var && (CheckHitKey(KEY_INPUT_Z) || CheckHitKey(KEY_INPUT_RETURN) || CheckHitKey(KEY_INPUT_SPACE) || *p_push_joyshot_flag == true)) {
*p_system_var = 1;
}
}
void Keyconmode_select::Getinput_param() {
input_pad = GetJoypadInputState(DX_INPUT_PAD1);
}
void Keyconmode_select::Judgeinput_param() {
for (int i = 4; i < 32; i++) {
if ((input_pad & (1 << i)) != 0) {
str_directinput_pad[keycon_select_var] = input_pad;
str_input_pad[keycon_select_var] = i;
break;
}
}
}
void Keyconmode_select::Check_push_bottan() {
if (CheckHitKey(KEY_INPUT_UP) == 0 && CheckHitKey(KEY_INPUT_DOWN) == 0 && *p_push_joyup_flag == false && *p_push_joydown_flag == false) {
input_flag = false;
}
}
void Keyconmode_select::Keycon_select() {
if ((CheckHitKey(KEY_INPUT_DOWN) || *p_push_joydown_flag) && input_flag == false) {
keycon_select_var++;
input_flag = true;
}
if ((CheckHitKey(KEY_INPUT_UP) || *p_push_joyup_flag) && input_flag == false) {
keycon_select_var--;
input_flag = true;
}
if (keycon_select_var < 0) {
keycon_select_var = KEYCON_MODE_NUM;
}
else if (keycon_select_var > KEYCON_MODE_NUM) {
keycon_select_var = 0;
}
}
void Keyconmode_select::Keycon_mode() {
DrawRotaGraph2(0, 0, 0, 0, *p_define_srsize, 0, *keycon_backgr, true, false);
for (int i = 0; i < KEYCON_MODE_NUM + 1; i++) {
if (i < KEYCON_MODE_NUM) {
if (keycon_select_var == i) {
DrawRectGraph(KEYCON_MODE_DRAW_X, KEYCON_MODE_DRAW_Y + KEYCON_MDDE_MOVE_DIST * i, 100 * str_input_pad[i], 0, 100, 100, *keycon_numgr, true, false);
}
else {
SetDrawBlendMode(DX_BLENDMODE_ALPHA, 128);
DrawRectGraph(KEYCON_MODE_DRAW_X, KEYCON_MODE_DRAW_Y + KEYCON_MDDE_MOVE_DIST * i, 100 * str_input_pad[i], 0, 100, 100, *keycon_numgr, true, false);
SetDrawBlendMode(DX_BLENDMODE_NOBLEND, 0);
}
}
else {
if (keycon_select_var == i) {
DrawGraph(KEYCON_MODE_DRAW_X, KEYCON_MODE_DRAW_Y + KEYCON_MDDE_MOVE_DIST * i, *keycon_exitgr, true);
}
else {
SetDrawBlendMode(DX_BLENDMODE_ALPHA, 128);
DrawGraph(KEYCON_MODE_DRAW_X, KEYCON_MODE_DRAW_Y + KEYCON_MDDE_MOVE_DIST * i, *keycon_exitgr, true);
SetDrawBlendMode(DX_BLENDMODE_NOBLEND, 0);
}
}
}
}
void Keyconmode_select::Exit() {
if (keycon_select_var == KEYCON_MODE_NUM) {
}
}
void Keyconmode_select::Run() {
Getinput_param();
Judgeinput_param();
Keycon_select();
Keycon_mode();
Check_push_bottan();
}<commit_msg>keyconfigからtitleに移動できる<commit_after>#include "keyconmode_select.h"
void Keyconmode_select::Change_to_keyconmode() {
if (*menue_var == this_menue_var && (CheckHitKey(KEY_INPUT_Z) || CheckHitKey(KEY_INPUT_RETURN) || CheckHitKey(KEY_INPUT_SPACE) || *p_push_joyshot_flag == true)) {
*p_system_var = 1;
}
}
void Keyconmode_select::Getinput_param() {
input_pad = GetJoypadInputState(DX_INPUT_PAD1);
}
void Keyconmode_select::Judgeinput_param() {
for (int i = 4; i < 32; i++) {
if ((input_pad & (1 << i)) != 0) {
str_directinput_pad[keycon_select_var] = input_pad;
str_input_pad[keycon_select_var] = i;
break;
}
}
}
void Keyconmode_select::Check_push_bottan() {
if (CheckHitKey(KEY_INPUT_UP) == 0 && CheckHitKey(KEY_INPUT_DOWN) == 0 && *p_push_joyup_flag == false && *p_push_joydown_flag == false) {
input_flag = false;
}
}
void Keyconmode_select::Keycon_select() {
if ((CheckHitKey(KEY_INPUT_DOWN) || *p_push_joydown_flag) && input_flag == false) {
keycon_select_var++;
input_flag = true;
}
if ((CheckHitKey(KEY_INPUT_UP) || *p_push_joyup_flag) && input_flag == false) {
keycon_select_var--;
input_flag = true;
}
if (keycon_select_var < 0) {
keycon_select_var = KEYCON_MODE_NUM;
}
else if (keycon_select_var > KEYCON_MODE_NUM) {
keycon_select_var = 0;
}
}
void Keyconmode_select::Keycon_mode() {
DrawRotaGraph2(0, 0, 0, 0, *p_define_srsize, 0, *keycon_backgr, true, false);
for (int i = 0; i < KEYCON_MODE_NUM + 1; i++) {
if (i < KEYCON_MODE_NUM) {
if (keycon_select_var == i) {
DrawRectGraph(KEYCON_MODE_DRAW_X, KEYCON_MODE_DRAW_Y + KEYCON_MDDE_MOVE_DIST * i, 100 * str_input_pad[i], 0, 100, 100, *keycon_numgr, true, false);
}
else {
SetDrawBlendMode(DX_BLENDMODE_ALPHA, 128);
DrawRectGraph(KEYCON_MODE_DRAW_X, KEYCON_MODE_DRAW_Y + KEYCON_MDDE_MOVE_DIST * i, 100 * str_input_pad[i], 0, 100, 100, *keycon_numgr, true, false);
SetDrawBlendMode(DX_BLENDMODE_NOBLEND, 0);
}
}
else {
if (keycon_select_var == i) {
DrawGraph(KEYCON_MODE_DRAW_X, KEYCON_MODE_DRAW_Y + KEYCON_MDDE_MOVE_DIST * i, *keycon_exitgr, true);
}
else {
SetDrawBlendMode(DX_BLENDMODE_ALPHA, 128);
DrawGraph(KEYCON_MODE_DRAW_X, KEYCON_MODE_DRAW_Y + KEYCON_MDDE_MOVE_DIST * i, *keycon_exitgr, true);
SetDrawBlendMode(DX_BLENDMODE_NOBLEND, 0);
}
}
}
}
void Keyconmode_select::Exit() {
if (keycon_select_var == KEYCON_MODE_NUM && (CheckHitKey(KEY_INPUT_Z) || CheckHitKey(KEY_INPUT_RETURN) || CheckHitKey(KEY_INPUT_SPACE) || *p_push_joyshot_flag == true)) {
*p_system_var = 0;
}
}
void Keyconmode_select::Run() {
Getinput_param();
Judgeinput_param();
Keycon_select();
Exit();
Keycon_mode();
Check_push_bottan();
}<|endoftext|>
|
<commit_before>#include "FAP.h"
#include "Util.h"
namespace Neolib {
FastAPproximation::FastAPproximation() {
}
void FastAPproximation::addUnitPlayer1(FAPUnit fu) {
player1.push_back(fu);
}
void FastAPproximation::addUnitPlayer2(FAPUnit fu) {
player2.push_back(fu);
}
void FastAPproximation::simulate(int nFrames) {
while (nFrames--) {
if (!player1.size() || !player2.size())
break;
didSomething = false;
isimulate();
if (!didSomething)
break;
}
}
int FastAPproximation::getStatus() {
int score = 0;
for (auto & u : player1)
if (u.health && u.maxHealth)
score += (u.score * u.health) / u.maxHealth;
for (auto & u : player2)
if (u.health && u.maxHealth)
score -= (u.score * u.health) / u.maxHealth;
return score;
}
std::pair<std::vector<FastAPproximation::FAPUnit>*, std::vector<FastAPproximation::FAPUnit>*> FastAPproximation::getState() {
return { &player1, &player2 };
}
void FastAPproximation::clearState() {
player1.clear(), player2.clear();
}
void FastAPproximation::dealDamage(const FastAPproximation::FAPUnit &fu, int damage, BWAPI::DamageType damageType) const {
if (fu.shields >= damage - fu.shieldArmor) {
fu.shields -= damage - fu.shieldArmor;
return;
}
else if(fu.shields) {
damage -= (fu.shields + fu.shieldArmor);
fu.shields = 0;
}
if (!damage)
return;
switch (damageType) {
case BWAPI::DamageTypes::Concussive:
switch (fu.unitSize) {
case BWAPI::UnitSizeTypes::Large:
damage = damage / 2;
break;
case BWAPI::UnitSizeTypes::Medium:
damage = (damage * 3) / 4;
break;
}
break;
case BWAPI::DamageTypes::Explosive:
switch (fu.unitSize) {
case BWAPI::UnitSizeTypes::Small:
damage = damage / 2;
break;
case BWAPI::UnitSizeTypes::Medium:
damage = (damage * 3) / 4;
break;
}
break;
}
fu.health -= MAX(1, damage - fu.armor);
}
int FastAPproximation::dist(const FastAPproximation::FAPUnit &u1, const FastAPproximation::FAPUnit &u2) const {
return (int)sqrt((u1.x - u2.x)*(u1.x - u2.x) + (u1.y - u2.y)*(u1.y - u2.y));
}
void FastAPproximation::unitsim(const FastAPproximation::FAPUnit &fu, std::vector <FastAPproximation::FAPUnit> &enemyUnits) {
if (fu.attackCooldownRemaining) {
didSomething = true;
return;
}
auto closestEnemy = enemyUnits.end();
int closestDist;
for (auto enemyIt = enemyUnits.begin(); enemyIt != enemyUnits.end(); ++ enemyIt) {
if (enemyIt->flying) {
if (fu.airDamage) {
int d = dist(fu, *enemyIt);
if ((closestEnemy == enemyUnits.end() || d < closestDist) && d >= fu.airMinRange) {
closestDist = d;
closestEnemy = enemyIt;
}
}
}
else {
if (fu.groundDamage) {
int d = dist(fu, *enemyIt);
if ((closestEnemy == enemyUnits.end() || d < closestDist) && d >= fu.groundMinRange) {
closestDist = d;
closestEnemy = enemyIt;
}
}
}
}
if (closestEnemy != enemyUnits.end() && closestDist < fu.speed && !(fu.x == closestEnemy->x && fu.y == closestEnemy->y)) {
fu.x = closestEnemy->x;
fu.y = closestEnemy->y;
closestDist = 0;
didSomething = true;
}
if (closestEnemy != enemyUnits.end() && closestDist <= (closestEnemy->flying ? fu.groundMaxRange : fu.airMinRange)) {
if (closestEnemy->flying)
dealDamage(*closestEnemy, fu.airDamage, fu.airDamageType), fu.attackCooldownRemaining = fu.airCooldown;
else
dealDamage(*closestEnemy, fu.groundDamage, fu.groundDamageType), fu.attackCooldownRemaining = fu.groundCooldown;
if (closestEnemy->health < 1) {
*closestEnemy = enemyUnits.back();
enemyUnits.pop_back();
}
didSomething = true;
return;
}
else if(closestEnemy != enemyUnits.end()) {
int dx = closestEnemy->x - fu.x, dy = closestEnemy->y - fu.y;
if (dx || dy) {
fu.x += (int)(((float)dx / sqrt(dx*dx + dy*dy)) * fu.speed);
fu.y += (int)(((float)dy / sqrt(dx*dx + dy*dy)) * fu.speed);
didSomething = true;
return;
}
}
}
void FastAPproximation::isimulate() {
for (auto &fu : player1)
unitsim(fu, player2);
for (auto &fu : player2)
unitsim(fu, player1);
for (auto &fu : player1)
if (fu.attackCooldownRemaining)
--fu.attackCooldownRemaining;
for (auto &fu : player2)
if (fu.attackCooldownRemaining)
--fu.attackCooldownRemaining;
}
FastAPproximation::FAPUnit::FAPUnit(BWAPI::Unit u): FAPUnit(EnemyData(u)) {
}
FastAPproximation::FAPUnit::FAPUnit(EnemyData ed) :
x(ed.lastPosition.x),
y(ed.lastPosition.y),
speed((int)ed.lastPlayer->topSpeed(ed.lastType)),
health(ed.expectedHealth()),
maxHealth(ed.lastType.maxHitPoints()),
shields(ed.expectedShields()),
shieldArmor(ed.lastPlayer->getUpgradeLevel(BWAPI::UpgradeTypes::Protoss_Plasma_Shields)),
maxShields(ed.lastType.maxShields()),
armor(ed.lastPlayer->armor(ed.lastType)),
flying(ed.lastType.isFlyer()),
groundDamage(ed.lastPlayer->damage(ed.lastType.groundWeapon())),
groundCooldown(ed.lastType.groundWeapon().damageFactor() && ed.lastType.maxGroundHits() ? ed.lastPlayer->weaponDamageCooldown(ed.lastType) / (ed.lastType.groundWeapon().damageFactor() * ed.lastType.maxGroundHits()) : 0),
//groundInnerRadius(ed.lastType.groundWeapon().innerSplashRadius()),
//groundOuterRadius(ed.lastType.groundWeapon().outerSplashRadius()),
groundMaxRange(ed.lastPlayer->weaponMaxRange(ed.lastType.groundWeapon())),
groundMinRange(ed.lastType.groundWeapon().minRange()),
groundDamageType(ed.lastType.groundWeapon().damageType()),
airDamage(ed.lastPlayer->damage(ed.lastType.airWeapon())),
airCooldown(ed.lastType.airWeapon().damageFactor() && ed.lastType.maxAirHits() ? ed.lastType.airWeapon().damageCooldown() / (ed.lastType.airWeapon().damageFactor() * ed.lastType.maxAirHits()) : 0),
//airInnerRadius(ed.lastType.airWeapon().innerSplashRadius()),
//airOuterRadius(ed.lastType.airWeapon().outerSplashRadius()),
airMaxRange(ed.lastPlayer->weaponMaxRange(ed.lastType.airWeapon())),
airMinRange(ed.lastType.airWeapon().minRange()),
airDamageType(ed.lastType.airWeapon().damageType()),
score(ed.lastType.destroyScore()) {
static int nextId = 0;
id = nextId++;
switch (ed.lastType) {
case BWAPI::UnitTypes::Protoss_Carrier:
groundDamage = ed.lastPlayer->damage(BWAPI::UnitTypes::Protoss_Interceptor.groundWeapon());
groundCooldown = BWAPI::UnitTypes::Protoss_Interceptor.groundWeapon().damageCooldown() / 8;
groundMaxRange = 32 * 8;
airDamage = groundDamage;
airCooldown = groundCooldown;
airMaxRange = groundMaxRange;
break;
case BWAPI::UnitTypes::Terran_Bunker:
groundDamage = ed.lastPlayer->damage(BWAPI::WeaponTypes::Gauss_Rifle);
groundCooldown = BWAPI::UnitTypes::Terran_Marine.groundWeapon().damageCooldown() / 4;
groundMaxRange = ed.lastPlayer->weaponMaxRange(BWAPI::UnitTypes::Terran_Marine.groundWeapon()) + 32;
airDamage = groundDamage;
airCooldown = groundCooldown;
airMaxRange = groundMaxRange;
break;
case BWAPI::UnitTypes::Protoss_Reaver:
groundDamage = ed.lastPlayer->damage(BWAPI::WeaponTypes::Scarab);
break;
default:
break;
}
groundDamage *= 2;
airDamage *= 2;
shieldArmor *= 2;
armor *= 2;
health *= 2;
shields *= 2;
}
FastAPproximation::FAPUnit &FastAPproximation::FAPUnit::operator=(const FAPUnit & other) {
x = other.x, y = other.y;
health = other.health, maxHealth = other.maxHealth;
shields = other.shields, maxShields = other.maxShields;
speed = other.speed, armor = other.armor, flying = other.flying, unitSize = other.unitSize;
groundDamage = other.groundDamage, groundCooldown = other.groundCooldown, groundMaxRange = other.groundMaxRange, groundMinRange = other.groundMinRange, groundDamageType = other.groundDamageType;
airDamage = other.airDamage, airCooldown = other.airCooldown, airMaxRange = other.airMaxRange, airMinRange = other.airMinRange, airDamageType = other.airDamageType;
score = other.score;
attackCooldownRemaining = other.attackCooldownRemaining;
return *this;
}
bool FastAPproximation::FAPUnit::operator<(const FAPUnit & other) const {
return id < other.id;
}
}
<commit_msg>Fix for infinite loop<commit_after>#include "FAP.h"
#include "Util.h"
namespace Neolib {
FastAPproximation::FastAPproximation() {
}
void FastAPproximation::addUnitPlayer1(FAPUnit fu) {
player1.push_back(fu);
}
void FastAPproximation::addUnitPlayer2(FAPUnit fu) {
player2.push_back(fu);
}
void FastAPproximation::simulate(int nFrames) {
while (nFrames--) {
if (!player1.size() || !player2.size())
break;
didSomething = false;
isimulate();
if (!didSomething)
break;
}
}
int FastAPproximation::getStatus() {
int score = 0;
for (auto & u : player1)
if (u.health && u.maxHealth)
score += (u.score * u.health) / u.maxHealth;
for (auto & u : player2)
if (u.health && u.maxHealth)
score -= (u.score * u.health) / u.maxHealth;
return score;
}
std::pair<std::vector<FastAPproximation::FAPUnit>*, std::vector<FastAPproximation::FAPUnit>*> FastAPproximation::getState() {
return { &player1, &player2 };
}
void FastAPproximation::clearState() {
player1.clear(), player2.clear();
}
void FastAPproximation::dealDamage(const FastAPproximation::FAPUnit &fu, int damage, BWAPI::DamageType damageType) const {
if (fu.shields >= damage - fu.shieldArmor) {
fu.shields -= damage - fu.shieldArmor;
return;
}
else if(fu.shields) {
damage -= (fu.shields + fu.shieldArmor);
fu.shields = 0;
}
if (!damage)
return;
switch (damageType) {
case BWAPI::DamageTypes::Concussive:
switch (fu.unitSize) {
case BWAPI::UnitSizeTypes::Large:
damage = damage / 2;
break;
case BWAPI::UnitSizeTypes::Medium:
damage = (damage * 3) / 4;
break;
}
break;
case BWAPI::DamageTypes::Explosive:
switch (fu.unitSize) {
case BWAPI::UnitSizeTypes::Small:
damage = damage / 2;
break;
case BWAPI::UnitSizeTypes::Medium:
damage = (damage * 3) / 4;
break;
}
break;
}
fu.health -= MAX(1, damage - fu.armor);
}
int FastAPproximation::dist(const FastAPproximation::FAPUnit &u1, const FastAPproximation::FAPUnit &u2) const {
return (int)sqrt((u1.x - u2.x)*(u1.x - u2.x) + (u1.y - u2.y)*(u1.y - u2.y));
}
void FastAPproximation::unitsim(const FastAPproximation::FAPUnit &fu, std::vector <FastAPproximation::FAPUnit> &enemyUnits) {
if (fu.attackCooldownRemaining) {
didSomething = true;
return;
}
auto closestEnemy = enemyUnits.end();
int closestDist;
for (auto enemyIt = enemyUnits.begin(); enemyIt != enemyUnits.end(); ++ enemyIt) {
if (enemyIt->flying) {
if (fu.airDamage) {
int d = dist(fu, *enemyIt);
if ((closestEnemy == enemyUnits.end() || d < closestDist) && d >= fu.airMinRange) {
closestDist = d;
closestEnemy = enemyIt;
}
}
}
else {
if (fu.groundDamage) {
int d = dist(fu, *enemyIt);
if ((closestEnemy == enemyUnits.end() || d < closestDist) && d >= fu.groundMinRange) {
closestDist = d;
closestEnemy = enemyIt;
}
}
}
}
if (closestEnemy != enemyUnits.end() && closestDist <= fu.speed && !(fu.x == closestEnemy->x && fu.y == closestEnemy->y)) {
fu.x = closestEnemy->x;
fu.y = closestEnemy->y;
closestDist = 0;
didSomething = true;
}
if (closestEnemy != enemyUnits.end() && closestDist <= (closestEnemy->flying ? fu.groundMaxRange : fu.airMinRange)) {
if (closestEnemy->flying)
dealDamage(*closestEnemy, fu.airDamage, fu.airDamageType), fu.attackCooldownRemaining = fu.airCooldown;
else
dealDamage(*closestEnemy, fu.groundDamage, fu.groundDamageType), fu.attackCooldownRemaining = fu.groundCooldown;
if (closestEnemy->health < 1) {
*closestEnemy = enemyUnits.back();
enemyUnits.pop_back();
}
didSomething = true;
return;
}
else if(closestEnemy != enemyUnits.end() && closestDist > fu.speed) {
int dx = closestEnemy->x - fu.x, dy = closestEnemy->y - fu.y;
if (dx || dy) {
fu.x += (int)(((float)dx / sqrt(dx*dx + dy*dy)) * fu.speed);
fu.y += (int)(((float)dy / sqrt(dx*dx + dy*dy)) * fu.speed);
didSomething = true;
return;
}
}
}
void FastAPproximation::isimulate() {
for (auto &fu : player1)
unitsim(fu, player2);
for (auto &fu : player2)
unitsim(fu, player1);
for (auto &fu : player1)
if (fu.attackCooldownRemaining)
--fu.attackCooldownRemaining;
for (auto &fu : player2)
if (fu.attackCooldownRemaining)
--fu.attackCooldownRemaining;
}
FastAPproximation::FAPUnit::FAPUnit(BWAPI::Unit u): FAPUnit(EnemyData(u)) {
}
FastAPproximation::FAPUnit::FAPUnit(EnemyData ed) :
x(ed.lastPosition.x),
y(ed.lastPosition.y),
speed((int)ed.lastPlayer->topSpeed(ed.lastType)),
health(ed.expectedHealth()),
maxHealth(ed.lastType.maxHitPoints()),
shields(ed.expectedShields()),
shieldArmor(ed.lastPlayer->getUpgradeLevel(BWAPI::UpgradeTypes::Protoss_Plasma_Shields)),
maxShields(ed.lastType.maxShields()),
armor(ed.lastPlayer->armor(ed.lastType)),
flying(ed.lastType.isFlyer()),
groundDamage(ed.lastPlayer->damage(ed.lastType.groundWeapon())),
groundCooldown(ed.lastType.groundWeapon().damageFactor() && ed.lastType.maxGroundHits() ? ed.lastPlayer->weaponDamageCooldown(ed.lastType) / (ed.lastType.groundWeapon().damageFactor() * ed.lastType.maxGroundHits()) : 0),
//groundInnerRadius(ed.lastType.groundWeapon().innerSplashRadius()),
//groundOuterRadius(ed.lastType.groundWeapon().outerSplashRadius()),
groundMaxRange(ed.lastPlayer->weaponMaxRange(ed.lastType.groundWeapon())),
groundMinRange(ed.lastType.groundWeapon().minRange()),
groundDamageType(ed.lastType.groundWeapon().damageType()),
airDamage(ed.lastPlayer->damage(ed.lastType.airWeapon())),
airCooldown(ed.lastType.airWeapon().damageFactor() && ed.lastType.maxAirHits() ? ed.lastType.airWeapon().damageCooldown() / (ed.lastType.airWeapon().damageFactor() * ed.lastType.maxAirHits()) : 0),
//airInnerRadius(ed.lastType.airWeapon().innerSplashRadius()),
//airOuterRadius(ed.lastType.airWeapon().outerSplashRadius()),
airMaxRange(ed.lastPlayer->weaponMaxRange(ed.lastType.airWeapon())),
airMinRange(ed.lastType.airWeapon().minRange()),
airDamageType(ed.lastType.airWeapon().damageType()),
score(ed.lastType.destroyScore()) {
static int nextId = 0;
id = nextId++;
switch (ed.lastType) {
case BWAPI::UnitTypes::Protoss_Carrier:
groundDamage = ed.lastPlayer->damage(BWAPI::UnitTypes::Protoss_Interceptor.groundWeapon());
groundCooldown = BWAPI::UnitTypes::Protoss_Interceptor.groundWeapon().damageCooldown() / 8;
groundMaxRange = 32 * 8;
airDamage = groundDamage;
airCooldown = groundCooldown;
airMaxRange = groundMaxRange;
break;
case BWAPI::UnitTypes::Terran_Bunker:
groundDamage = ed.lastPlayer->damage(BWAPI::WeaponTypes::Gauss_Rifle);
groundCooldown = BWAPI::UnitTypes::Terran_Marine.groundWeapon().damageCooldown() / 4;
groundMaxRange = ed.lastPlayer->weaponMaxRange(BWAPI::UnitTypes::Terran_Marine.groundWeapon()) + 32;
airDamage = groundDamage;
airCooldown = groundCooldown;
airMaxRange = groundMaxRange;
break;
case BWAPI::UnitTypes::Protoss_Reaver:
groundDamage = ed.lastPlayer->damage(BWAPI::WeaponTypes::Scarab);
break;
default:
break;
}
groundDamage *= 2;
airDamage *= 2;
shieldArmor *= 2;
armor *= 2;
health *= 2;
shields *= 2;
}
FastAPproximation::FAPUnit &FastAPproximation::FAPUnit::operator=(const FAPUnit & other) {
x = other.x, y = other.y;
health = other.health, maxHealth = other.maxHealth;
shields = other.shields, maxShields = other.maxShields;
speed = other.speed, armor = other.armor, flying = other.flying, unitSize = other.unitSize;
groundDamage = other.groundDamage, groundCooldown = other.groundCooldown, groundMaxRange = other.groundMaxRange, groundMinRange = other.groundMinRange, groundDamageType = other.groundDamageType;
airDamage = other.airDamage, airCooldown = other.airCooldown, airMaxRange = other.airMaxRange, airMinRange = other.airMinRange, airDamageType = other.airDamageType;
score = other.score;
attackCooldownRemaining = other.attackCooldownRemaining;
return *this;
}
bool FastAPproximation::FAPUnit::operator<(const FAPUnit & other) const {
return id < other.id;
}
}
<|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. *
**************************************************************************/
/* $Id: */
//____________________________________________________________________
//
// START - T0.
//
// This class is a singleton that handles various parameters of
// the START detectors.
// Eventually, this class will use the Conditions DB to get the
// various parameters, which code can then request from here.
//
#include "AliLog.h"
#include "AliSTARTParameters.h"
#include "AliSTARTCalibData.h"
#include "AliSTARTAlignData.h"
#include <AliCDBManager.h>
#include <AliCDBEntry.h>
#include <AliCDBStorage.h>
#include <Riostream.h>
AliSTARTAlignData* AliSTARTParameters::fgAlignData = 0;
AliSTARTCalibData* AliSTARTParameters::fgCalibData = 0;
//====================================================================
ClassImp(AliSTARTParameters)
#if 0
; // This is here to keep Emacs for indenting the next line
#endif
//____________________________________________________________________
AliSTARTParameters* AliSTARTParameters::fgInstance = 0;
//____________________________________________________________________
AliSTARTParameters*
AliSTARTParameters::Instance()
{
// Get static instance
if (!fgInstance) fgInstance = new AliSTARTParameters;
return fgInstance;
}
//____________________________________________________________________
AliSTARTParameters::AliSTARTParameters()
: fIsInit(kFALSE)
{
// Default constructor
for (Int_t ipmt=0; ipmt<24; ipmt++)
{
SetTimeDelayCablesCFD(ipmt);
SetTimeDelayCablesLED(ipmt);
SetTimeDelayElectronicCFD(ipmt);
SetTimeDelayElectronicLED(ipmt);
SetTimeDelayPMT(ipmt);
SetVariableDelayLine(ipmt);
SetSlewingLED(ipmt);
SetPh2Mip();
SetChannelWidth();
SetmV2channel();
SetGain();
SetQTmin();
SetQTmax();
SetPMTeff(ipmt);
}
SetZposition();
}
//__________________________________________________________________
void
AliSTARTParameters::Init()
{
// Initialize the parameters manager. We need to get stuff from the
// CDB here.
// if (fIsInit) return;
AliCDBManager* cdb = AliCDBManager::Instance();
cout<<" AliSTARTParameters::Init() CDB "<<cdb<<endl;
AliCDBStorage *stor = cdb->GetStorage("local://DBLocal");
fCalibentry = stor->Get("START/Calib/Gain_TimeDelay_Slewing_Walk",1);
if (fCalibentry){
fgCalibData = (AliSTARTCalibData*)fCalibentry->GetObject();
cout<<" got calibdata "<<endl;
}
fAlignentry = stor-> Get("START/Align/Positions",1);
if (fAlignentry){
fgAlignData = (AliSTARTAlignData*) fAlignentry->GetObject();
cout<<" got align data "<<endl;
}
cout<<" in INT :: calib "<<fCalibentry<<" align "<<fAlignentry<<endl;
fIsInit = kTRUE;
}
//__________________________________________________________________
Float_t
AliSTARTParameters::GetGain(Int_t ipmt) const
{
// Returns the calibrated gain for each PMT
//
if (!fCalibentry)
return fFixedGain;
return fgCalibData->GetGain(ipmt);
}
//__________________________________________________________________
Float_t
AliSTARTParameters::GetTimeDelayLED(Int_t ipmt)
{
// return time delay for LED channel
//
if (!fCalibentry) {
fTimeDelayLED = fTimeDelayCablesLED[ipmt] + fTimeDelayElectronicLED[ipmt] + fTimeDelayPMT[ipmt];
return fTimeDelayLED;
}
return fgCalibData ->GetTimeDelayLED(ipmt);
}
//__________________________________________________________________
Float_t
AliSTARTParameters::GetTimeDelayCFD(Int_t ipmt)
{
// return time delay for CFD channel
//
if (!fCalibentry)
{
fTimeDelayCFD = fTimeDelayCablesCFD[ipmt] + fTimeDelayElectronicCFD[ipmt] + fTimeDelayPMT[ipmt] + fVariableDelayLine[ipmt];
return fTimeDelayCFD;
}
return fgCalibData->GetTimeDelayCFD(ipmt);
}
//__________________________________________________________________
void
AliSTARTParameters::SetSlewingLED(Int_t ipmt)
{
// Set Slweing Correction for LED channel
Float_t mv[23] = {25, 30,40,60, 80,100,150,200,250,300,400,500,600,800,1000,1500, 2000, 3000, 4000, 5500, 6000, 7000,8000};
Float_t y[23] = {5044, 4719, 3835, 3224, 2847, 2691,2327, 1937, 1781, 1560, 1456 ,1339, 1163.5, 1027, 819, 650, 520, 370.5, 234, 156, 78, 0};
TGraph* gr = new TGraph(23,mv,y);
fSlewingLED.AddAtAndExpand(gr,ipmt);
}
//__________________________________________________________________
void
AliSTARTParameters::SetPMTeff(Int_t ipmt)
{
Float_t lambda[50];
Float_t eff[50 ] = {0, 0, 0.23619, 0.202909, 0.177913,
0.175667, 0.17856, 0.190769, 0.206667, 0.230286,
0.252276, 0.256267,0.26, 0.27125, 0.281818,
0.288118, 0.294057,0.296222, 0.301622, 0.290421,
0.276615, 0.2666, 0.248, 0.23619, 0.227814,
0.219818, 0.206667,0.194087, 0.184681, 0.167917,
0.154367, 0.1364, 0.109412, 0.0834615,0.0725283,
0.0642963,0.05861, 0.0465, 0.0413333,0.032069,
0.0252203,0.02066, 0.016262, 0.012, 0.00590476,
0.003875, 0.00190, 0, 0, 0 } ;
for (Int_t i=0; i<50; i++) lambda[i]=200+10*i;
TGraph* gr = new TGraph(50,lambda,eff);
fPMTeff.AddAtAndExpand(gr,ipmt);
}
<commit_msg>Setting default CDB storage<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. *
**************************************************************************/
/* $Id: */
//____________________________________________________________________
//
// START - T0.
//
// This class is a singleton that handles various parameters of
// the START detectors.
// Eventually, this class will use the Conditions DB to get the
// various parameters, which code can then request from here.
//
#include "AliLog.h"
#include "AliSTARTParameters.h"
#include "AliSTARTCalibData.h"
#include "AliSTARTAlignData.h"
#include <AliCDBManager.h>
#include <AliCDBEntry.h>
#include <AliCDBStorage.h>
#include <Riostream.h>
AliSTARTAlignData* AliSTARTParameters::fgAlignData = 0;
AliSTARTCalibData* AliSTARTParameters::fgCalibData = 0;
//====================================================================
ClassImp(AliSTARTParameters)
#if 0
; // This is here to keep Emacs for indenting the next line
#endif
//____________________________________________________________________
AliSTARTParameters* AliSTARTParameters::fgInstance = 0;
//____________________________________________________________________
AliSTARTParameters*
AliSTARTParameters::Instance()
{
// Get static instance
if (!fgInstance) fgInstance = new AliSTARTParameters;
return fgInstance;
}
//____________________________________________________________________
AliSTARTParameters::AliSTARTParameters()
: fIsInit(kFALSE)
{
// Default constructor
for (Int_t ipmt=0; ipmt<24; ipmt++)
{
SetTimeDelayCablesCFD(ipmt);
SetTimeDelayCablesLED(ipmt);
SetTimeDelayElectronicCFD(ipmt);
SetTimeDelayElectronicLED(ipmt);
SetTimeDelayPMT(ipmt);
SetVariableDelayLine(ipmt);
SetSlewingLED(ipmt);
SetPh2Mip();
SetChannelWidth();
SetmV2channel();
SetGain();
SetQTmin();
SetQTmax();
SetPMTeff(ipmt);
}
SetZposition();
}
//__________________________________________________________________
void
AliSTARTParameters::Init()
{
// Initialize the parameters manager. We need to get stuff from the
// CDB here.
// if (fIsInit) return;
AliCDBManager* cdb = AliCDBManager::Instance();
cout<<" AliSTARTParameters::Init() CDB "<<cdb<<endl;
AliCDBStorage *stor = cdb->GetStorage("local://$ALICE_ROOT");
fCalibentry = stor->Get("START/Calib/Gain_TimeDelay_Slewing_Walk",1);
if (fCalibentry){
fgCalibData = (AliSTARTCalibData*)fCalibentry->GetObject();
cout<<" got calibdata "<<endl;
}
fAlignentry = stor-> Get("START/Align/Positions",1);
if (fAlignentry){
fgAlignData = (AliSTARTAlignData*) fAlignentry->GetObject();
cout<<" got align data "<<endl;
}
cout<<" in INT :: calib "<<fCalibentry<<" align "<<fAlignentry<<endl;
fIsInit = kTRUE;
}
//__________________________________________________________________
Float_t
AliSTARTParameters::GetGain(Int_t ipmt) const
{
// Returns the calibrated gain for each PMT
//
if (!fCalibentry)
return fFixedGain;
return fgCalibData->GetGain(ipmt);
}
//__________________________________________________________________
Float_t
AliSTARTParameters::GetTimeDelayLED(Int_t ipmt)
{
// return time delay for LED channel
//
if (!fCalibentry) {
fTimeDelayLED = fTimeDelayCablesLED[ipmt] + fTimeDelayElectronicLED[ipmt] + fTimeDelayPMT[ipmt];
return fTimeDelayLED;
}
return fgCalibData ->GetTimeDelayLED(ipmt);
}
//__________________________________________________________________
Float_t
AliSTARTParameters::GetTimeDelayCFD(Int_t ipmt)
{
// return time delay for CFD channel
//
if (!fCalibentry)
{
fTimeDelayCFD = fTimeDelayCablesCFD[ipmt] + fTimeDelayElectronicCFD[ipmt] + fTimeDelayPMT[ipmt] + fVariableDelayLine[ipmt];
return fTimeDelayCFD;
}
return fgCalibData->GetTimeDelayCFD(ipmt);
}
//__________________________________________________________________
void
AliSTARTParameters::SetSlewingLED(Int_t ipmt)
{
// Set Slweing Correction for LED channel
Float_t mv[23] = {25, 30,40,60, 80,100,150,200,250,300,400,500,600,800,1000,1500, 2000, 3000, 4000, 5500, 6000, 7000,8000};
Float_t y[23] = {5044, 4719, 3835, 3224, 2847, 2691,2327, 1937, 1781, 1560, 1456 ,1339, 1163.5, 1027, 819, 650, 520, 370.5, 234, 156, 78, 0};
TGraph* gr = new TGraph(23,mv,y);
fSlewingLED.AddAtAndExpand(gr,ipmt);
}
//__________________________________________________________________
void
AliSTARTParameters::SetPMTeff(Int_t ipmt)
{
Float_t lambda[50];
Float_t eff[50 ] = {0, 0, 0.23619, 0.202909, 0.177913,
0.175667, 0.17856, 0.190769, 0.206667, 0.230286,
0.252276, 0.256267,0.26, 0.27125, 0.281818,
0.288118, 0.294057,0.296222, 0.301622, 0.290421,
0.276615, 0.2666, 0.248, 0.23619, 0.227814,
0.219818, 0.206667,0.194087, 0.184681, 0.167917,
0.154367, 0.1364, 0.109412, 0.0834615,0.0725283,
0.0642963,0.05861, 0.0465, 0.0413333,0.032069,
0.0252203,0.02066, 0.016262, 0.012, 0.00590476,
0.003875, 0.00190, 0, 0, 0 } ;
for (Int_t i=0; i<50; i++) lambda[i]=200+10*i;
TGraph* gr = new TGraph(50,lambda,eff);
fPMTeff.AddAtAndExpand(gr,ipmt);
}
<|endoftext|>
|
<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include <assert.h>
#include <stdio.h>
#include <string.h>
#include <windows.h>
#include <msctf.h>
#include "hooks.h"
#include "msctfhooks.h"
void MSCTFHooks_PostInsertTextAtSelection(ITfInsertAtSelection *This, TfEditCookie ec, DWORD dwFlags, const WCHAR *pchText, LONG cchText, ITfRange **ppRange)
{
ThreadIn ti;
if (!HooksActive())
return;
LastErrorSave les;
HookSuspension hs;
HWND hwndMaster = FindWindowEx(HWND_MESSAGE, nullptr, TEXT("DictationBridgeMaster"), nullptr);
if (hwndMaster == nullptr)
{
return;
}
ITfRange* range = nullptr;
if (ppRange != nullptr)
{
range = *ppRange;
}
if (range != nullptr)
{
MSCTFHooks_HookRange(range);
ITfContext* ctx = nullptr;
range->GetContext(&ctx);
if (ctx != nullptr)
{
ITfContextView* view = nullptr;
ctx->GetActiveView(&view);
if (view != nullptr)
{
HWND hwnd = nullptr;
view->GetWnd(&hwnd);
ITfRangeACP* rangeACP = nullptr;
range->QueryInterface(IID_ITfRangeACP, (void**) &rangeACP);
if (rangeACP != nullptr)
{
LONG acpAnchor = -1, cchRange = -1;
if (rangeACP->GetExtent(&acpAnchor, &cchRange) == S_OK)
{
DWORD cbData = (sizeof(DWORD) * 3) + (cchText * sizeof(WCHAR));
BYTE* data = new BYTE[cbData];
DWORD tmp = (DWORD)((__int64)hwnd & 0xffffffff);
memcpy(data, &tmp, sizeof(tmp));
tmp = (DWORD)acpAnchor;
memcpy(data + sizeof(DWORD), &tmp, sizeof(tmp));
tmp = (DWORD)cchRange;
memcpy(data + sizeof(DWORD) * 2, &tmp, sizeof(tmp));
memcpy(data + sizeof(DWORD) * 3, pchText, cchText * sizeof(WCHAR));
COPYDATASTRUCT cds;
cds.dwData = 0;
cds.lpData = (PVOID) data;
cds.cbData = cbData;
DWORD_PTR result;
SendMessageTimeout(hwndMaster, WM_COPYDATA, 0, (LPARAM) &cds, SMTO_BLOCK, 1000, &result);
delete[] data;
}
rangeACP->Release();
}
view->Release();
}
ctx->Release();
}
}
}
void MSCTFHooks_PreSetText(ITfRange *This, TfEditCookie ec, DWORD dwFlags, const WCHAR *pchText, LONG cch)
{
ThreadIn ti;
if (!HooksActive())
return;
LastErrorSave les;
HookSuspension hs;
HWND hwndMaster = FindWindowEx(HWND_MESSAGE, nullptr, TEXT("DictationBridgeMaster"), nullptr);
if (hwndMaster == nullptr)
{
return;
}
if (cch == 0)
{
WCHAR pchOrigText[512];
ULONG cchOrigText;
HRESULT hr = This->GetText(ec, 0, pchOrigText, ARRAYSIZE(pchOrigText), &cchOrigText);
if (hr == S_OK && cchOrigText > 0)
{
HWND hwnd = nullptr;
ITfContext* ctx = nullptr;
This->GetContext(&ctx);
if (ctx != nullptr)
{
ITfContextView* view = nullptr;
ctx->GetActiveView(&view);
if (view != nullptr)
{
view->GetWnd(&hwnd);
}
}
DWORD selStart = -1;
DWORD cbData = (sizeof(DWORD) * 3) + (cchOrigText * sizeof(WCHAR));
BYTE* data = new BYTE[cbData];
DWORD tmp = (DWORD)((__int64)hwnd & 0xffffffff);
memcpy(data, &tmp, sizeof(tmp));
tmp = (DWORD)selStart;
memcpy(data + sizeof(DWORD), &tmp, sizeof(tmp));
tmp = (DWORD)cchOrigText;
memcpy(data + sizeof(DWORD) * 2, &tmp, sizeof(tmp));
memcpy(data + sizeof(DWORD) * 3, pchOrigText, cchOrigText * sizeof(WCHAR));
COPYDATASTRUCT cds;
cds.dwData = 2;
cds.lpData = (PVOID) data;
cds.cbData = cbData;
DWORD_PTR result;
SendMessageTimeout(hwndMaster, WM_COPYDATA, 0, (LPARAM) &cds, SMTO_BLOCK, 1000, &result);
delete[] data;
}
}
}
<commit_msg>Eliminate extraneous 'new paragraph' messages<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include <assert.h>
#include <stdio.h>
#include <string.h>
#include <windows.h>
#include <msctf.h>
#include "hooks.h"
#include "msctfhooks.h"
void MSCTFHooks_PostInsertTextAtSelection(ITfInsertAtSelection *This, TfEditCookie ec, DWORD dwFlags, const WCHAR *pchText, LONG cchText, ITfRange **ppRange)
{
ThreadIn ti;
if (cchText <= 0)
return;
if (!HooksActive())
return;
LastErrorSave les;
HookSuspension hs;
HWND hwndMaster = FindWindowEx(HWND_MESSAGE, nullptr, TEXT("DictationBridgeMaster"), nullptr);
if (hwndMaster == nullptr)
{
return;
}
ITfRange* range = nullptr;
if (ppRange != nullptr)
{
range = *ppRange;
}
if (range != nullptr)
{
MSCTFHooks_HookRange(range);
ITfContext* ctx = nullptr;
range->GetContext(&ctx);
if (ctx != nullptr)
{
ITfContextView* view = nullptr;
ctx->GetActiveView(&view);
if (view != nullptr)
{
HWND hwnd = nullptr;
view->GetWnd(&hwnd);
ITfRangeACP* rangeACP = nullptr;
range->QueryInterface(IID_ITfRangeACP, (void**) &rangeACP);
if (rangeACP != nullptr)
{
LONG acpAnchor = -1, cchRange = -1;
if (rangeACP->GetExtent(&acpAnchor, &cchRange) == S_OK)
{
DWORD cbData = (sizeof(DWORD) * 3) + (cchText * sizeof(WCHAR));
BYTE* data = new BYTE[cbData];
DWORD tmp = (DWORD)((__int64)hwnd & 0xffffffff);
memcpy(data, &tmp, sizeof(tmp));
tmp = (DWORD)acpAnchor;
memcpy(data + sizeof(DWORD), &tmp, sizeof(tmp));
tmp = (DWORD)cchRange;
memcpy(data + sizeof(DWORD) * 2, &tmp, sizeof(tmp));
memcpy(data + sizeof(DWORD) * 3, pchText, cchText * sizeof(WCHAR));
COPYDATASTRUCT cds;
cds.dwData = 0;
cds.lpData = (PVOID) data;
cds.cbData = cbData;
DWORD_PTR result;
SendMessageTimeout(hwndMaster, WM_COPYDATA, 0, (LPARAM) &cds, SMTO_BLOCK, 1000, &result);
delete[] data;
}
rangeACP->Release();
}
view->Release();
}
ctx->Release();
}
}
}
void MSCTFHooks_PreSetText(ITfRange *This, TfEditCookie ec, DWORD dwFlags, const WCHAR *pchText, LONG cch)
{
ThreadIn ti;
if (!HooksActive())
return;
LastErrorSave les;
HookSuspension hs;
HWND hwndMaster = FindWindowEx(HWND_MESSAGE, nullptr, TEXT("DictationBridgeMaster"), nullptr);
if (hwndMaster == nullptr)
{
return;
}
if (cch == 0)
{
WCHAR pchOrigText[512];
ULONG cchOrigText;
HRESULT hr = This->GetText(ec, 0, pchOrigText, ARRAYSIZE(pchOrigText), &cchOrigText);
if (hr == S_OK && cchOrigText > 0)
{
HWND hwnd = nullptr;
ITfContext* ctx = nullptr;
This->GetContext(&ctx);
if (ctx != nullptr)
{
ITfContextView* view = nullptr;
ctx->GetActiveView(&view);
if (view != nullptr)
{
view->GetWnd(&hwnd);
}
}
DWORD selStart = -1;
DWORD cbData = (sizeof(DWORD) * 3) + (cchOrigText * sizeof(WCHAR));
BYTE* data = new BYTE[cbData];
DWORD tmp = (DWORD)((__int64)hwnd & 0xffffffff);
memcpy(data, &tmp, sizeof(tmp));
tmp = (DWORD)selStart;
memcpy(data + sizeof(DWORD), &tmp, sizeof(tmp));
tmp = (DWORD)cchOrigText;
memcpy(data + sizeof(DWORD) * 2, &tmp, sizeof(tmp));
memcpy(data + sizeof(DWORD) * 3, pchOrigText, cchOrigText * sizeof(WCHAR));
COPYDATASTRUCT cds;
cds.dwData = 2;
cds.lpData = (PVOID) data;
cds.cbData = cbData;
DWORD_PTR result;
SendMessageTimeout(hwndMaster, WM_COPYDATA, 0, (LPARAM) &cds, SMTO_BLOCK, 1000, &result);
delete[] data;
}
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2015, Matthew Malensek.
// Distributed under the BSD 2-Clause License (see LICENSE.txt for details)
#include "Updater.h"
#pragma comment(lib, "Urlmon.lib")
#pragma comment(lib, "Version.lib")
#pragma comment(lib, "wininet.lib")
#include <Windows.h>
#include <WinInet.h>
#include <sstream>
#include "../../3RVX/Settings.h"
#include "../../3RVX/StringUtils.h"
#include "../../3RVX/Logger.h"
#include "../Controls/StatusCallback.h"
#include "Version.h"
const std::wstring Updater::DOWNLOAD_URL
= L"https://3rvx.com/releases/";
/* Since this const depends on DOWNLOAD_URL, it needs to be defined after it. */
const std::wstring Updater::LATEST_URL
= Updater::DOWNLOAD_URL + L"latest_version";
bool Updater::NewerVersionAvailable() {
Version remote = RemoteVersion();
Version local = MainAppVersion();
CLOG(L"Remote version: %s\n Local version: %s",
remote.ToString().c_str(),
local.ToString().c_str());
if (remote.ToInt() == 0 || local.ToInt() == 0) {
/* One of the version checks failed, so say that there is no new
* version. No need to bother the user with (hopefully) temporary
* errors. */
return false;
}
if (remote.ToInt() > local.ToInt()) {
return true;
} else {
return false;
}
}
Version Updater::MainAppVersion() {
std::wstring mainExe = Settings::Instance()->MainApp();
BOOL result;
DWORD size = GetFileVersionInfoSize(mainExe.c_str(), NULL);
if (size == 0) {
CLOG(L"Could not determine version info size");
return { 0, 0, 0 };
}
unsigned char *block = new unsigned char[size];
result = GetFileVersionInfo(mainExe.c_str(), NULL, size, block);
if (result == 0) {
CLOG(L"Failed to retrieve file version info");
delete[] block;
return { 0, 0, 0 };
}
unsigned int dataSz;
VS_FIXEDFILEINFO *vers;
result = VerQueryValue(block, L"\\", (void **) &vers, &dataSz);
if (result == 0) {
CLOG(L"Could not query root block for version info");
delete[] block;
return { 0, 0, 0 };
}
if (vers->dwSignature != 0xFEEF04BD) {
CLOG(L"Invalid version signature");
delete[] block;
return { 0, 0, 0 };
}
unsigned long verms = vers->dwProductVersionMS;
int hi = (verms >> 16) & 0xFF;
int lo = verms & 0xFF;
unsigned long verls = vers->dwProductVersionLS;
int rev = (verls >> 16) & 0xFF;
delete[] block;
return Version(hi, lo, rev);
}
std::wstring Updater::DownloadVersion(Version version, DownloadStatus *ds) {
wchar_t path[MAX_PATH];
DWORD result = GetTempPath(MAX_PATH, path);
if (result == 0) {
CLOG(L"Could not get temp download path");
return L"";
}
std::wstring tempDir(path);
std::wstring fname = DownloadFileName(version);
std::wstring url = DOWNLOAD_URL + fname;
std::wstring localFile = tempDir + L"\\" + fname;
CLOG(L"Downloading %s to %s...", url.c_str(), localFile.c_str());
DeleteUrlCacheEntry(url.c_str());
HRESULT hr = URLDownloadToFile(
NULL,
url.c_str(),
localFile.c_str(),
0,
ds);
if (hr == S_OK) {
return localFile;
} else {
return L"";
}
}
std::wstring Updater::DownloadFileName(Version version) {
std::wstring ext;
if (Settings::Portable()) {
ext = L".zip";
} else {
ext = L".msi";
}
return std::wstring(L"3RVX-" + version.ToString() + ext);
}
Version Updater::RemoteVersion() {
HINTERNET internet = InternetOpen(
L"3RVX Updater",
INTERNET_OPEN_TYPE_PRECONFIG,
NULL,
NULL,
NULL);
CLOG(L"Opening URL: %s", LATEST_URL.c_str());
HINTERNET connection = InternetOpenUrl(
internet,
LATEST_URL.c_str(),
NULL,
0,
INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_PRAGMA_NOCACHE,
0);
if (connection == NULL) {
CLOG(L"Could not connect to URL!");
return { 0, 0, 0 };
}
std::string str("");
char buf[32];
DWORD read;
while (InternetReadFile(connection, buf, 16, &read) == TRUE && read != 0) {
str.append(buf);
}
/* Only consider the first line */
str.erase(str.find('\n'), str.size() - 1);
size_t dot = str.find('.');
size_t dot2 = str.find('.', dot + 1);
std::string major = str.substr(0, dot);
std::string minor = str.substr(dot + 1, dot2);
std::string rev = str.substr(dot2 + 1, str.size());
return Version(std::stoi(major), std::stoi(minor), std::stoi(rev));
}<commit_msg>More updates for StatusCallback rename<commit_after>// Copyright (c) 2015, Matthew Malensek.
// Distributed under the BSD 2-Clause License (see LICENSE.txt for details)
#include "Updater.h"
#pragma comment(lib, "Urlmon.lib")
#pragma comment(lib, "Version.lib")
#pragma comment(lib, "wininet.lib")
#include <Windows.h>
#include <WinInet.h>
#include <sstream>
#include "../../3RVX/Settings.h"
#include "../../3RVX/StringUtils.h"
#include "../../3RVX/Logger.h"
#include "../Controls/StatusCallback.h"
#include "Version.h"
const std::wstring Updater::DOWNLOAD_URL
= L"https://3rvx.com/releases/";
/* Since this const depends on DOWNLOAD_URL, it needs to be defined after it. */
const std::wstring Updater::LATEST_URL
= Updater::DOWNLOAD_URL + L"latest_version";
bool Updater::NewerVersionAvailable() {
Version remote = RemoteVersion();
Version local = MainAppVersion();
CLOG(L"Remote version: %s\n Local version: %s",
remote.ToString().c_str(),
local.ToString().c_str());
if (remote.ToInt() == 0 || local.ToInt() == 0) {
/* One of the version checks failed, so say that there is no new
* version. No need to bother the user with (hopefully) temporary
* errors. */
return false;
}
if (remote.ToInt() > local.ToInt()) {
return true;
} else {
return false;
}
}
Version Updater::MainAppVersion() {
std::wstring mainExe = Settings::Instance()->MainApp();
BOOL result;
DWORD size = GetFileVersionInfoSize(mainExe.c_str(), NULL);
if (size == 0) {
CLOG(L"Could not determine version info size");
return { 0, 0, 0 };
}
unsigned char *block = new unsigned char[size];
result = GetFileVersionInfo(mainExe.c_str(), NULL, size, block);
if (result == 0) {
CLOG(L"Failed to retrieve file version info");
delete[] block;
return { 0, 0, 0 };
}
unsigned int dataSz;
VS_FIXEDFILEINFO *vers;
result = VerQueryValue(block, L"\\", (void **) &vers, &dataSz);
if (result == 0) {
CLOG(L"Could not query root block for version info");
delete[] block;
return { 0, 0, 0 };
}
if (vers->dwSignature != 0xFEEF04BD) {
CLOG(L"Invalid version signature");
delete[] block;
return { 0, 0, 0 };
}
unsigned long verms = vers->dwProductVersionMS;
int hi = (verms >> 16) & 0xFF;
int lo = verms & 0xFF;
unsigned long verls = vers->dwProductVersionLS;
int rev = (verls >> 16) & 0xFF;
delete[] block;
return Version(hi, lo, rev);
}
std::wstring Updater::DownloadVersion(Version version, StatusCallback *cb) {
wchar_t path[MAX_PATH];
DWORD result = GetTempPath(MAX_PATH, path);
if (result == 0) {
CLOG(L"Could not get temp download path");
return L"";
}
std::wstring tempDir(path);
std::wstring fname = DownloadFileName(version);
std::wstring url = DOWNLOAD_URL + fname;
std::wstring localFile = tempDir + L"\\" + fname;
CLOG(L"Downloading %s to %s...", url.c_str(), localFile.c_str());
DeleteUrlCacheEntry(url.c_str());
HRESULT hr = URLDownloadToFile(
NULL,
url.c_str(),
localFile.c_str(),
0,
cb);
if (hr == S_OK) {
return localFile;
} else {
return L"";
}
}
std::wstring Updater::DownloadFileName(Version version) {
std::wstring ext;
if (Settings::Portable()) {
ext = L".zip";
} else {
ext = L".msi";
}
return std::wstring(L"3RVX-" + version.ToString() + ext);
}
Version Updater::RemoteVersion() {
HINTERNET internet = InternetOpen(
L"3RVX Updater",
INTERNET_OPEN_TYPE_PRECONFIG,
NULL,
NULL,
NULL);
CLOG(L"Opening URL: %s", LATEST_URL.c_str());
HINTERNET connection = InternetOpenUrl(
internet,
LATEST_URL.c_str(),
NULL,
0,
INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_PRAGMA_NOCACHE,
0);
if (connection == NULL) {
CLOG(L"Could not connect to URL!");
return { 0, 0, 0 };
}
std::string str("");
char buf[32];
DWORD read;
while (InternetReadFile(connection, buf, 16, &read) == TRUE && read != 0) {
str.append(buf);
}
/* Only consider the first line */
str.erase(str.find('\n'), str.size() - 1);
size_t dot = str.find('.');
size_t dot2 = str.find('.', dot + 1);
std::string major = str.substr(0, dot);
std::string minor = str.substr(dot + 1, dot2);
std::string rev = str.substr(dot2 + 1, str.size());
return Version(std::stoi(major), std::stoi(minor), std::stoi(rev));
}<|endoftext|>
|
<commit_before><commit_msg>INTEGRATION: CWS ooo19126 (1.3.452); FILE MERGED 2005/09/05 15:00:31 rt 1.3.452.1: #i54170# Change license header: remove SISSL<commit_after><|endoftext|>
|
<commit_before>// Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "xwalk/runtime/browser/xwalk_browser_main_parts.h"
#include <string>
#include "base/bind.h"
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/files/file_path.h"
#include "base/strings/string_number_conversions.h"
#include "xwalk/application/browser/application_process_manager.h"
#include "xwalk/application/browser/application_system.h"
#include "xwalk/application/common/application.h"
#include "xwalk/application/common/application_file_util.h"
#include "xwalk/application/common/application_manifest_constants.h"
#include "xwalk/experimental/dialog/dialog_extension.h"
#include "xwalk/extensions/browser/xwalk_extension_service.h"
#include "xwalk/runtime/browser/devtools/remote_debugging_server.h"
#include "xwalk/runtime/browser/runtime.h"
#include "xwalk/runtime/browser/runtime_context.h"
#include "xwalk/runtime/browser/runtime_registry.h"
#include "xwalk/runtime/common/xwalk_switches.h"
#include "xwalk/runtime/extension/runtime_extension.h"
#include "cc/base/switches.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/main_function_params.h"
#include "content/public/common/url_constants.h"
#include "content/public/common/result_codes.h"
#include "grit/net_resources.h"
#include "net/base/net_util.h"
#include "net/base/net_module.h"
#include "ui/base/layout.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/ui_base_paths.h"
#if defined(OS_ANDROID)
#include "content/public/browser/android/compositor.h"
#include "net/android/network_change_notifier_factory_android.h"
#include "net/base/network_change_notifier.h"
#include "ui/base/l10n/l10n_util_android.h"
#endif // defined(OS_ANDROID)
namespace {
base::StringPiece PlatformResourceProvider(int key) {
if (key == IDR_DIR_HEADER_HTML) {
base::StringPiece html_data =
ui::ResourceBundle::GetSharedInstance().GetRawDataResource(
IDR_DIR_HEADER_HTML);
return html_data;
}
return base::StringPiece();
}
} // namespace
namespace xwalk {
XWalkBrowserMainParts::XWalkBrowserMainParts(
const content::MainFunctionParams& parameters)
: BrowserMainParts(),
startup_url_(content::kAboutBlankURL),
parameters_(parameters),
run_default_message_loop_(true) {
}
XWalkBrowserMainParts::~XWalkBrowserMainParts() {
}
#if defined(OS_ANDROID)
void XWalkBrowserMainParts::SetRuntimeContext(RuntimeContext* context) {
runtime_context_ = context;
}
#endif
void XWalkBrowserMainParts::PreMainMessageLoopStart() {
#if defined(OS_ANDROID)
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableWebRTC);
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kAllowFileAccessFromFiles);
// WebGL is disabled by default on Android, explicitly enable it in switches.
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableExperimentalWebGL);
#endif
#if !defined(OS_ANDROID)
CommandLine* command_line = CommandLine::ForCurrentProcess();
const CommandLine::StringVector& args = command_line->GetArgs();
if (args.empty())
return;
GURL url(args[0]);
if (url.is_valid() && url.has_scheme()) {
startup_url_ = url;
} else {
base::FilePath path(args[0]);
if (!path.IsAbsolute())
path = MakeAbsoluteFilePath(path);
startup_url_ = net::FilePathToFileURL(path);
}
#endif
#if defined(OS_MACOSX)
PreMainMessageLoopStartMac();
#endif
}
void XWalkBrowserMainParts::PostMainMessageLoopStart() {
#if defined(OS_ANDROID)
MessageLoopForUI::current()->Start();
#endif
}
void XWalkBrowserMainParts::PreEarlyInitialization() {
#if defined(OS_ANDROID)
net::NetworkChangeNotifier::SetFactory(
new net::NetworkChangeNotifierFactoryAndroid());
CommandLine::ForCurrentProcess()->AppendSwitch(
cc::switches::kCompositeToMailbox);
// Initialize the Compositor.
content::Compositor::Initialize();
#endif
#if defined(OS_LINUX)
// FIXME: Issue 496. We need to explicitly disable sandboxing on Linux while
// we do not support it (ie. ship the appropriate binary), otherwise we will
// crash on startup.
CommandLine::ForCurrentProcess()->AppendSwitch(switches::kNoSandbox);
#endif
}
int XWalkBrowserMainParts::PreCreateThreads() {
#if defined(OS_ANDROID)
DCHECK(runtime_context_);
runtime_context_->InitializeBeforeThreadCreation();
#endif
return content::RESULT_CODE_NORMAL_EXIT;
}
void XWalkBrowserMainParts::RegisterExternalExtensions() {
CommandLine* cmd_line = CommandLine::ForCurrentProcess();
if (!cmd_line->HasSwitch(switches::kXWalkExternalExtensionsPath))
return;
if (!cmd_line->HasSwitch(
switches::kXWalkAllowExternalExtensionsForRemoteSources) &&
!startup_url_.SchemeIsFile()) {
VLOG(0) << "Unsupported scheme for external extensions: " <<
startup_url_.scheme();
return;
}
base::FilePath extensions_dir =
cmd_line->GetSwitchValuePath(switches::kXWalkExternalExtensionsPath);
if (!file_util::DirectoryExists(extensions_dir)) {
LOG(WARNING) << "Ignoring non-existent extension directory: "
<< extensions_dir.AsUTF8Unsafe();
return;
}
extension_service_->RegisterExternalExtensionsForPath(extensions_dir);
}
void XWalkBrowserMainParts::PreMainMessageLoopRun() {
#if defined(OS_ANDROID)
net::NetModule::SetResourceProvider(PlatformResourceProvider);
if (parameters_.ui_task) {
parameters_.ui_task->Run();
delete parameters_.ui_task;
run_default_message_loop_ = false;
}
DCHECK(runtime_context_);
runtime_context_->PreMainMessageLoopRun();
#else
runtime_context_.reset(new RuntimeContext);
runtime_registry_.reset(new RuntimeRegistry);
extension_service_.reset(
new extensions::XWalkExtensionService(runtime_registry_.get()));
RegisterInternalExtensions();
RegisterExternalExtensions();
CommandLine* command_line = CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(switches::kRemoteDebuggingPort)) {
std::string port_str =
command_line->GetSwitchValueASCII(switches::kRemoteDebuggingPort);
int port;
const char* loopback_ip = "127.0.0.1";
if (base::StringToInt(port_str, &port) && port > 0 && port < 65535) {
remote_debugging_server_.reset(
new RemoteDebuggingServer(runtime_context_.get(),
loopback_ip, port, std::string()));
}
}
NativeAppWindow::Initialize();
if (startup_url_.SchemeIsFile()) {
base::FilePath path;
if (!net::FileURLToFilePath(startup_url_, &path))
return;
if (file_util::DirectoryExists(path)) {
std::string error;
scoped_refptr<xwalk::application::Application> application =
xwalk::application::LoadApplication(
path,
xwalk::application::Manifest::COMMAND_LINE,
&error);
if (!error.empty())
LOG(ERROR) << "Failed to load application: " << error;
if (application != NULL) {
xwalk::application::ApplicationSystem* system =
runtime_context_->GetApplicationSystem();
xwalk::application::ApplicationProcessManager* manager =
system->process_manager();
manager->LaunchApplication(runtime_context_.get(), application);
return;
}
}
}
// The new created Runtime instance will be managed by RuntimeRegistry.
Runtime::Create(runtime_context_.get(), startup_url_);
// If the |ui_task| is specified in main function parameter, it indicates
// that we will run this UI task instead of running the the default main
// message loop. See |content::BrowserTestBase::SetUp| for |ui_task| usage
// case.
if (parameters_.ui_task) {
parameters_.ui_task->Run();
delete parameters_.ui_task;
run_default_message_loop_ = false;
}
#endif
}
bool XWalkBrowserMainParts::MainMessageLoopRun(int* result_code) {
return !run_default_message_loop_;
}
void XWalkBrowserMainParts::PostMainMessageLoopRun() {
#if defined(OS_ANDROID)
MessageLoopForUI::current()->Start();
#else
runtime_context_.reset();
#endif
}
void XWalkBrowserMainParts::RegisterInternalExtensions() {
extension_service_->RegisterExtension(scoped_ptr<XWalkExtension>(
new RuntimeExtension()));
extension_service_->RegisterExtension(scoped_ptr<XWalkExtension>(
new experimental::DialogExtension(runtime_registry_.get())));
}
} // namespace xwalk
<commit_msg>[Android] WebRTC is now enabled by default on android.<commit_after>// Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "xwalk/runtime/browser/xwalk_browser_main_parts.h"
#include <string>
#include "base/bind.h"
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/files/file_path.h"
#include "base/strings/string_number_conversions.h"
#include "xwalk/application/browser/application_process_manager.h"
#include "xwalk/application/browser/application_system.h"
#include "xwalk/application/common/application.h"
#include "xwalk/application/common/application_file_util.h"
#include "xwalk/application/common/application_manifest_constants.h"
#include "xwalk/experimental/dialog/dialog_extension.h"
#include "xwalk/extensions/browser/xwalk_extension_service.h"
#include "xwalk/runtime/browser/devtools/remote_debugging_server.h"
#include "xwalk/runtime/browser/runtime.h"
#include "xwalk/runtime/browser/runtime_context.h"
#include "xwalk/runtime/browser/runtime_registry.h"
#include "xwalk/runtime/common/xwalk_switches.h"
#include "xwalk/runtime/extension/runtime_extension.h"
#include "cc/base/switches.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/main_function_params.h"
#include "content/public/common/url_constants.h"
#include "content/public/common/result_codes.h"
#include "grit/net_resources.h"
#include "net/base/net_util.h"
#include "net/base/net_module.h"
#include "ui/base/layout.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/ui_base_paths.h"
#if defined(OS_ANDROID)
#include "content/public/browser/android/compositor.h"
#include "net/android/network_change_notifier_factory_android.h"
#include "net/base/network_change_notifier.h"
#include "ui/base/l10n/l10n_util_android.h"
#endif // defined(OS_ANDROID)
namespace {
base::StringPiece PlatformResourceProvider(int key) {
if (key == IDR_DIR_HEADER_HTML) {
base::StringPiece html_data =
ui::ResourceBundle::GetSharedInstance().GetRawDataResource(
IDR_DIR_HEADER_HTML);
return html_data;
}
return base::StringPiece();
}
} // namespace
namespace xwalk {
XWalkBrowserMainParts::XWalkBrowserMainParts(
const content::MainFunctionParams& parameters)
: BrowserMainParts(),
startup_url_(content::kAboutBlankURL),
parameters_(parameters),
run_default_message_loop_(true) {
}
XWalkBrowserMainParts::~XWalkBrowserMainParts() {
}
#if defined(OS_ANDROID)
void XWalkBrowserMainParts::SetRuntimeContext(RuntimeContext* context) {
runtime_context_ = context;
}
#endif
void XWalkBrowserMainParts::PreMainMessageLoopStart() {
#if defined(OS_ANDROID)
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kAllowFileAccessFromFiles);
// WebGL is disabled by default on Android, explicitly enable it in switches.
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableExperimentalWebGL);
#endif
#if !defined(OS_ANDROID)
CommandLine* command_line = CommandLine::ForCurrentProcess();
const CommandLine::StringVector& args = command_line->GetArgs();
if (args.empty())
return;
GURL url(args[0]);
if (url.is_valid() && url.has_scheme()) {
startup_url_ = url;
} else {
base::FilePath path(args[0]);
if (!path.IsAbsolute())
path = MakeAbsoluteFilePath(path);
startup_url_ = net::FilePathToFileURL(path);
}
#endif
#if defined(OS_MACOSX)
PreMainMessageLoopStartMac();
#endif
}
void XWalkBrowserMainParts::PostMainMessageLoopStart() {
#if defined(OS_ANDROID)
MessageLoopForUI::current()->Start();
#endif
}
void XWalkBrowserMainParts::PreEarlyInitialization() {
#if defined(OS_ANDROID)
net::NetworkChangeNotifier::SetFactory(
new net::NetworkChangeNotifierFactoryAndroid());
CommandLine::ForCurrentProcess()->AppendSwitch(
cc::switches::kCompositeToMailbox);
// Initialize the Compositor.
content::Compositor::Initialize();
#endif
#if defined(OS_LINUX)
// FIXME: Issue 496. We need to explicitly disable sandboxing on Linux while
// we do not support it (ie. ship the appropriate binary), otherwise we will
// crash on startup.
CommandLine::ForCurrentProcess()->AppendSwitch(switches::kNoSandbox);
#endif
}
int XWalkBrowserMainParts::PreCreateThreads() {
#if defined(OS_ANDROID)
DCHECK(runtime_context_);
runtime_context_->InitializeBeforeThreadCreation();
#endif
return content::RESULT_CODE_NORMAL_EXIT;
}
void XWalkBrowserMainParts::RegisterExternalExtensions() {
CommandLine* cmd_line = CommandLine::ForCurrentProcess();
if (!cmd_line->HasSwitch(switches::kXWalkExternalExtensionsPath))
return;
if (!cmd_line->HasSwitch(
switches::kXWalkAllowExternalExtensionsForRemoteSources) &&
!startup_url_.SchemeIsFile()) {
VLOG(0) << "Unsupported scheme for external extensions: " <<
startup_url_.scheme();
return;
}
base::FilePath extensions_dir =
cmd_line->GetSwitchValuePath(switches::kXWalkExternalExtensionsPath);
if (!file_util::DirectoryExists(extensions_dir)) {
LOG(WARNING) << "Ignoring non-existent extension directory: "
<< extensions_dir.AsUTF8Unsafe();
return;
}
extension_service_->RegisterExternalExtensionsForPath(extensions_dir);
}
void XWalkBrowserMainParts::PreMainMessageLoopRun() {
#if defined(OS_ANDROID)
net::NetModule::SetResourceProvider(PlatformResourceProvider);
if (parameters_.ui_task) {
parameters_.ui_task->Run();
delete parameters_.ui_task;
run_default_message_loop_ = false;
}
DCHECK(runtime_context_);
runtime_context_->PreMainMessageLoopRun();
#else
runtime_context_.reset(new RuntimeContext);
runtime_registry_.reset(new RuntimeRegistry);
extension_service_.reset(
new extensions::XWalkExtensionService(runtime_registry_.get()));
RegisterInternalExtensions();
RegisterExternalExtensions();
CommandLine* command_line = CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(switches::kRemoteDebuggingPort)) {
std::string port_str =
command_line->GetSwitchValueASCII(switches::kRemoteDebuggingPort);
int port;
const char* loopback_ip = "127.0.0.1";
if (base::StringToInt(port_str, &port) && port > 0 && port < 65535) {
remote_debugging_server_.reset(
new RemoteDebuggingServer(runtime_context_.get(),
loopback_ip, port, std::string()));
}
}
NativeAppWindow::Initialize();
if (startup_url_.SchemeIsFile()) {
base::FilePath path;
if (!net::FileURLToFilePath(startup_url_, &path))
return;
if (file_util::DirectoryExists(path)) {
std::string error;
scoped_refptr<xwalk::application::Application> application =
xwalk::application::LoadApplication(
path,
xwalk::application::Manifest::COMMAND_LINE,
&error);
if (!error.empty())
LOG(ERROR) << "Failed to load application: " << error;
if (application != NULL) {
xwalk::application::ApplicationSystem* system =
runtime_context_->GetApplicationSystem();
xwalk::application::ApplicationProcessManager* manager =
system->process_manager();
manager->LaunchApplication(runtime_context_.get(), application);
return;
}
}
}
// The new created Runtime instance will be managed by RuntimeRegistry.
Runtime::Create(runtime_context_.get(), startup_url_);
// If the |ui_task| is specified in main function parameter, it indicates
// that we will run this UI task instead of running the the default main
// message loop. See |content::BrowserTestBase::SetUp| for |ui_task| usage
// case.
if (parameters_.ui_task) {
parameters_.ui_task->Run();
delete parameters_.ui_task;
run_default_message_loop_ = false;
}
#endif
}
bool XWalkBrowserMainParts::MainMessageLoopRun(int* result_code) {
return !run_default_message_loop_;
}
void XWalkBrowserMainParts::PostMainMessageLoopRun() {
#if defined(OS_ANDROID)
MessageLoopForUI::current()->Start();
#else
runtime_context_.reset();
#endif
}
void XWalkBrowserMainParts::RegisterInternalExtensions() {
extension_service_->RegisterExtension(scoped_ptr<XWalkExtension>(
new RuntimeExtension()));
extension_service_->RegisterExtension(scoped_ptr<XWalkExtension>(
new experimental::DialogExtension(runtime_registry_.get())));
}
} // namespace xwalk
<|endoftext|>
|
<commit_before>#pragma once
#include <vpp/core/vector.hh>
#include <vpp/draw/square.hh>
#include <vpp/draw/symbols.hh>
#include <list>
namespace vpp
{
using namespace vpp;
using namespace draw;
template <typename V, typename U>
void line2d_hough(vint2 a, vint2 b, V paint, U paint_border,image2d<unsigned char> grad , int line_width = 5)
{
int x0 = a[1]; int y0 = a[0];
int x1 = b[1]; int y1 = b[0];
int steep = ::abs(y1 - y0) > ::abs(x1 - x0);
if (steep)
{
std::swap(x0, y0);
std::swap(x1, y1);
}
if (x0 > x1)
{
std::swap(x0, x1);
std::swap(y0, y1);
}
int deltax = x1 - x0;
int deltay = ::abs(y1 - y0);
float error = 0.f;
float deltaerr = deltay / float(deltax);
int ystep;
int y = y0;
if (y0 < y1) ystep = 1; else ystep = -1;
for (int x = x0 + 1; x <= x1; x++)
{
vint2 to_plot;
vint2 d1,d2; // line border.
if (steep)
{
to_plot = vint2{x, y};
d1 = vint2{0, -1};
d2 = vint2{0, +1};
}
else
{
to_plot = vint2{y, x};
d1 = vint2{-1, 0};
d2 = vint2{+1, 0};
}
if(grad(to_plot) < 10)
continue;
float interp = float(x - x0) / (x1 - x0);
paint(to_plot, interp);
for (int bi = 1; bi < line_width / 2; bi++)
{
paint_border(to_plot + bi * d1, interp, bi);
paint_border(to_plot + bi * d2, interp, bi);
}
error = error + deltaerr;
if (error >= 0.5)
{
y = y + ystep;
error = error - 1.0;
}
}
}
template <typename V, typename U>
void line2d_hough_particles(std::list<vint2> list_points,vint2 a, vint2 b, V paint, U paint_border, int line_width = 5)
{
int x0 = a[1]; int y0 = a[0];
int x1 = b[1]; int y1 = b[0];
int steep = ::abs(y1 - y0) > ::abs(x1 - x0);
if (steep)
{
std::swap(x0, y0);
std::swap(x1, y1);
}
if (x0 > x1)
{
std::swap(x0, x1);
std::swap(y0, y1);
}
for (auto &list_point : list_points)
{
vint2 to_plot;
vint2 d1,d2; // point.
if (steep)
{
to_plot = list_point;
d1 = vint2{0, -1};
d2 = vint2{0, +1};
}
else
{
to_plot = list_point;
d1 = vint2{-1, 0};
d2 = vint2{+1, 0};
}
float interp = float((list_point)[0] - x0) / (x1 - x0);
paint(to_plot, interp);
for (int bi = 1; bi < line_width / 2; bi++)
{
paint_border(to_plot + bi * d1, interp, bi);
paint_border(to_plot + bi * d2, interp, bi);
}
}
}
}
<commit_msg>delete option to draw lines<commit_after>#pragma once
#include <vpp/core/vector.hh>
#include <vpp/draw/square.hh>
#include <vpp/draw/symbols.hh>
#include <list>
namespace vpp
{
using namespace vpp;
using namespace draw;
template <typename V, typename U>
void line2d_hough(vint2 a, vint2 b, V paint, U paint_border,image2d<unsigned char> grad , int line_width = 5)
{
int x0 = a[1]; int y0 = a[0];
int x1 = b[1]; int y1 = b[0];
int steep = ::abs(y1 - y0) > ::abs(x1 - x0);
if (steep)
{
std::swap(x0, y0);
std::swap(x1, y1);
}
if (x0 > x1)
{
std::swap(x0, x1);
std::swap(y0, y1);
}
int deltax = x1 - x0;
int deltay = ::abs(y1 - y0);
float error = 0.f;
float deltaerr = deltay / float(deltax);
int ystep;
int y = y0;
if (y0 < y1) ystep = 1; else ystep = -1;
for (int x = x0 + 1; x <= x1; x++)
{
vint2 to_plot;
vint2 d1,d2; // line border.
if (steep)
{
to_plot = vint2{x, y};
d1 = vint2{0, -1};
d2 = vint2{0, +1};
}
else
{
to_plot = vint2{y, x};
d1 = vint2{-1, 0};
d2 = vint2{+1, 0};
}
if(grad(to_plot) < 10)
continue;
float interp = float(x - x0) / (x1 - x0);
paint(to_plot, interp);
for (int bi = 1; bi < line_width / 2; bi++)
{
paint_border(to_plot + bi * d1, interp, bi);
paint_border(to_plot + bi * d2, interp, bi);
}
error = error + deltaerr;
if (error >= 0.5)
{
y = y + ystep;
error = error - 1.0;
}
}
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2008, 2010 Apple Inc. All Rights Reserved.
* Copyright (C) 2009 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:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 "core/workers/Worker.h"
#include "bindings/core/v8/ExceptionState.h"
#include "core/dom/Document.h"
#include "core/events/MessageEvent.h"
#include "core/fetch/ResourceFetcher.h"
#include "core/inspector/InspectorInstrumentation.h"
#include "core/frame/LocalDOMWindow.h"
#include "core/frame/UseCounter.h"
#include "core/workers/WorkerGlobalScopeProxy.h"
#include "core/workers/WorkerGlobalScopeProxyProvider.h"
#include "core/workers/WorkerScriptLoader.h"
#include "core/workers/WorkerThread.h"
#include "wtf/MainThread.h"
namespace WebCore {
inline Worker::Worker(ExecutionContext* context)
: AbstractWorker(context)
, m_contextProxy(0)
{
ScriptWrappable::init(this);
}
PassRefPtrWillBeRawPtr<Worker> Worker::create(ExecutionContext* context, const String& url, ExceptionState& exceptionState)
{
ASSERT(isMainThread());
Document* document = toDocument(context);
UseCounter::count(context, UseCounter::WorkerStart);
if (!document->page()) {
exceptionState.throwDOMException(InvalidAccessError, "The context provided is invalid.");
return nullptr;
}
WorkerGlobalScopeProxyProvider* proxyProvider = WorkerGlobalScopeProxyProvider::from(*document->page());
ASSERT(proxyProvider);
RefPtrWillBeRawPtr<Worker> worker = adoptRefWillBeRefCountedGarbageCollected(new Worker(context));
worker->suspendIfNeeded();
KURL scriptURL = worker->resolveURL(url, exceptionState);
if (scriptURL.isEmpty())
return nullptr;
// The worker context does not exist while loading, so we must ensure that the worker object is not collected, nor are its event listeners.
worker->setPendingActivity(worker.get());
worker->m_scriptLoader = WorkerScriptLoader::create();
worker->m_scriptLoader->loadAsynchronously(*context, scriptURL, DenyCrossOriginRequests, worker.get());
worker->m_contextProxy = proxyProvider->createWorkerGlobalScopeProxy(worker.get());
return worker.release();
}
Worker::~Worker()
{
ASSERT(isMainThread());
ASSERT(executionContext()); // The context is protected by worker context proxy, so it cannot be destroyed while a Worker exists.
if (m_contextProxy)
m_contextProxy->workerObjectDestroyed();
}
const AtomicString& Worker::interfaceName() const
{
return EventTargetNames::Worker;
}
void Worker::postMessage(PassRefPtr<SerializedScriptValue> message, const MessagePortArray* ports, ExceptionState& exceptionState)
{
// Disentangle the port in preparation for sending it to the remote context.
OwnPtr<MessagePortChannelArray> channels = MessagePort::disentanglePorts(ports, exceptionState);
if (exceptionState.hadException())
return;
m_contextProxy->postMessageToWorkerGlobalScope(message, channels.release());
}
void Worker::terminate()
{
if (m_contextProxy)
m_contextProxy->terminateWorkerGlobalScope();
}
void Worker::stop()
{
terminate();
}
bool Worker::hasPendingActivity() const
{
return m_contextProxy->hasPendingActivity() || ActiveDOMObject::hasPendingActivity();
}
void Worker::didReceiveResponse(unsigned long identifier, const ResourceResponse&)
{
InspectorInstrumentation::didReceiveScriptResponse(executionContext(), identifier);
}
void Worker::notifyFinished()
{
if (m_scriptLoader->failed()) {
dispatchEvent(Event::createCancelable(EventTypeNames::error));
} else {
WorkerThreadStartMode startMode = DontPauseWorkerGlobalScopeOnStart;
if (InspectorInstrumentation::shouldPauseDedicatedWorkerOnStart(executionContext()))
startMode = PauseWorkerGlobalScopeOnStart;
m_contextProxy->startWorkerGlobalScope(m_scriptLoader->url(), executionContext()->userAgent(m_scriptLoader->url()), m_scriptLoader->script(), startMode);
InspectorInstrumentation::scriptImported(executionContext(), m_scriptLoader->identifier(), m_scriptLoader->script());
}
m_scriptLoader = nullptr;
unsetPendingActivity(this);
}
void Worker::trace(Visitor* visitor)
{
AbstractWorker::trace(visitor);
}
} // namespace WebCore
<commit_msg>Have the Worker destructor handle non-started Workers better.<commit_after>/*
* Copyright (C) 2008, 2010 Apple Inc. All Rights Reserved.
* Copyright (C) 2009 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:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 "core/workers/Worker.h"
#include "bindings/core/v8/ExceptionState.h"
#include "core/dom/Document.h"
#include "core/events/MessageEvent.h"
#include "core/fetch/ResourceFetcher.h"
#include "core/inspector/InspectorInstrumentation.h"
#include "core/frame/LocalDOMWindow.h"
#include "core/frame/UseCounter.h"
#include "core/workers/WorkerGlobalScopeProxy.h"
#include "core/workers/WorkerGlobalScopeProxyProvider.h"
#include "core/workers/WorkerScriptLoader.h"
#include "core/workers/WorkerThread.h"
#include "wtf/MainThread.h"
namespace WebCore {
inline Worker::Worker(ExecutionContext* context)
: AbstractWorker(context)
, m_contextProxy(0)
{
ScriptWrappable::init(this);
}
PassRefPtrWillBeRawPtr<Worker> Worker::create(ExecutionContext* context, const String& url, ExceptionState& exceptionState)
{
ASSERT(isMainThread());
Document* document = toDocument(context);
UseCounter::count(context, UseCounter::WorkerStart);
if (!document->page()) {
exceptionState.throwDOMException(InvalidAccessError, "The context provided is invalid.");
return nullptr;
}
WorkerGlobalScopeProxyProvider* proxyProvider = WorkerGlobalScopeProxyProvider::from(*document->page());
ASSERT(proxyProvider);
RefPtrWillBeRawPtr<Worker> worker = adoptRefWillBeRefCountedGarbageCollected(new Worker(context));
worker->suspendIfNeeded();
KURL scriptURL = worker->resolveURL(url, exceptionState);
if (scriptURL.isEmpty())
return nullptr;
// The worker context does not exist while loading, so we must ensure that the worker object is not collected, nor are its event listeners.
worker->setPendingActivity(worker.get());
worker->m_scriptLoader = WorkerScriptLoader::create();
worker->m_scriptLoader->loadAsynchronously(*context, scriptURL, DenyCrossOriginRequests, worker.get());
worker->m_contextProxy = proxyProvider->createWorkerGlobalScopeProxy(worker.get());
return worker.release();
}
Worker::~Worker()
{
ASSERT(isMainThread());
if (!m_contextProxy)
return;
ASSERT(executionContext()); // The context is protected by worker context proxy, so it cannot be destroyed while a Worker exists.
m_contextProxy->workerObjectDestroyed();
}
const AtomicString& Worker::interfaceName() const
{
return EventTargetNames::Worker;
}
void Worker::postMessage(PassRefPtr<SerializedScriptValue> message, const MessagePortArray* ports, ExceptionState& exceptionState)
{
ASSERT(m_contextProxy);
// Disentangle the port in preparation for sending it to the remote context.
OwnPtr<MessagePortChannelArray> channels = MessagePort::disentanglePorts(ports, exceptionState);
if (exceptionState.hadException())
return;
m_contextProxy->postMessageToWorkerGlobalScope(message, channels.release());
}
void Worker::terminate()
{
if (m_contextProxy)
m_contextProxy->terminateWorkerGlobalScope();
}
void Worker::stop()
{
terminate();
}
bool Worker::hasPendingActivity() const
{
return (m_contextProxy && m_contextProxy->hasPendingActivity()) || ActiveDOMObject::hasPendingActivity();
}
void Worker::didReceiveResponse(unsigned long identifier, const ResourceResponse&)
{
InspectorInstrumentation::didReceiveScriptResponse(executionContext(), identifier);
}
void Worker::notifyFinished()
{
if (m_scriptLoader->failed()) {
dispatchEvent(Event::createCancelable(EventTypeNames::error));
} else {
ASSERT(m_contextProxy);
WorkerThreadStartMode startMode = DontPauseWorkerGlobalScopeOnStart;
if (InspectorInstrumentation::shouldPauseDedicatedWorkerOnStart(executionContext()))
startMode = PauseWorkerGlobalScopeOnStart;
m_contextProxy->startWorkerGlobalScope(m_scriptLoader->url(), executionContext()->userAgent(m_scriptLoader->url()), m_scriptLoader->script(), startMode);
InspectorInstrumentation::scriptImported(executionContext(), m_scriptLoader->identifier(), m_scriptLoader->script());
}
m_scriptLoader = nullptr;
unsetPendingActivity(this);
}
void Worker::trace(Visitor* visitor)
{
AbstractWorker::trace(visitor);
}
} // namespace WebCore
<|endoftext|>
|
<commit_before>/*
* Copyright 2014 Real Logic Ltd.
*
* 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 "ClientConductor.h"
using namespace aeron;
template <typename A>
inline static std::size_t findInVector(std::vector<A>& container, std::function<int(A)> compare)
{
std::size_t result = SIZE_MAX;
for (std::size_t i = 0; i < container.size(); i++)
{
if (compare(container[i]) == 0)
{
result = i;
break;
}
}
return result;
}
Publication* ClientConductor::addPublication(const std::string& channel, std::int32_t streamId, std::int32_t sessionId)
{
std::lock_guard<std::mutex> lock(m_publicationsLock);
std::size_t element = findInVector<Publication*>(m_publications, [&](Publication* pub)
{
return (streamId == pub->streamId() && sessionId == pub->sessionId() && channel == pub->channel());
});
Publication* publication = nullptr;
if (SIZE_MAX == element)
{
std::int64_t correlationId = 0;
publication = new Publication(*this, channel, streamId, sessionId, correlationId);
m_publications.push_back(publication);
}
else
{
publication = m_publications[element];
}
return publication;
}
void ClientConductor::releasePublication(Publication* publication)
{
std::lock_guard<std::mutex> lock(m_publicationsLock);
// TODO: send command to driver?
std::size_t element = findInVector<Publication*>(m_publications, [&](Publication* pub)
{
return pub == publication;
});
if (SIZE_MAX != element)
{
m_publications.erase(m_publications.begin() + element);
}
}
Subscription* ClientConductor::addSubscription(const std::string& channel, std::int32_t streamId, logbuffer::handler_t& handler)
{
std::lock_guard<std::mutex> lock(m_subscriptionsLock);
std::size_t element = findInVector<Subscription*>(m_subscriptions, [&](Subscription* sub)
{
return (streamId == sub->streamId() && channel == sub->channel());
});
Subscription* subscription = nullptr;
if (SIZE_MAX == element)
{
subscription = new Subscription(*this, channel, streamId);
m_subscriptions.push_back(subscription);
// TODO: send command to driver
}
else
{
subscription = m_subscriptions[element];
}
return subscription;
}
void ClientConductor::releaseSubscription(Subscription* subscription)
{
std::lock_guard<std::mutex> lock(m_subscriptionsLock);
// TODO: send command to driver?
std::size_t element = findInVector<Subscription*>(m_subscriptions, [&](Subscription* sub)
{
return sub == subscription;
});
if (SIZE_MAX != element)
{
m_subscriptions.erase(m_subscriptions.begin() + element);
}
}
void ClientConductor::onNewPublication(
std::int64_t correlationId,
const std::string& channel,
std::int32_t streamId,
std::int32_t sessionId,
std::int32_t termId,
std::int32_t positionCounterId,
std::int32_t mtuLengt,
const PublicationReadyFlyweight& publicationReady)
{
}
<commit_msg>[C++]: remove stray include.<commit_after>/*
* Copyright 2014 Real Logic Ltd.
*
* 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 "ClientConductor.h"
using namespace aeron;
template <typename A>
inline static std::size_t findInVector(std::vector<A>& container, std::function<int(A)> compare)
{
std::size_t result = SIZE_MAX;
for (std::size_t i = 0; i < container.size(); i++)
{
if (compare(container[i]) == 0)
{
result = i;
break;
}
}
return result;
}
Publication* ClientConductor::addPublication(const std::string& channel, std::int32_t streamId, std::int32_t sessionId)
{
std::lock_guard<std::mutex> lock(m_publicationsLock);
std::size_t element = findInVector<Publication*>(m_publications, [&](Publication* pub)
{
return (streamId == pub->streamId() && sessionId == pub->sessionId() && channel == pub->channel());
});
Publication* publication = nullptr;
if (SIZE_MAX == element)
{
std::int64_t correlationId = m_driverProxy.addPublication(channel, streamId, sessionId);
publication = new Publication(*this, channel, streamId, sessionId, correlationId);
m_publications.push_back(publication);
}
else
{
publication = m_publications[element];
}
return publication;
}
void ClientConductor::releasePublication(Publication* publication)
{
std::lock_guard<std::mutex> lock(m_publicationsLock);
// TODO: send command to driver?
std::size_t element = findInVector<Publication*>(m_publications, [&](Publication* pub)
{
return pub == publication;
});
if (SIZE_MAX != element)
{
m_publications.erase(m_publications.begin() + element);
}
}
Subscription* ClientConductor::addSubscription(const std::string& channel, std::int32_t streamId, logbuffer::handler_t& handler)
{
std::lock_guard<std::mutex> lock(m_subscriptionsLock);
std::size_t element = findInVector<Subscription*>(m_subscriptions, [&](Subscription* sub)
{
return (streamId == sub->streamId() && channel == sub->channel());
});
Subscription* subscription = nullptr;
if (SIZE_MAX == element)
{
subscription = new Subscription(*this, channel, streamId);
m_subscriptions.push_back(subscription);
// TODO: send command to driver
}
else
{
subscription = m_subscriptions[element];
}
return subscription;
}
void ClientConductor::releaseSubscription(Subscription* subscription)
{
std::lock_guard<std::mutex> lock(m_subscriptionsLock);
// TODO: send command to driver?
std::size_t element = findInVector<Subscription*>(m_subscriptions, [&](Subscription* sub)
{
return sub == subscription;
});
if (SIZE_MAX != element)
{
m_subscriptions.erase(m_subscriptions.begin() + element);
}
}
void ClientConductor::onNewPublication(
std::int64_t correlationId,
const std::string& channel,
std::int32_t streamId,
std::int32_t sessionId,
std::int32_t termId,
std::int32_t positionCounterId,
std::int32_t mtuLengt,
const PublicationReadyFlyweight& publicationReady)
{
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2017, Arm Limited and affiliates.
* SPDX-License-Identifier: Apache-2.0
*
* 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 "rtos/ThisThread.h"
#include "mbed_error.h"
#include "platform/mbed_atomic.h"
#include "events/EventQueue.h"
#include "events/mbed_shared_queues.h"
#include "QUECTEL_BC95_CellularStack.h"
#include "CellularUtil.h"
#include "CellularLog.h"
#define PACKET_SIZE_MAX 1358
#define TXFULL_EVENT_TIMEOUT 1s
#define AT_UPLINK_BUSY 159
#define AT_UART_BUFFER_ERROR 536
#define AT_BACK_OFF_TIMER 537
using namespace std::chrono;
using namespace mbed;
using namespace mbed_cellular_util;
QUECTEL_BC95_CellularStack::QUECTEL_BC95_CellularStack(ATHandler &atHandler, int cid, nsapi_ip_stack_t stack_type, AT_CellularDevice &device) :
AT_CellularStack(atHandler, cid, stack_type, device), _event_queue(mbed_event_queue()), _txfull_event_id(0)
{
_at.set_urc_handler("+NSONMI:", mbed::Callback<void()>(this, &QUECTEL_BC95_CellularStack::urc_nsonmi));
_at.set_urc_handler("+NSOCLI:", mbed::Callback<void()>(this, &QUECTEL_BC95_CellularStack::urc_nsocli));
}
QUECTEL_BC95_CellularStack::~QUECTEL_BC95_CellularStack()
{
if (_txfull_event_id) {
_event_queue->cancel(_txfull_event_id);
}
_at.set_urc_handler("+NSONMI:", nullptr);
_at.set_urc_handler("+NSOCLI:", nullptr);
}
nsapi_error_t QUECTEL_BC95_CellularStack::socket_listen(nsapi_socket_t handle, int backlog)
{
return NSAPI_ERROR_UNSUPPORTED;
}
nsapi_error_t QUECTEL_BC95_CellularStack::socket_accept(void *server, void **socket, SocketAddress *addr)
{
return NSAPI_ERROR_UNSUPPORTED;
}
nsapi_error_t QUECTEL_BC95_CellularStack::socket_connect(nsapi_socket_t handle, const SocketAddress &address)
{
CellularSocket *socket = (CellularSocket *)handle;
_at.lock();
if (socket->id == -1) {
const nsapi_error_t error_create = create_socket_impl(socket);
if (error_create != NSAPI_ERROR_OK) {
return error_create;
}
}
_at.cmd_start("AT+NSOCO=");
_at.write_int(socket->id);
_at.write_string(address.get_ip_address(), false);
_at.write_int(address.get_port());
_at.cmd_stop_read_resp();
_at.unlock();
if (_at.get_last_error() == NSAPI_ERROR_OK) {
socket->remoteAddress = address;
socket->connected = true;
return NSAPI_ERROR_OK;
}
return NSAPI_ERROR_NO_CONNECTION;
}
void QUECTEL_BC95_CellularStack::urc_nsonmi()
{
int sock_id = _at.read_int();
for (int i = 0; i < _device.get_property(AT_CellularDevice::PROPERTY_SOCKET_COUNT); i++) {
CellularSocket *sock = _socket[i];
if (sock && sock->id == sock_id) {
if (sock->_cb) {
sock->_cb(sock->_data);
}
break;
}
}
}
void QUECTEL_BC95_CellularStack::urc_nsocli()
{
int sock_id = _at.read_int();
const nsapi_error_t err = _at.get_last_error();
if (err != NSAPI_ERROR_OK) {
return;
}
CellularSocket *sock = find_socket(sock_id);
if (sock) {
sock->closed = true;
if (sock->_cb) {
sock->_cb(sock->_data);
}
tr_info("Socket closed %d", sock_id);
}
}
nsapi_error_t QUECTEL_BC95_CellularStack::socket_close_impl(int sock_id)
{
CellularSocket *sock = find_socket(sock_id);
if (sock && sock->closed) {
return NSAPI_ERROR_OK;
}
sock->txfull_event = false;
nsapi_error_t err = _at.at_cmd_discard("+NSOCL", "=", "%d", sock_id);
tr_info("Close socket: %d error: %d", sock_id, err);
return err;
}
nsapi_error_t QUECTEL_BC95_CellularStack::create_socket_impl(CellularSocket *socket)
{
int sock_id = -1;
bool socketOpenWorking = false;
if (socket->proto == NSAPI_UDP) {
_at.cmd_start_stop("+NSOCR", "=DGRAM,", "%d%d%d%s", 17, socket->localAddress.get_port(), 1, ((_ip_ver_sendto == NSAPI_IPv4) ? "AF_INET" : "AF_INET6"));
} else if (socket->proto == NSAPI_TCP) {
_at.cmd_start_stop("+NSOCR", "=STREAM,", "%d%d%d%s", 6, socket->localAddress.get_port(), 1, ((_ip_ver_sendto == NSAPI_IPv4) ? "AF_INET" : "AF_INET6"));
} else {
return NSAPI_ERROR_PARAMETER;
}
_at.resp_start();
sock_id = _at.read_int();
_at.resp_stop();
socketOpenWorking = (_at.get_last_error() == NSAPI_ERROR_OK);
if (!socketOpenWorking || (sock_id == -1)) {
tr_error("Socket create failed!");
return NSAPI_ERROR_NO_SOCKET;
}
tr_info("Socket create id: %d", sock_id);
socket->id = sock_id;
return NSAPI_ERROR_OK;
}
nsapi_size_or_error_t QUECTEL_BC95_CellularStack::socket_sendto_impl(CellularSocket *socket, const SocketAddress &address,
const void *data, nsapi_size_t size)
{
//AT_CellularStack::socket_sendto(...) will create a socket on modem if it wasn't
// open already.
MBED_ASSERT(socket->id != -1);
if (_ip_ver_sendto != address.get_ip_version()) {
_ip_ver_sendto = address.get_ip_version();
socket_close_impl(socket->id);
create_socket_impl(socket);
}
int sent_len = 0;
if (size > PACKET_SIZE_MAX) {
return NSAPI_ERROR_PARAMETER;
}
int retry = 0;
retry_send:
if (socket->proto == NSAPI_UDP) {
_at.cmd_start("AT+NSOST=");
_at.write_int(socket->id);
_at.write_string(address.get_ip_address(), false);
_at.write_int(address.get_port());
_at.write_int(size);
} else if (socket->proto == NSAPI_TCP) {
_at.cmd_start("AT+NSOSD=");
_at.write_int(socket->id);
_at.write_int(size);
} else {
return NSAPI_ERROR_PARAMETER;
}
_at.write_hex_string((char *)data, size);
_at.cmd_stop();
_at.resp_start();
// skip socket id
_at.skip_param();
sent_len = _at.read_int();
_at.resp_stop();
if (_at.get_last_error() == NSAPI_ERROR_OK) {
return sent_len;
}
// check for network congestion
device_err_t err = _at.get_last_device_error();
if (err.errType == DeviceErrorTypeErrorCME &&
(err.errCode == AT_UART_BUFFER_ERROR || err.errCode == AT_BACK_OFF_TIMER) || err.errCode == AT_UPLINK_BUSY) {
if (socket->proto == NSAPI_UDP) {
if (retry < 3) {
retry++;
tr_warn("Socket %d sendto EAGAIN", socket->id);
rtos::ThisThread::sleep_for(30ms);
_at.clear_error();
goto retry_send;
}
return NSAPI_ERROR_NO_MEMORY;
}
_socket_mutex.lock();
if (!socket->txfull_event && !_txfull_event_id) {
tr_warn("socket %d tx full", socket->id);
socket->txfull_event = true;
_txfull_event_id = _event_queue->call_in(TXFULL_EVENT_TIMEOUT, callback(this, &QUECTEL_BC95_CellularStack::txfull_event_timeout));
if (!_txfull_event_id) {
MBED_ERROR(MBED_MAKE_ERROR(MBED_MODULE_DRIVER, MBED_ERROR_CODE_ENOMEM), \
"QUECTEL_BC95_CellularStack::socket_sendto_impl(): unable to add event to queue. Increase \"events.shared-eventsize\"\n");
_socket_mutex.unlock();
return NSAPI_ERROR_NO_MEMORY;
}
}
_socket_mutex.unlock();
return NSAPI_ERROR_WOULD_BLOCK;
}
return _at.get_last_error();
}
nsapi_size_or_error_t QUECTEL_BC95_CellularStack::socket_recvfrom_impl(CellularSocket *socket, SocketAddress *address,
void *buffer, nsapi_size_t size)
{
//AT_CellularStack::socket_recvfrom(...) will create a socket on modem if it wasn't
// open already.
MBED_ASSERT(socket->id != -1);
nsapi_size_or_error_t recv_len = 0;
int port;
char ip_address[NSAPI_IP_SIZE];
_at.cmd_start_stop("+NSORF", "=", "%d%d", socket->id, size < PACKET_SIZE_MAX ? size : PACKET_SIZE_MAX);
_at.resp_start();
// receiving socket id
_at.skip_param();
_at.read_string(ip_address, sizeof(ip_address));
port = _at.read_int();
recv_len = _at.read_int();
int hexlen = _at.read_hex_string((char *)buffer, recv_len);
// remaining length
_at.skip_param();
_at.resp_stop();
if (!recv_len || (recv_len == -1) || (_at.get_last_error() != NSAPI_ERROR_OK)) {
return NSAPI_ERROR_WOULD_BLOCK;
}
if (address) {
address->set_ip_address(ip_address);
address->set_port(port);
}
if (recv_len != hexlen) {
tr_error("Not received as much data as expected. Should receive: %d bytes, received: %d bytes", recv_len, hexlen);
}
return recv_len;
}
void QUECTEL_BC95_CellularStack::txfull_event_timeout()
{
_socket_mutex.lock();
_txfull_event_id = 0;
for (int i = 0; i < _device.get_property(AT_CellularDevice::PROPERTY_SOCKET_COUNT); i++) {
CellularSocket *sock = _socket[i];
if (sock && sock->_cb && sock->txfull_event) {
sock->txfull_event = false;
sock->_cb(sock->_data);
}
}
_socket_mutex.unlock();
}
<commit_msg>fixed warnings: suggest parentheses around '&&' within '||'<commit_after>/*
* Copyright (c) 2017, Arm Limited and affiliates.
* SPDX-License-Identifier: Apache-2.0
*
* 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 "rtos/ThisThread.h"
#include "mbed_error.h"
#include "platform/mbed_atomic.h"
#include "events/EventQueue.h"
#include "events/mbed_shared_queues.h"
#include "QUECTEL_BC95_CellularStack.h"
#include "CellularUtil.h"
#include "CellularLog.h"
#define PACKET_SIZE_MAX 1358
#define TXFULL_EVENT_TIMEOUT 1s
#define AT_UPLINK_BUSY 159
#define AT_UART_BUFFER_ERROR 536
#define AT_BACK_OFF_TIMER 537
using namespace std::chrono;
using namespace mbed;
using namespace mbed_cellular_util;
QUECTEL_BC95_CellularStack::QUECTEL_BC95_CellularStack(ATHandler &atHandler, int cid, nsapi_ip_stack_t stack_type, AT_CellularDevice &device) :
AT_CellularStack(atHandler, cid, stack_type, device), _event_queue(mbed_event_queue()), _txfull_event_id(0)
{
_at.set_urc_handler("+NSONMI:", mbed::Callback<void()>(this, &QUECTEL_BC95_CellularStack::urc_nsonmi));
_at.set_urc_handler("+NSOCLI:", mbed::Callback<void()>(this, &QUECTEL_BC95_CellularStack::urc_nsocli));
}
QUECTEL_BC95_CellularStack::~QUECTEL_BC95_CellularStack()
{
if (_txfull_event_id) {
_event_queue->cancel(_txfull_event_id);
}
_at.set_urc_handler("+NSONMI:", nullptr);
_at.set_urc_handler("+NSOCLI:", nullptr);
}
nsapi_error_t QUECTEL_BC95_CellularStack::socket_listen(nsapi_socket_t handle, int backlog)
{
return NSAPI_ERROR_UNSUPPORTED;
}
nsapi_error_t QUECTEL_BC95_CellularStack::socket_accept(void *server, void **socket, SocketAddress *addr)
{
return NSAPI_ERROR_UNSUPPORTED;
}
nsapi_error_t QUECTEL_BC95_CellularStack::socket_connect(nsapi_socket_t handle, const SocketAddress &address)
{
CellularSocket *socket = (CellularSocket *)handle;
_at.lock();
if (socket->id == -1) {
const nsapi_error_t error_create = create_socket_impl(socket);
if (error_create != NSAPI_ERROR_OK) {
return error_create;
}
}
_at.cmd_start("AT+NSOCO=");
_at.write_int(socket->id);
_at.write_string(address.get_ip_address(), false);
_at.write_int(address.get_port());
_at.cmd_stop_read_resp();
_at.unlock();
if (_at.get_last_error() == NSAPI_ERROR_OK) {
socket->remoteAddress = address;
socket->connected = true;
return NSAPI_ERROR_OK;
}
return NSAPI_ERROR_NO_CONNECTION;
}
void QUECTEL_BC95_CellularStack::urc_nsonmi()
{
int sock_id = _at.read_int();
for (int i = 0; i < _device.get_property(AT_CellularDevice::PROPERTY_SOCKET_COUNT); i++) {
CellularSocket *sock = _socket[i];
if (sock && sock->id == sock_id) {
if (sock->_cb) {
sock->_cb(sock->_data);
}
break;
}
}
}
void QUECTEL_BC95_CellularStack::urc_nsocli()
{
int sock_id = _at.read_int();
const nsapi_error_t err = _at.get_last_error();
if (err != NSAPI_ERROR_OK) {
return;
}
CellularSocket *sock = find_socket(sock_id);
if (sock) {
sock->closed = true;
if (sock->_cb) {
sock->_cb(sock->_data);
}
tr_info("Socket closed %d", sock_id);
}
}
nsapi_error_t QUECTEL_BC95_CellularStack::socket_close_impl(int sock_id)
{
CellularSocket *sock = find_socket(sock_id);
if (sock && sock->closed) {
return NSAPI_ERROR_OK;
}
sock->txfull_event = false;
nsapi_error_t err = _at.at_cmd_discard("+NSOCL", "=", "%d", sock_id);
tr_info("Close socket: %d error: %d", sock_id, err);
return err;
}
nsapi_error_t QUECTEL_BC95_CellularStack::create_socket_impl(CellularSocket *socket)
{
int sock_id = -1;
bool socketOpenWorking = false;
if (socket->proto == NSAPI_UDP) {
_at.cmd_start_stop("+NSOCR", "=DGRAM,", "%d%d%d%s", 17, socket->localAddress.get_port(), 1, ((_ip_ver_sendto == NSAPI_IPv4) ? "AF_INET" : "AF_INET6"));
} else if (socket->proto == NSAPI_TCP) {
_at.cmd_start_stop("+NSOCR", "=STREAM,", "%d%d%d%s", 6, socket->localAddress.get_port(), 1, ((_ip_ver_sendto == NSAPI_IPv4) ? "AF_INET" : "AF_INET6"));
} else {
return NSAPI_ERROR_PARAMETER;
}
_at.resp_start();
sock_id = _at.read_int();
_at.resp_stop();
socketOpenWorking = (_at.get_last_error() == NSAPI_ERROR_OK);
if (!socketOpenWorking || (sock_id == -1)) {
tr_error("Socket create failed!");
return NSAPI_ERROR_NO_SOCKET;
}
tr_info("Socket create id: %d", sock_id);
socket->id = sock_id;
return NSAPI_ERROR_OK;
}
nsapi_size_or_error_t QUECTEL_BC95_CellularStack::socket_sendto_impl(CellularSocket *socket, const SocketAddress &address,
const void *data, nsapi_size_t size)
{
//AT_CellularStack::socket_sendto(...) will create a socket on modem if it wasn't
// open already.
MBED_ASSERT(socket->id != -1);
if (_ip_ver_sendto != address.get_ip_version()) {
_ip_ver_sendto = address.get_ip_version();
socket_close_impl(socket->id);
create_socket_impl(socket);
}
int sent_len = 0;
if (size > PACKET_SIZE_MAX) {
return NSAPI_ERROR_PARAMETER;
}
int retry = 0;
retry_send:
if (socket->proto == NSAPI_UDP) {
_at.cmd_start("AT+NSOST=");
_at.write_int(socket->id);
_at.write_string(address.get_ip_address(), false);
_at.write_int(address.get_port());
_at.write_int(size);
} else if (socket->proto == NSAPI_TCP) {
_at.cmd_start("AT+NSOSD=");
_at.write_int(socket->id);
_at.write_int(size);
} else {
return NSAPI_ERROR_PARAMETER;
}
_at.write_hex_string((char *)data, size);
_at.cmd_stop();
_at.resp_start();
// skip socket id
_at.skip_param();
sent_len = _at.read_int();
_at.resp_stop();
if (_at.get_last_error() == NSAPI_ERROR_OK) {
return sent_len;
}
// check for network congestion
device_err_t err = _at.get_last_device_error();
if ((err.errType == DeviceErrorTypeErrorCME &&
(err.errCode == AT_UART_BUFFER_ERROR || err.errCode == AT_BACK_OFF_TIMER)) || err.errCode == AT_UPLINK_BUSY) {
if (socket->proto == NSAPI_UDP) {
if (retry < 3) {
retry++;
tr_warn("Socket %d sendto EAGAIN", socket->id);
rtos::ThisThread::sleep_for(30ms);
_at.clear_error();
goto retry_send;
}
return NSAPI_ERROR_NO_MEMORY;
}
_socket_mutex.lock();
if (!socket->txfull_event && !_txfull_event_id) {
tr_warn("socket %d tx full", socket->id);
socket->txfull_event = true;
_txfull_event_id = _event_queue->call_in(TXFULL_EVENT_TIMEOUT, callback(this, &QUECTEL_BC95_CellularStack::txfull_event_timeout));
if (!_txfull_event_id) {
MBED_ERROR(MBED_MAKE_ERROR(MBED_MODULE_DRIVER, MBED_ERROR_CODE_ENOMEM), \
"QUECTEL_BC95_CellularStack::socket_sendto_impl(): unable to add event to queue. Increase \"events.shared-eventsize\"\n");
_socket_mutex.unlock();
return NSAPI_ERROR_NO_MEMORY;
}
}
_socket_mutex.unlock();
return NSAPI_ERROR_WOULD_BLOCK;
}
return _at.get_last_error();
}
nsapi_size_or_error_t QUECTEL_BC95_CellularStack::socket_recvfrom_impl(CellularSocket *socket, SocketAddress *address,
void *buffer, nsapi_size_t size)
{
//AT_CellularStack::socket_recvfrom(...) will create a socket on modem if it wasn't
// open already.
MBED_ASSERT(socket->id != -1);
nsapi_size_or_error_t recv_len = 0;
int port;
char ip_address[NSAPI_IP_SIZE];
_at.cmd_start_stop("+NSORF", "=", "%d%d", socket->id, size < PACKET_SIZE_MAX ? size : PACKET_SIZE_MAX);
_at.resp_start();
// receiving socket id
_at.skip_param();
_at.read_string(ip_address, sizeof(ip_address));
port = _at.read_int();
recv_len = _at.read_int();
int hexlen = _at.read_hex_string((char *)buffer, recv_len);
// remaining length
_at.skip_param();
_at.resp_stop();
if (!recv_len || (recv_len == -1) || (_at.get_last_error() != NSAPI_ERROR_OK)) {
return NSAPI_ERROR_WOULD_BLOCK;
}
if (address) {
address->set_ip_address(ip_address);
address->set_port(port);
}
if (recv_len != hexlen) {
tr_error("Not received as much data as expected. Should receive: %d bytes, received: %d bytes", recv_len, hexlen);
}
return recv_len;
}
void QUECTEL_BC95_CellularStack::txfull_event_timeout()
{
_socket_mutex.lock();
_txfull_event_id = 0;
for (int i = 0; i < _device.get_property(AT_CellularDevice::PROPERTY_SOCKET_COUNT); i++) {
CellularSocket *sock = _socket[i];
if (sock && sock->_cb && sock->txfull_event) {
sock->txfull_event = false;
sock->_cb(sock->_data);
}
}
_socket_mutex.unlock();
}
<|endoftext|>
|
<commit_before>#include <bts/db/object_database.hpp>
#include <bts/db/undo_database.hpp>
#include <fc/reflect/variant.hpp>
namespace bts { namespace db {
void undo_database::enable() { _disabled = false; }
void undo_database::disable() { _disabled = true; }
undo_database::session undo_database::start_undo_session()
{
if( _disabled ) return session(*this);
if( size() == max_size() )
_stack.pop_front();
_stack.emplace_back();
++_active_sessions;
return session(*this);
}
void undo_database::on_create( const object& obj )
{
if( _disabled ) return;
if( _stack.empty() )
_stack.emplace_back();
auto& state = _stack.back();
auto index_id = object_id_type( obj.id.space(), obj.id.type(), 0 );
auto itr = state.old_index_next_ids.find( index_id );
if( itr == state.old_index_next_ids.end() )
state.old_index_next_ids[index_id] = obj.id;
state.new_ids.insert(obj.id);
}
void undo_database::on_modify( const object& obj )
{
if( _disabled ) return;
if( _stack.empty() )
_stack.emplace_back();
auto& state = _stack.back();
if( state.new_ids.find(obj.id) != state.new_ids.end() )
return;
auto itr = state.old_values.find(obj.id);
if( itr != state.old_values.end() ) return;
state.old_values[obj.id] = obj.clone();
}
void undo_database::on_remove( const object& obj )
{
if( _disabled ) return;
if( _stack.empty() )
_stack.emplace_back();
auto& state = _stack.back();
if( state.new_ids.find(obj.id) != state.new_ids.end() )
{
state.new_ids.erase(obj.id);
return;
}
auto itr = state.removed.find(obj.id);
if( itr != state.removed.end() ) return;
state.removed[obj.id] = obj.clone();
}
void undo_database::undo()
{ try {
FC_ASSERT( !_disabled );
FC_ASSERT( _active_sessions > 0 );
disable();
auto& state = _stack.back();
for( auto& item : state.old_values )
{
_db.modify( _db.get_object( item.second->id ), [&]( object& obj ){ obj.move_from( *item.second ); } );
}
for( auto ritr = state.new_ids.rbegin(); ritr != state.new_ids.rend(); ++ritr )
{
_db.remove( _db.get_object(*ritr) );
}
for( auto& item : state.old_index_next_ids )
{
_db.get_mutable_index( item.first.space(), item.first.type() ).set_next_id( item.second );
}
for( auto& item : state.removed )
_db.insert( std::move(*item.second) );
_stack.pop_back();
if( _stack.empty() )
_stack.emplace_back();
enable();
--_active_sessions;
} FC_CAPTURE_AND_RETHROW() }
void undo_database::merge()
{
FC_ASSERT( _active_sessions > 0 );
FC_ASSERT( _stack.size() >=2 );
auto& state = _stack.back();
auto& prev_state = _stack[_stack.size()-2];
for( auto& obj : state.old_values )
{
if( prev_state.new_ids.find(obj.second->id) != prev_state.new_ids.end() )
continue;
if( prev_state.old_values.find(obj.second->id) == prev_state.old_values.end() )
prev_state.old_values[obj.second->id] = std::move(obj.second);
}
for( auto id : state.new_ids )
prev_state.new_ids.insert(id);
for( auto& item : state.old_index_next_ids )
{
if( prev_state.old_index_next_ids.find( item.first ) == prev_state.old_index_next_ids.end() )
prev_state.old_index_next_ids[item.first] = item.second;
}
for( auto& obj : state.removed )
if( prev_state.new_ids.find(obj.second->id) == prev_state.new_ids.end() )
prev_state.removed[obj.second->id] = std::move(obj.second);
else
prev_state.new_ids.erase(obj.second->id);
_stack.pop_back();
--_active_sessions;
}
void undo_database::commit()
{
--_active_sessions;
}
void undo_database::pop_commit()
{
FC_ASSERT( _active_sessions == 0 );
FC_ASSERT( !_stack.empty() );
disable();
try {
auto& state = _stack.back();
for( auto& item : state.old_values )
{
_db.modify( _db.get_object( item.second->id ), [&]( object& obj ){ obj.move_from( *item.second ); } );
}
for( auto ritr = state.new_ids.rbegin(); ritr != state.new_ids.rend(); ++ritr )
{
_db.remove( _db.get_object(*ritr) );
}
for( auto& item : state.old_index_next_ids )
{
_db.get_mutable_index( item.first.space(), item.first.type() ).set_next_id( item.second );
}
for( auto& item : state.removed )
_db.insert( std::move(*item.second) );
_stack.pop_back();
}
catch ( const fc::exception& e )
{
elog( "error popping commit ${e}", ("e", e.to_detail_string() ) );
enable();
throw;
}
enable();
}
} } // bts::db
<commit_msg>undo_database: Assert when commit() has no matching start_undo_session()<commit_after>#include <bts/db/object_database.hpp>
#include <bts/db/undo_database.hpp>
#include <fc/reflect/variant.hpp>
namespace bts { namespace db {
void undo_database::enable() { _disabled = false; }
void undo_database::disable() { _disabled = true; }
undo_database::session undo_database::start_undo_session()
{
if( _disabled ) return session(*this);
if( size() == max_size() )
_stack.pop_front();
_stack.emplace_back();
++_active_sessions;
return session(*this);
}
void undo_database::on_create( const object& obj )
{
if( _disabled ) return;
if( _stack.empty() )
_stack.emplace_back();
auto& state = _stack.back();
auto index_id = object_id_type( obj.id.space(), obj.id.type(), 0 );
auto itr = state.old_index_next_ids.find( index_id );
if( itr == state.old_index_next_ids.end() )
state.old_index_next_ids[index_id] = obj.id;
state.new_ids.insert(obj.id);
}
void undo_database::on_modify( const object& obj )
{
if( _disabled ) return;
if( _stack.empty() )
_stack.emplace_back();
auto& state = _stack.back();
if( state.new_ids.find(obj.id) != state.new_ids.end() )
return;
auto itr = state.old_values.find(obj.id);
if( itr != state.old_values.end() ) return;
state.old_values[obj.id] = obj.clone();
}
void undo_database::on_remove( const object& obj )
{
if( _disabled ) return;
if( _stack.empty() )
_stack.emplace_back();
auto& state = _stack.back();
if( state.new_ids.find(obj.id) != state.new_ids.end() )
{
state.new_ids.erase(obj.id);
return;
}
auto itr = state.removed.find(obj.id);
if( itr != state.removed.end() ) return;
state.removed[obj.id] = obj.clone();
}
void undo_database::undo()
{ try {
FC_ASSERT( !_disabled );
FC_ASSERT( _active_sessions > 0 );
disable();
auto& state = _stack.back();
for( auto& item : state.old_values )
{
_db.modify( _db.get_object( item.second->id ), [&]( object& obj ){ obj.move_from( *item.second ); } );
}
for( auto ritr = state.new_ids.rbegin(); ritr != state.new_ids.rend(); ++ritr )
{
_db.remove( _db.get_object(*ritr) );
}
for( auto& item : state.old_index_next_ids )
{
_db.get_mutable_index( item.first.space(), item.first.type() ).set_next_id( item.second );
}
for( auto& item : state.removed )
_db.insert( std::move(*item.second) );
_stack.pop_back();
if( _stack.empty() )
_stack.emplace_back();
enable();
--_active_sessions;
} FC_CAPTURE_AND_RETHROW() }
void undo_database::merge()
{
FC_ASSERT( _active_sessions > 0 );
FC_ASSERT( _stack.size() >=2 );
auto& state = _stack.back();
auto& prev_state = _stack[_stack.size()-2];
for( auto& obj : state.old_values )
{
if( prev_state.new_ids.find(obj.second->id) != prev_state.new_ids.end() )
continue;
if( prev_state.old_values.find(obj.second->id) == prev_state.old_values.end() )
prev_state.old_values[obj.second->id] = std::move(obj.second);
}
for( auto id : state.new_ids )
prev_state.new_ids.insert(id);
for( auto& item : state.old_index_next_ids )
{
if( prev_state.old_index_next_ids.find( item.first ) == prev_state.old_index_next_ids.end() )
prev_state.old_index_next_ids[item.first] = item.second;
}
for( auto& obj : state.removed )
if( prev_state.new_ids.find(obj.second->id) == prev_state.new_ids.end() )
prev_state.removed[obj.second->id] = std::move(obj.second);
else
prev_state.new_ids.erase(obj.second->id);
_stack.pop_back();
--_active_sessions;
}
void undo_database::commit()
{
FC_ASSERT( _active_sessions > 0 );
--_active_sessions;
}
void undo_database::pop_commit()
{
FC_ASSERT( _active_sessions == 0 );
FC_ASSERT( !_stack.empty() );
disable();
try {
auto& state = _stack.back();
for( auto& item : state.old_values )
{
_db.modify( _db.get_object( item.second->id ), [&]( object& obj ){ obj.move_from( *item.second ); } );
}
for( auto ritr = state.new_ids.rbegin(); ritr != state.new_ids.rend(); ++ritr )
{
_db.remove( _db.get_object(*ritr) );
}
for( auto& item : state.old_index_next_ids )
{
_db.get_mutable_index( item.first.space(), item.first.type() ).set_next_id( item.second );
}
for( auto& item : state.removed )
_db.insert( std::move(*item.second) );
_stack.pop_back();
}
catch ( const fc::exception& e )
{
elog( "error popping commit ${e}", ("e", e.to_detail_string() ) );
enable();
throw;
}
enable();
}
} } // bts::db
<|endoftext|>
|
<commit_before>/*
ESP8266WebServer.cpp - Dead simple web-server.
Supports only one simultaneous client, knows how to handle GET and POST.
Copyright (c) 2014 Ivan Grokhotkov. 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Modified 8 May 2015 by Hristo Gochkov (proper post and file upload handling)
*/
#include <Arduino.h>
#include "WiFiServer.h"
#include "WiFiClient.h"
#include "ESP8266WebServer.h"
#include "FS.h"
#include "detail/RequestHandler.h"
// #define DEBUG
#define DEBUG_OUTPUT Serial
ESP8266WebServer::ESP8266WebServer(int port)
: _server(port)
, _firstHandler(0)
, _lastHandler(0)
, _currentArgCount(0)
, _currentArgs(0)
{
}
ESP8266WebServer::~ESP8266WebServer()
{
if (!_firstHandler)
return;
RequestHandler* handler = _firstHandler;
while (handler) {
RequestHandler* next = handler->next;
delete handler;
handler = next;
}
}
void ESP8266WebServer::begin() {
_server.begin();
}
void ESP8266WebServer::on(const char* uri, ESP8266WebServer::THandlerFunction handler)
{
on(uri, HTTP_ANY, handler);
}
void ESP8266WebServer::on(const char* uri, HTTPMethod method, ESP8266WebServer::THandlerFunction fn)
{
_addRequestHandler(new FunctionRequestHandler(fn, uri, method));
}
void ESP8266WebServer::_addRequestHandler(RequestHandler* handler) {
if (!_lastHandler) {
_firstHandler = handler;
_lastHandler = handler;
}
else {
_lastHandler->next = handler;
_lastHandler = handler;
}
}
void ESP8266WebServer::serveStatic(const char* uri, FS& fs, const char* path) {
_addRequestHandler(new StaticRequestHandler(fs, uri));
}
void ESP8266WebServer::handleClient()
{
WiFiClient client = _server.available();
if (!client) {
return;
}
#ifdef DEBUG
DEBUG_OUTPUT.println("New client");
#endif
// Wait for data from client to become available
uint16_t maxWait = HTTP_MAX_DATA_WAIT;
while(client.connected() && !client.available() && maxWait--){
delay(1);
}
if (!_parseRequest(client)) {
return;
}
_currentClient = client;
_contentLength = CONTENT_LENGTH_NOT_SET;
_handleRequest();
}
void ESP8266WebServer::sendHeader(const String& name, const String& value, bool first) {
String headerLine = name;
headerLine += ": ";
headerLine += value;
headerLine += "\r\n";
if (first) {
_responseHeaders = headerLine + _responseHeaders;
}
else {
_responseHeaders += headerLine;
}
}
void ESP8266WebServer::_prepareHeader(String& response, int code, const char* content_type, size_t contentLength) {
response = "HTTP/1.1 ";
response += String(code);
response += " ";
response += _responseCodeToString(code);
response += "\r\n";
if (!content_type)
content_type = "text/html";
sendHeader("Content-Type", content_type, true);
if (_contentLength != CONTENT_LENGTH_UNKNOWN && _contentLength != CONTENT_LENGTH_NOT_SET) {
sendHeader("Content-Length", String(_contentLength).c_str());
}
else if (contentLength > 0){
sendHeader("Content-Length", String(contentLength).c_str());
}
sendHeader("Connection", "close");
sendHeader("Access-Control-Allow-Origin", "*");
response += _responseHeaders;
response += "\r\n";
_responseHeaders = String();
}
void ESP8266WebServer::send(int code, const char* content_type, const String& content) {
String header;
_prepareHeader(header, code, content_type, content.length());
sendContent(header);
sendContent(content);
}
void ESP8266WebServer::send_P(int code, PGM_P content_type, PGM_P content) {
size_t contentLength = 0;
if (content != NULL) {
contentLength = strlen_P(content);
}
String header;
_prepareHeader(header, code, String(FPSTR(content_type)).c_str(), contentLength);
sendContent(header);
sendContent_P(content);
}
void ESP8266WebServer::send(int code, char* content_type, const String& content) {
send(code, (const char*)content_type, content);
}
void ESP8266WebServer::send(int code, const String& content_type, const String& content) {
send(code, (const char*)content_type.c_str(), content);
}
void ESP8266WebServer::sendContent(const String& content) {
const size_t unit_size = HTTP_DOWNLOAD_UNIT_SIZE;
size_t size_to_send = content.length();
const char* send_start = content.c_str();
while (size_to_send) {
size_t will_send = (size_to_send < unit_size) ? size_to_send : unit_size;
size_t sent = _currentClient.write(send_start, will_send);
if (sent == 0) {
break;
}
size_to_send -= sent;
send_start += sent;
}
}
void ESP8266WebServer::sendContent_P(PGM_P content) {
char contentUnit[HTTP_DOWNLOAD_UNIT_SIZE + 1];
contentUnit[HTTP_DOWNLOAD_UNIT_SIZE] = '\0';
while (content != NULL) {
size_t contentUnitLen;
PGM_P contentNext;
// due to the memccpy signature, lots of casts are needed
contentNext = (PGM_P)memccpy_P((void*)contentUnit, (PGM_VOID_P)content, 0, HTTP_DOWNLOAD_UNIT_SIZE);
if (contentNext == NULL) {
// no terminator, more data available
content += HTTP_DOWNLOAD_UNIT_SIZE;
contentUnitLen = HTTP_DOWNLOAD_UNIT_SIZE;
}
else {
// reached terminator
contentUnitLen = contentNext - content;
content = NULL;
}
// write is so overloaded, had to use the cast to get it pick the right one
_currentClient.write((const char*)contentUnit, contentUnitLen);
}
}
void ESP8266WebServer::sendContent_P(PGM_P content, size_t size) {
char contentUnit[HTTP_DOWNLOAD_UNIT_SIZE + 1];
contentUnit[HTTP_DOWNLOAD_UNIT_SIZE] = '\0';
while (content != NULL) {
size_t contentUnitLen;
PGM_P contentNext;
// due to the memcpy signature, lots of casts are needed
contentNext = (PGM_P)memcpy_P((void*)contentUnit, (PGM_VOID_P)content, HTTP_DOWNLOAD_UNIT_SIZE);
if (contentNext == NULL) {
// no terminator, more data available
content += HTTP_DOWNLOAD_UNIT_SIZE;
contentUnitLen = HTTP_DOWNLOAD_UNIT_SIZE;
}
else {
// reached terminator
contentUnitLen = contentNext - content;
content = NULL;
}
if (size < WIFICLIENT_MAX_PACKET_SIZE) contentUnitLen = size;
// write is so overloaded, had to use the cast to get it pick the right one
_currentClient.write((const char*)contentUnit, contentUnitLen);
}
}
String ESP8266WebServer::arg(const char* name) {
for (int i = 0; i < _currentArgCount; ++i) {
if (_currentArgs[i].key == name)
return _currentArgs[i].value;
}
return String();
}
String ESP8266WebServer::arg(int i) {
if (i < _currentArgCount)
return _currentArgs[i].value;
return String();
}
String ESP8266WebServer::argName(int i) {
if (i < _currentArgCount)
return _currentArgs[i].key;
return String();
}
int ESP8266WebServer::args() {
return _currentArgCount;
}
bool ESP8266WebServer::hasArg(const char* name) {
for (int i = 0; i < _currentArgCount; ++i) {
if (_currentArgs[i].key == name)
return true;
}
return false;
}
String ESP8266WebServer::hostHeader() {
return _hostHeader;
}
void ESP8266WebServer::onFileUpload(THandlerFunction fn) {
_fileUploadHandler = fn;
}
void ESP8266WebServer::onNotFound(THandlerFunction fn) {
_notFoundHandler = fn;
}
void ESP8266WebServer::_handleRequest() {
RequestHandler* handler;
for (handler = _firstHandler; handler; handler = handler->next) {
if (handler->handle(*this, _currentMethod, _currentUri))
break;
}
if (!handler){
#ifdef DEBUG
DEBUG_OUTPUT.println("request handler not found");
#endif
if(_notFoundHandler) {
_notFoundHandler();
}
else {
send(404, "text/plain", String("Not found: ") + _currentUri);
}
}
uint16_t maxWait = HTTP_MAX_CLOSE_WAIT;
while(_currentClient.connected() && maxWait--) {
delay(1);
}
_currentClient = WiFiClient();
_currentUri = String();
}
const char* ESP8266WebServer::_responseCodeToString(int code) {
switch (code) {
case 101: return "Switching Protocols";
case 200: return "OK";
case 403: return "Forbidden";
case 404: return "Not found";
case 500: return "Fail";
default: return "";
}
}
<commit_msg>fix bug in WiFiClient::write_P/ESP8266WebServer::sendContent_P introduced few minutes ago when changing memccpy_P to memcpy_P<commit_after>/*
ESP8266WebServer.cpp - Dead simple web-server.
Supports only one simultaneous client, knows how to handle GET and POST.
Copyright (c) 2014 Ivan Grokhotkov. 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Modified 8 May 2015 by Hristo Gochkov (proper post and file upload handling)
*/
#include <Arduino.h>
#include "WiFiServer.h"
#include "WiFiClient.h"
#include "ESP8266WebServer.h"
#include "FS.h"
#include "detail/RequestHandler.h"
// #define DEBUG
#define DEBUG_OUTPUT Serial
ESP8266WebServer::ESP8266WebServer(int port)
: _server(port)
, _firstHandler(0)
, _lastHandler(0)
, _currentArgCount(0)
, _currentArgs(0)
{
}
ESP8266WebServer::~ESP8266WebServer()
{
if (!_firstHandler)
return;
RequestHandler* handler = _firstHandler;
while (handler) {
RequestHandler* next = handler->next;
delete handler;
handler = next;
}
}
void ESP8266WebServer::begin() {
_server.begin();
}
void ESP8266WebServer::on(const char* uri, ESP8266WebServer::THandlerFunction handler)
{
on(uri, HTTP_ANY, handler);
}
void ESP8266WebServer::on(const char* uri, HTTPMethod method, ESP8266WebServer::THandlerFunction fn)
{
_addRequestHandler(new FunctionRequestHandler(fn, uri, method));
}
void ESP8266WebServer::_addRequestHandler(RequestHandler* handler) {
if (!_lastHandler) {
_firstHandler = handler;
_lastHandler = handler;
}
else {
_lastHandler->next = handler;
_lastHandler = handler;
}
}
void ESP8266WebServer::serveStatic(const char* uri, FS& fs, const char* path) {
_addRequestHandler(new StaticRequestHandler(fs, uri));
}
void ESP8266WebServer::handleClient()
{
WiFiClient client = _server.available();
if (!client) {
return;
}
#ifdef DEBUG
DEBUG_OUTPUT.println("New client");
#endif
// Wait for data from client to become available
uint16_t maxWait = HTTP_MAX_DATA_WAIT;
while(client.connected() && !client.available() && maxWait--){
delay(1);
}
if (!_parseRequest(client)) {
return;
}
_currentClient = client;
_contentLength = CONTENT_LENGTH_NOT_SET;
_handleRequest();
}
void ESP8266WebServer::sendHeader(const String& name, const String& value, bool first) {
String headerLine = name;
headerLine += ": ";
headerLine += value;
headerLine += "\r\n";
if (first) {
_responseHeaders = headerLine + _responseHeaders;
}
else {
_responseHeaders += headerLine;
}
}
void ESP8266WebServer::_prepareHeader(String& response, int code, const char* content_type, size_t contentLength) {
response = "HTTP/1.1 ";
response += String(code);
response += " ";
response += _responseCodeToString(code);
response += "\r\n";
if (!content_type)
content_type = "text/html";
sendHeader("Content-Type", content_type, true);
if (_contentLength != CONTENT_LENGTH_UNKNOWN && _contentLength != CONTENT_LENGTH_NOT_SET) {
sendHeader("Content-Length", String(_contentLength).c_str());
}
else if (contentLength > 0){
sendHeader("Content-Length", String(contentLength).c_str());
}
sendHeader("Connection", "close");
sendHeader("Access-Control-Allow-Origin", "*");
response += _responseHeaders;
response += "\r\n";
_responseHeaders = String();
}
void ESP8266WebServer::send(int code, const char* content_type, const String& content) {
String header;
_prepareHeader(header, code, content_type, content.length());
sendContent(header);
sendContent(content);
}
void ESP8266WebServer::send_P(int code, PGM_P content_type, PGM_P content) {
size_t contentLength = 0;
if (content != NULL) {
contentLength = strlen_P(content);
}
String header;
_prepareHeader(header, code, String(FPSTR(content_type)).c_str(), contentLength);
sendContent(header);
sendContent_P(content);
}
void ESP8266WebServer::send(int code, char* content_type, const String& content) {
send(code, (const char*)content_type, content);
}
void ESP8266WebServer::send(int code, const String& content_type, const String& content) {
send(code, (const char*)content_type.c_str(), content);
}
void ESP8266WebServer::sendContent(const String& content) {
const size_t unit_size = HTTP_DOWNLOAD_UNIT_SIZE;
size_t size_to_send = content.length();
const char* send_start = content.c_str();
while (size_to_send) {
size_t will_send = (size_to_send < unit_size) ? size_to_send : unit_size;
size_t sent = _currentClient.write(send_start, will_send);
if (sent == 0) {
break;
}
size_to_send -= sent;
send_start += sent;
}
}
void ESP8266WebServer::sendContent_P(PGM_P content) {
char contentUnit[HTTP_DOWNLOAD_UNIT_SIZE + 1];
contentUnit[HTTP_DOWNLOAD_UNIT_SIZE] = '\0';
while (content != NULL) {
size_t contentUnitLen;
PGM_P contentNext;
// due to the memccpy signature, lots of casts are needed
contentNext = (PGM_P)memccpy_P((void*)contentUnit, (PGM_VOID_P)content, 0, HTTP_DOWNLOAD_UNIT_SIZE);
if (contentNext == NULL) {
// no terminator, more data available
content += HTTP_DOWNLOAD_UNIT_SIZE;
contentUnitLen = HTTP_DOWNLOAD_UNIT_SIZE;
}
else {
// reached terminator
contentUnitLen = contentNext - content;
content = NULL;
}
// write is so overloaded, had to use the cast to get it pick the right one
_currentClient.write((const char*)contentUnit, contentUnitLen);
}
}
void ESP8266WebServer::sendContent_P(PGM_P content, size_t size) {
char contentUnit[HTTP_DOWNLOAD_UNIT_SIZE + 1];
contentUnit[HTTP_DOWNLOAD_UNIT_SIZE] = '\0';
size_t remaining_size = size;
while (content != NULL && remaining_size > 0) {
size_t contentUnitLen = HTTP_DOWNLOAD_UNIT_SIZE;
if (remaining_size < HTTP_DOWNLOAD_UNIT_SIZE) contentUnitLen = remaining_size;
// due to the memcpy signature, lots of casts are needed
memcpy_P((void*)contentUnit, (PGM_VOID_P)content, contentUnitLen);
content += contentUnitLen;
remaining_size -= contentUnitLen;
// write is so overloaded, had to use the cast to get it pick the right one
_currentClient.write((const char*)contentUnit, contentUnitLen);
}
}
String ESP8266WebServer::arg(const char* name) {
for (int i = 0; i < _currentArgCount; ++i) {
if (_currentArgs[i].key == name)
return _currentArgs[i].value;
}
return String();
}
String ESP8266WebServer::arg(int i) {
if (i < _currentArgCount)
return _currentArgs[i].value;
return String();
}
String ESP8266WebServer::argName(int i) {
if (i < _currentArgCount)
return _currentArgs[i].key;
return String();
}
int ESP8266WebServer::args() {
return _currentArgCount;
}
bool ESP8266WebServer::hasArg(const char* name) {
for (int i = 0; i < _currentArgCount; ++i) {
if (_currentArgs[i].key == name)
return true;
}
return false;
}
String ESP8266WebServer::hostHeader() {
return _hostHeader;
}
void ESP8266WebServer::onFileUpload(THandlerFunction fn) {
_fileUploadHandler = fn;
}
void ESP8266WebServer::onNotFound(THandlerFunction fn) {
_notFoundHandler = fn;
}
void ESP8266WebServer::_handleRequest() {
RequestHandler* handler;
for (handler = _firstHandler; handler; handler = handler->next) {
if (handler->handle(*this, _currentMethod, _currentUri))
break;
}
if (!handler){
#ifdef DEBUG
DEBUG_OUTPUT.println("request handler not found");
#endif
if(_notFoundHandler) {
_notFoundHandler();
}
else {
send(404, "text/plain", String("Not found: ") + _currentUri);
}
}
uint16_t maxWait = HTTP_MAX_CLOSE_WAIT;
while(_currentClient.connected() && maxWait--) {
delay(1);
}
_currentClient = WiFiClient();
_currentUri = String();
}
const char* ESP8266WebServer::_responseCodeToString(int code) {
switch (code) {
case 101: return "Switching Protocols";
case 200: return "OK";
case 403: return "Forbidden";
case 404: return "Not found";
case 500: return "Fail";
default: return "";
}
}
<|endoftext|>
|
<commit_before>/**
* Throughout these tests, you might see some notation indicating the state of
* a placement allocator. General things to know:
*
* - R = active region structure in memory
* - S = inactive region structure in the stack
* - space = a free piece of memory
*
* I denote disjoint regions using brackets ([ and ]). I separate cells of
* memory using vertical bars (|).
*/
#include "scoped-pass.hpp"
#include <analloc2/free-list>
using namespace analloc;
using namespace ansa;
template <size_t Capacity>
void TestAll();
template <size_t Capacity>
void TestSimplePlace();
template <size_t Capacity>
void TestOffsetPlace();
template <size_t Capacity>
void TestNormalAllocOverflow();
template <size_t Capacity>
void TestDoubleAllocOverflow();
template <size_t Capacity>
size_t ComputePreambleSize();
template <size_t Capacity>
size_t ComputeRegionSize();
int main() {
TestAll<3>();
TestAll<4>();
TestAll<5>();
TestAll<6>();
TestAll<0x10>();
return 0;
}
template <size_t Capacity>
void TestAll() {
TestSimplePlace<Capacity>();
TestOffsetPlace<Capacity>();
TestNormalAllocOverflow<Capacity>();
TestDoubleAllocOverflow<Capacity>();
}
template <size_t Capacity>
void TestSimplePlace() {
ScopedPass pass("PlacedFreeList<", Capacity, ">::Place() [simple]");
typedef PlacedFreeList<Capacity> Pfl;
size_t regionSize = ComputeRegionSize<Capacity>();
size_t preamble = ComputePreambleSize<Capacity>();
// Create a buffer that gives everything the proper alignment.
void * buffer;
assert(!posix_memalign(&buffer, regionSize, preamble + regionSize * 3));
uintptr_t start = (uintptr_t)buffer;
uintptr_t addr;
assert(!Pfl::Place(start, preamble));
assert(!Pfl::Place(start, preamble + regionSize - 1));
Pfl * pfl = Pfl::Place(start, preamble + regionSize);
assert(!pfl->Alloc(addr, 1));
assert(!pfl->Alloc(addr, 0));
pfl = Pfl::Place(start, preamble + regionSize * 2);
assert(!pfl->Alloc(addr, 1));
assert(!pfl->Alloc(addr, 0));
pfl = Pfl::Place(start, preamble + regionSize * 3);
assert(!pfl->Alloc(addr, regionSize + 1));
assert(pfl->Alloc(addr, regionSize));
assert(addr == start + preamble + regionSize * 2);
assert(!pfl->Alloc(addr, 1));
free(buffer);
}
template <size_t Capacity>
void TestOffsetPlace() {
ScopedPass pass("PlacedFreeList<", Capacity, ">::Place() [offset]");
typedef PlacedFreeList<Capacity> Pfl;
size_t objectAlign = sizeof(void *);
size_t regionSize = (size_t)1 << Log2Ceil(sizeof(typename Pfl::FreeRegion));
regionSize = Align2(regionSize, objectAlign);
size_t instanceSize = Align2(sizeof(Pfl), objectAlign);
size_t stackSize = Align2(sizeof(typename Pfl::StackType), objectAlign);
size_t preamble = instanceSize + stackSize;
size_t misalignment = (preamble + objectAlign) % regionSize;
if (misalignment) {
preamble += regionSize - misalignment;
}
// Create a buffer that gives everything the proper alignment.
void * buffer;
assert(!posix_memalign(&buffer, regionSize, objectAlign + preamble +
regionSize * 3));
uintptr_t start = (uintptr_t)buffer + objectAlign;
uintptr_t addr;
assert(!Pfl::Place(start, preamble));
assert(!Pfl::Place(start, preamble + regionSize - 1));
Pfl * pfl = Pfl::Place(start, preamble + regionSize);
assert(!pfl->Alloc(addr, 1));
assert(!pfl->Alloc(addr, 0));
pfl = Pfl::Place(start, preamble + regionSize * 2);
assert(!pfl->Alloc(addr, 1));
assert(!pfl->Alloc(addr, 0));
pfl = Pfl::Place(start, preamble + regionSize * 3);
assert(!pfl->Alloc(addr, regionSize + 1));
assert(pfl->Alloc(addr, regionSize));
assert(addr == start + preamble + regionSize * 2);
assert(!pfl->Alloc(addr, 1));
free(buffer);
}
template <size_t Capacity>
void TestNormalAllocOverflow() {
}
template <size_t Capacity>
void TestDoubleAllocOverflow() {
ScopedPass pass("PlacedFreeList<", Capacity, ">::Alloc() [double overflow]");
typedef PlacedFreeList<Capacity> Pfl;
uintptr_t addr;
size_t preambleSize = ComputePreambleSize<Capacity>();
size_t regionSize = ComputeRegionSize<Capacity>();
// Let R=regionSize, N=Capacity
// We will have:
// - one region of size R*(N+2)
// - N-1 regions of size R*(N+3)
// - Every region will be separated by R bytes
// Total size needed = R*(N+2) + (N-1)*R*(N+3) + R*N
size_t headingSize = regionSize * (Capacity + 2);
size_t blockSize = regionSize * (Capacity + 3);
size_t totalSize = headingSize + blockSize * (Capacity - 1) +
regionSize * Capacity;
void * buffer;
assert(!posix_memalign(&buffer, regionSize, totalSize));
uintptr_t start = (uintptr_t)buffer;
Pfl * pfl = Pfl::Place(start, regionSize * (Capacity + 1));
assert(pfl->GetStackCount() == 1);
// Currently, the allocator looks like this: [S|R| |...]
// Add a bunch of blocks
for (size_t i = 1; i < Capacity; ++i) {
size_t offset = headingSize + i * regionSize + (i - 1) * blockSize;
pfl->Dealloc(start + offset, blockSize);
assert(pfl->GetStackCount() == 1);
}
// Currently, the allocator looks like this:
// [R|R|...|S| ] [ |...] ... [ |...]
// Each time we Alloc() another block, it moves a region structure to the
// stack as follows:
// [S|R|...|S| ]
// [S|R|S|R...|S| ]
// [S|R|S|S|R...|S| ]
// Thus, after Capacity - 2 Alloc()s, the stack will contain Capacity - 1
// items:
// [S|R|S|S|S|...|R|S| ]
for (size_t i = Capacity - 1; i > 1; --i) {
size_t offset = headingSize + i * regionSize + (i - 1) * blockSize;
assert(pfl->Alloc(addr, blockSize));
assert(addr == start + offset);
size_t stackCount = 1 + (Capacity - i);
assert(pfl->GetStackCount() == stackCount);
}
// When we allocate the next block, the heading will at first look like this:
// [S|R|S|S|...|S|S|S| ]
// To address this, the stack will remove the last element from the stack:
// [S|R|S|S|...|S|X|S| ]
// Then, it will need a new region, so it will remove the next element from
// the stack as well:
// [S|R|S|S|...|R| |S| ]
assert(pfl->Alloc(addr, regionSize));
assert(addr == start + headingSize + regionSize);
assert(pfl->GetStackCount() == Capacity - 2);
// The first free region is now located near the end of the heading.
uintptr_t addr;
assert(pfl->Alloc(addr, regionSize));
assert(addr == start + headingSize - (regionSize * 3));
}
template <size_t Capacity>
size_t ComputePreambleSize() {
typedef PlacedFreeList<Capacity> Pfl;
size_t objectAlign = sizeof(void *);
size_t regionSize = ComputeRegionSize<Capacity>();
size_t instanceSize = Align2(sizeof(Pfl), objectAlign);
size_t stackSize = Align2(sizeof(typename Pfl::StackType), objectAlign);
return Align2(instanceSize + stackSize, regionSize);
}
template <size_t Capacity>
size_t ComputeRegionSize() {
typedef PlacedFreeList<Capacity> Pfl;
size_t objectAlign = sizeof(void *);
size_t regionSize = (size_t)1 << Log2Ceil(sizeof(typename Pfl::FreeRegion));
return Align2(regionSize, objectAlign);
}
<commit_msg>double overflow test passes<commit_after>/**
* Throughout these tests, you might see some notation indicating the state of
* a placement allocator. General things to know:
*
* - R = active region structure in memory
* - S = inactive region structure in the stack
* - space = a free piece of memory
*
* I denote disjoint regions using brackets ([ and ]). I separate cells of
* memory using vertical bars (|).
*/
#include "scoped-pass.hpp"
#include <analloc2/free-list>
using namespace analloc;
using namespace ansa;
template <size_t Capacity>
void TestAll();
template <size_t Capacity>
void TestSimplePlace();
template <size_t Capacity>
void TestOffsetPlace();
template <size_t Capacity>
void TestNormalAllocOverflow();
template <size_t Capacity>
void TestDoubleAllocOverflow();
template <size_t Capacity>
size_t ComputePreambleSize();
template <size_t Capacity>
size_t ComputeRegionSize();
int main() {
TestAll<3>();
TestAll<4>();
TestAll<5>();
TestAll<6>();
TestAll<0x10>();
return 0;
}
template <size_t Capacity>
void TestAll() {
TestSimplePlace<Capacity>();
TestOffsetPlace<Capacity>();
TestNormalAllocOverflow<Capacity>();
TestDoubleAllocOverflow<Capacity>();
}
template <size_t Capacity>
void TestSimplePlace() {
ScopedPass pass("PlacedFreeList<", Capacity, ">::Place() [simple]");
typedef PlacedFreeList<Capacity> Pfl;
size_t regionSize = ComputeRegionSize<Capacity>();
size_t preamble = ComputePreambleSize<Capacity>();
// Create a buffer that gives everything the proper alignment.
void * buffer;
assert(!posix_memalign(&buffer, regionSize, preamble + regionSize * 3));
uintptr_t start = (uintptr_t)buffer;
uintptr_t addr;
assert(!Pfl::Place(start, preamble));
assert(!Pfl::Place(start, preamble + regionSize - 1));
Pfl * pfl = Pfl::Place(start, preamble + regionSize);
assert(!pfl->Alloc(addr, 1));
assert(!pfl->Alloc(addr, 0));
pfl = Pfl::Place(start, preamble + regionSize * 2);
assert(!pfl->Alloc(addr, 1));
assert(!pfl->Alloc(addr, 0));
pfl = Pfl::Place(start, preamble + regionSize * 3);
assert(!pfl->Alloc(addr, regionSize + 1));
assert(pfl->Alloc(addr, regionSize));
assert(addr == start + preamble + regionSize * 2);
assert(!pfl->Alloc(addr, 1));
free(buffer);
}
template <size_t Capacity>
void TestOffsetPlace() {
ScopedPass pass("PlacedFreeList<", Capacity, ">::Place() [offset]");
typedef PlacedFreeList<Capacity> Pfl;
size_t objectAlign = sizeof(void *);
size_t regionSize = (size_t)1 << Log2Ceil(sizeof(typename Pfl::FreeRegion));
regionSize = Align2(regionSize, objectAlign);
size_t instanceSize = Align2(sizeof(Pfl), objectAlign);
size_t stackSize = Align2(sizeof(typename Pfl::StackType), objectAlign);
size_t preamble = instanceSize + stackSize;
size_t misalignment = (preamble + objectAlign) % regionSize;
if (misalignment) {
preamble += regionSize - misalignment;
}
// Create a buffer that gives everything the proper alignment.
void * buffer;
assert(!posix_memalign(&buffer, regionSize, objectAlign + preamble +
regionSize * 3));
uintptr_t start = (uintptr_t)buffer + objectAlign;
uintptr_t addr;
assert(!Pfl::Place(start, preamble));
assert(!Pfl::Place(start, preamble + regionSize - 1));
Pfl * pfl = Pfl::Place(start, preamble + regionSize);
assert(!pfl->Alloc(addr, 1));
assert(!pfl->Alloc(addr, 0));
pfl = Pfl::Place(start, preamble + regionSize * 2);
assert(!pfl->Alloc(addr, 1));
assert(!pfl->Alloc(addr, 0));
pfl = Pfl::Place(start, preamble + regionSize * 3);
assert(!pfl->Alloc(addr, regionSize + 1));
assert(pfl->Alloc(addr, regionSize));
assert(addr == start + preamble + regionSize * 2);
assert(!pfl->Alloc(addr, 1));
free(buffer);
}
template <size_t Capacity>
void TestNormalAllocOverflow() {
}
template <size_t Capacity>
void TestDoubleAllocOverflow() {
// NOTE: most of the visual examples in this test make use of a large
// Capacity to give a good depiction of what's going on. This test works for
// Capacity >= 3, but the visual examples don't.
ScopedPass pass("PlacedFreeList<", Capacity, ">::Alloc() [double overflow]");
typedef PlacedFreeList<Capacity> Pfl;
uintptr_t addr;
size_t preambleSize = ComputePreambleSize<Capacity>();
size_t regionSize = ComputeRegionSize<Capacity>();
// Let R=regionSize, N=Capacity
// We will have:
// - one region of size R*(N+2)
// - N-1 regions of size R*(N+3)
// - Every region will be separated by R bytes
// Total size needed = R*(N+2) + (N-1)*R*(N+3) + R*(N - 1)
size_t headingSize = regionSize * (Capacity + 2);
size_t blockSize = regionSize * (Capacity + 3);
size_t totalSize = preambleSize + headingSize + blockSize * (Capacity - 1) +
regionSize * (Capacity - 1);
void * buffer;
assert(!posix_memalign(&buffer, regionSize, totalSize));
Pfl * pfl = Pfl::Place((uintptr_t)buffer, preambleSize + headingSize);
assert(pfl != nullptr);
assert(pfl->GetStackCount() == 1);
uintptr_t start = (uintptr_t)buffer + preambleSize;
// Currently, the allocator looks like this: [S|R| |...]
// Add a bunch of blocks
for (size_t i = 1; i < Capacity; ++i) {
size_t offset = headingSize + i * regionSize + (i - 1) * blockSize;
pfl->Dealloc(start + offset, blockSize);
assert(pfl->GetStackCount() == 1);
}
// Currently, the allocator looks like this:
// [R|R|...|S| ] [ |...] ... [ |...]
// Each time we Alloc() another block, it moves a region structure to the
// stack as follows:
// [S|R|...|S| ]
// [S|R|S|R...|S| ]
// [S|R|S|S|R...|S| ]
// Thus, after Capacity - 2 Alloc()s, the stack will contain Capacity - 1
// items:
// [S|R|S|S|S|...|R|S| ]
for (size_t i = 1; i < Capacity - 1; ++i) {
assert(pfl->GetStackCount() == i);
size_t offset = headingSize + i * regionSize + (i - 1) * blockSize;
assert(pfl->Alloc(addr, blockSize));
assert(addr == start + offset);
assert(pfl->GetStackCount() == i + 1);
}
// When we allocate the next block, the heading will at first look like this:
// [S|R|S|S|...|S|S|S| ]
// To address this, the stack will remove the last element from the stack:
// [S|R|S|S|...|S|X|S| ]
// Then, it will need a new region, so it will remove the next element from
// the stack as well:
// [S|R|S|S|...|R| |S| ]
assert(pfl->Alloc(addr, blockSize));
assert(addr == start + headingSize + regionSize * (Capacity - 1) +
blockSize * (Capacity - 2));
assert(pfl->GetStackCount() == Capacity - 2);
// The first free region is now located near the end of the heading.
assert(pfl->Alloc(addr, regionSize));
assert(addr == start + headingSize - (regionSize * 3));
}
template <size_t Capacity>
size_t ComputePreambleSize() {
typedef PlacedFreeList<Capacity> Pfl;
size_t objectAlign = sizeof(void *);
size_t regionSize = ComputeRegionSize<Capacity>();
size_t instanceSize = Align2(sizeof(Pfl), objectAlign);
size_t stackSize = Align2(sizeof(typename Pfl::StackType), objectAlign);
return Align2(instanceSize + stackSize, regionSize);
}
template <size_t Capacity>
size_t ComputeRegionSize() {
typedef PlacedFreeList<Capacity> Pfl;
size_t objectAlign = sizeof(void *);
size_t regionSize = (size_t)1 << Log2Ceil(sizeof(typename Pfl::FreeRegion));
return Align2(regionSize, objectAlign);
}
<|endoftext|>
|
<commit_before>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/prediction/predictor/sequence/sequence_predictor.h"
#include <cmath>
#include <limits>
#include <memory>
#include <utility>
#include "modules/common/adapters/proto/adapter_config.pb.h"
#include "modules/common/math/vec2d.h"
#include "modules/prediction/common/prediction_gflags.h"
#include "modules/prediction/common/prediction_map.h"
#include "modules/prediction/common/road_graph.h"
#include "modules/prediction/container/adc_trajectory/adc_trajectory_container.h"
#include "modules/prediction/container/container_manager.h"
#include "modules/prediction/container/pose/pose_container.h"
namespace apollo {
namespace prediction {
using ::apollo::common::PathPoint;
using ::apollo::common::TrajectoryPoint;
using ::apollo::common::adapter::AdapterConfig;
using ::apollo::common::math::Vec2d;
using ::apollo::hdmap::LaneInfo;
void SequencePredictor::Predict(Obstacle* obstacle) {
Clear();
CHECK_NOTNULL(obstacle);
CHECK_GT(obstacle->history_size(), 0);
}
void SequencePredictor::Clear() { Predictor::Clear(); }
std::string SequencePredictor::ToString(const LaneSequence& sequence) {
std::string str_lane_sequence = "";
if (sequence.lane_segment_size() > 0) {
str_lane_sequence += sequence.lane_segment(0).lane_id();
}
for (int i = 1; i < sequence.lane_segment_size(); ++i) {
str_lane_sequence += ("->" + sequence.lane_segment(i).lane_id());
}
return str_lane_sequence;
}
void SequencePredictor::FilterLaneSequences(
const Feature& feature, const std::string& lane_id,
std::vector<bool>* enable_lane_sequence) {
if (!feature.has_lane() || !feature.lane().has_lane_graph()) {
return;
}
const LaneGraph& lane_graph = feature.lane().lane_graph();
int num_lane_sequence = lane_graph.lane_sequence_size();
std::vector<LaneChangeType> lane_change_type(num_lane_sequence,
LaneChangeType::INVALID);
std::pair<int, double> change(-1, -1.0);
std::pair<int, double> all(-1, -1.0);
for (int i = 0; i < num_lane_sequence; ++i) {
const LaneSequence& sequence = lane_graph.lane_sequence(i);
lane_change_type[i] = GetLaneChangeType(lane_id, sequence);
if (lane_change_type[i] != LaneChangeType::LEFT &&
lane_change_type[i] != LaneChangeType::RIGHT &&
lane_change_type[i] != LaneChangeType::ONTO_LANE) {
ADEBUG "Ignore lane sequence [" << ToString(sequence) << "].";
continue;
}
// The obstacle has interference with ADC within a small distance
double distance = GetLaneChangeDistanceWithADC(sequence);
ADEBUG << "Distance to ADC " << std::fixed << std::setprecision(6)
<< distance;
if (distance > 0.0 && distance < FLAGS_lane_change_dist) {
(*enable_lane_sequence)[i] = false;
ADEBUG << "Filter trajectory [" << ToString(sequence)
<< "] due to small distance " << distance << ".";
}
}
for (int i = 0; i < num_lane_sequence; ++i) {
const LaneSequence& sequence = lane_graph.lane_sequence(i);
if (!(*enable_lane_sequence)[i]) {
ADEBUG << "Disabled lane sequence [" << ToString(sequence) << "].";
continue;
}
double probability = sequence.probability();
if (LaneSequenceWithMaxProb(lane_change_type[i], probability, all.second)) {
all.first = i;
all.second = probability;
}
if (LaneChangeWithMaxProb(lane_change_type[i], probability,
change.second)) {
change.first = i;
change.second = probability;
}
}
for (int i = 0; i < num_lane_sequence; ++i) {
const LaneSequence& sequence = lane_graph.lane_sequence(i);
if (!(*enable_lane_sequence)[i]) {
ADEBUG << "Disabled lane sequence [" << ToString(sequence) << "].";
continue;
}
double probability = sequence.probability();
if (probability < FLAGS_lane_sequence_threshold && i != all.first) {
(*enable_lane_sequence)[i] = false;
} else if (change.first >= 0 && change.first < num_lane_sequence &&
(lane_change_type[i] == LaneChangeType::LEFT ||
lane_change_type[i] == LaneChangeType::RIGHT) &&
lane_change_type[i] != lane_change_type[change.first]) {
(*enable_lane_sequence)[i] = false;
}
}
}
SequencePredictor::LaneChangeType SequencePredictor::GetLaneChangeType(
const std::string& lane_id, const LaneSequence& lane_sequence) {
if (lane_id.empty()) {
return LaneChangeType::ONTO_LANE;
}
std::string lane_change_id = lane_sequence.lane_segment(0).lane_id();
if (lane_id == lane_change_id) {
return LaneChangeType::STRAIGHT;
} else {
if (PredictionMap::IsLeftNeighborLane(
PredictionMap::LaneById(lane_change_id),
PredictionMap::LaneById(lane_id))) {
return LaneChangeType::LEFT;
} else if (PredictionMap::IsRightNeighborLane(
PredictionMap::LaneById(lane_change_id),
PredictionMap::LaneById(lane_id))) {
return LaneChangeType::RIGHT;
}
}
return LaneChangeType::INVALID;
}
double SequencePredictor::GetLaneChangeDistanceWithADC(
const LaneSequence& lane_sequence) {
PoseContainer* pose_container = dynamic_cast<PoseContainer*>(
ContainerManager::Instance()->GetContainer(AdapterConfig::LOCALIZATION));
ADCTrajectoryContainer* adc_container = dynamic_cast<ADCTrajectoryContainer*>(
ContainerManager::Instance()->GetContainer(
AdapterConfig::PLANNING_TRAJECTORY));
CHECK_NOTNULL(pose_container);
CHECK_NOTNULL(adc_container);
if (!adc_container->HasOverlap(lane_sequence)) {
ADEBUG << "The sequence [" << ToString(lane_sequence)
<< "] has no overlap with ADC.";
return std::numeric_limits<double>::max();
}
Eigen::Vector2d adc_position;
if (pose_container->ToPerceptionObstacle() != nullptr) {
adc_position[0] = pose_container->ToPerceptionObstacle()->position().x();
adc_position[1] = pose_container->ToPerceptionObstacle()->position().y();
std::string obstacle_lane_id = lane_sequence.lane_segment(0).lane_id();
double obstacle_lane_s = lane_sequence.lane_segment(0).start_s();
double lane_s = 0.0;
double lane_l = 0.0;
if (PredictionMap::GetProjection(adc_position,
PredictionMap::LaneById(obstacle_lane_id),
&lane_s, &lane_l)) {
ADEBUG << "Distance with ADC is " << std::fabs(lane_s - obstacle_lane_s);
return obstacle_lane_s - lane_s;
}
}
ADEBUG << "Invalid ADC pose.";
return std::numeric_limits<double>::max();
}
bool SequencePredictor::LaneSequenceWithMaxProb(const LaneChangeType& type,
const double probability,
const double max_prob) {
if (probability > max_prob) {
return true;
} else {
double prob_diff = std::fabs(probability - max_prob);
if (prob_diff <= std::numeric_limits<double>::epsilon() &&
type == LaneChangeType::STRAIGHT) {
return true;
}
}
return false;
}
bool SequencePredictor::LaneChangeWithMaxProb(const LaneChangeType& type,
const double probability,
const double max_prob) {
if (type == LaneChangeType::LEFT || type == LaneChangeType::RIGHT) {
if (probability > max_prob) {
return true;
}
}
return false;
}
} // namespace prediction
} // namespace apollo
<commit_msg>Prediction: added some comments for better understanding.<commit_after>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/prediction/predictor/sequence/sequence_predictor.h"
#include <cmath>
#include <limits>
#include <memory>
#include <utility>
#include "modules/common/adapters/proto/adapter_config.pb.h"
#include "modules/common/math/vec2d.h"
#include "modules/prediction/common/prediction_gflags.h"
#include "modules/prediction/common/prediction_map.h"
#include "modules/prediction/common/road_graph.h"
#include "modules/prediction/container/adc_trajectory/adc_trajectory_container.h"
#include "modules/prediction/container/container_manager.h"
#include "modules/prediction/container/pose/pose_container.h"
namespace apollo {
namespace prediction {
using ::apollo::common::PathPoint;
using ::apollo::common::TrajectoryPoint;
using ::apollo::common::adapter::AdapterConfig;
using ::apollo::common::math::Vec2d;
using ::apollo::hdmap::LaneInfo;
void SequencePredictor::Predict(Obstacle* obstacle) {
Clear();
CHECK_NOTNULL(obstacle);
CHECK_GT(obstacle->history_size(), 0);
}
void SequencePredictor::Clear() { Predictor::Clear(); }
std::string SequencePredictor::ToString(const LaneSequence& sequence) {
std::string str_lane_sequence = "";
if (sequence.lane_segment_size() > 0) {
str_lane_sequence += sequence.lane_segment(0).lane_id();
}
for (int i = 1; i < sequence.lane_segment_size(); ++i) {
str_lane_sequence += ("->" + sequence.lane_segment(i).lane_id());
}
return str_lane_sequence;
}
void SequencePredictor::FilterLaneSequences(
const Feature& feature, const std::string& lane_id,
std::vector<bool>* enable_lane_sequence) {
if (!feature.has_lane() || !feature.lane().has_lane_graph()) {
return;
}
const LaneGraph& lane_graph = feature.lane().lane_graph();
int num_lane_sequence = lane_graph.lane_sequence_size();
std::vector<LaneChangeType> lane_change_type(num_lane_sequence,
LaneChangeType::INVALID);
std::pair<int, double> change(-1, -1.0);
std::pair<int, double> all(-1, -1.0);
/**
* Filter out those obstacles that are close to the ADC
* so that we will ignore them and drive normally unless
* they really kick into our lane.
*/
for (int i = 0; i < num_lane_sequence; ++i) {
const LaneSequence& sequence = lane_graph.lane_sequence(i);
lane_change_type[i] = GetLaneChangeType(lane_id, sequence);
if (lane_change_type[i] != LaneChangeType::LEFT &&
lane_change_type[i] != LaneChangeType::RIGHT &&
lane_change_type[i] != LaneChangeType::ONTO_LANE) {
ADEBUG "Ignore lane sequence [" << ToString(sequence) << "].";
continue;
}
// The obstacle has interference with ADC within a small distance
double distance = GetLaneChangeDistanceWithADC(sequence);
ADEBUG << "Distance to ADC " << std::fixed << std::setprecision(6)
<< distance;
if (distance > 0.0 && distance < FLAGS_lane_change_dist) {
(*enable_lane_sequence)[i] = false;
ADEBUG << "Filter trajectory [" << ToString(sequence)
<< "] due to small distance " << distance << ".";
}
}
/**
* Pick the most probable lane-sequence and lane-change
*/
for (int i = 0; i < num_lane_sequence; ++i) {
const LaneSequence& sequence = lane_graph.lane_sequence(i);
if (!(*enable_lane_sequence)[i]) {
ADEBUG << "Disabled lane sequence [" << ToString(sequence) << "].";
continue;
}
double probability = sequence.probability();
if (LaneSequenceWithMaxProb(lane_change_type[i], probability, all.second)) {
all.first = i;
all.second = probability;
}
if (LaneChangeWithMaxProb(lane_change_type[i], probability,
change.second)) {
change.first = i;
change.second = probability;
}
}
for (int i = 0; i < num_lane_sequence; ++i) {
const LaneSequence& sequence = lane_graph.lane_sequence(i);
if (!(*enable_lane_sequence)[i]) {
ADEBUG << "Disabled lane sequence [" << ToString(sequence) << "].";
continue;
}
double probability = sequence.probability();
if (probability < FLAGS_lane_sequence_threshold && i != all.first) {
(*enable_lane_sequence)[i] = false;
} else if (change.first >= 0 && change.first < num_lane_sequence &&
(lane_change_type[i] == LaneChangeType::LEFT ||
lane_change_type[i] == LaneChangeType::RIGHT) &&
lane_change_type[i] != lane_change_type[change.first]) {
(*enable_lane_sequence)[i] = false;
}
}
}
SequencePredictor::LaneChangeType SequencePredictor::GetLaneChangeType(
const std::string& lane_id, const LaneSequence& lane_sequence) {
if (lane_id.empty()) {
return LaneChangeType::ONTO_LANE;
}
std::string lane_change_id = lane_sequence.lane_segment(0).lane_id();
if (lane_id == lane_change_id) {
return LaneChangeType::STRAIGHT;
} else {
if (PredictionMap::IsLeftNeighborLane(
PredictionMap::LaneById(lane_change_id),
PredictionMap::LaneById(lane_id))) {
return LaneChangeType::LEFT;
} else if (PredictionMap::IsRightNeighborLane(
PredictionMap::LaneById(lane_change_id),
PredictionMap::LaneById(lane_id))) {
return LaneChangeType::RIGHT;
}
}
return LaneChangeType::INVALID;
}
double SequencePredictor::GetLaneChangeDistanceWithADC(
const LaneSequence& lane_sequence) {
PoseContainer* pose_container = dynamic_cast<PoseContainer*>(
ContainerManager::Instance()->GetContainer(AdapterConfig::LOCALIZATION));
ADCTrajectoryContainer* adc_container = dynamic_cast<ADCTrajectoryContainer*>(
ContainerManager::Instance()->GetContainer(
AdapterConfig::PLANNING_TRAJECTORY));
CHECK_NOTNULL(pose_container);
CHECK_NOTNULL(adc_container);
if (!adc_container->HasOverlap(lane_sequence)) {
ADEBUG << "The sequence [" << ToString(lane_sequence)
<< "] has no overlap with ADC.";
return std::numeric_limits<double>::max();
}
Eigen::Vector2d adc_position;
if (pose_container->ToPerceptionObstacle() != nullptr) {
adc_position[0] = pose_container->ToPerceptionObstacle()->position().x();
adc_position[1] = pose_container->ToPerceptionObstacle()->position().y();
std::string obstacle_lane_id = lane_sequence.lane_segment(0).lane_id();
double obstacle_lane_s = lane_sequence.lane_segment(0).start_s();
double lane_s = 0.0;
double lane_l = 0.0;
if (PredictionMap::GetProjection(adc_position,
PredictionMap::LaneById(obstacle_lane_id),
&lane_s, &lane_l)) {
ADEBUG << "Distance with ADC is " << std::fabs(lane_s - obstacle_lane_s);
return obstacle_lane_s - lane_s;
}
}
ADEBUG << "Invalid ADC pose.";
return std::numeric_limits<double>::max();
}
bool SequencePredictor::LaneSequenceWithMaxProb(const LaneChangeType& type,
const double probability,
const double max_prob) {
if (probability > max_prob) {
return true;
} else {
double prob_diff = std::fabs(probability - max_prob);
if (prob_diff <= std::numeric_limits<double>::epsilon() &&
type == LaneChangeType::STRAIGHT) {
return true;
}
}
return false;
}
bool SequencePredictor::LaneChangeWithMaxProb(const LaneChangeType& type,
const double probability,
const double max_prob) {
if (type == LaneChangeType::LEFT || type == LaneChangeType::RIGHT) {
if (probability > max_prob) {
return true;
}
}
return false;
}
} // namespace prediction
} // namespace apollo
<|endoftext|>
|
<commit_before>/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Author: nikhilmadan@google.com (Nikhil Madan)
#include "net/instaweb/rewriter/public/redirect_on_size_limit_filter.h"
#include <algorithm>
#include "net/instaweb/rewriter/public/rewrite_driver.h"
#include "net/instaweb/rewriter/public/rewrite_options.h"
#include "net/instaweb/rewriter/public/rewrite_test_base.h"
#include "net/instaweb/rewriter/public/test_rewrite_driver_factory.h"
#include "pagespeed/kernel/base/gtest.h"
#include "pagespeed/kernel/base/string.h"
#include "pagespeed/kernel/base/string_util.h"
#include "pagespeed/kernel/base/string_writer.h"
namespace net_instaweb {
namespace {
static const char kScript[] = "<script type=\"text/javascript\">"
"window.location=\"http://test.com/in.html?PageSpeed=off\";"
"</script>";
} // namespace
class RedirectOnSizeLimitFilterTest : public RewriteTestBase {
public:
RedirectOnSizeLimitFilterTest() : writer_(&output_) {}
protected:
virtual void SetUp() {}
void SetupDriver(int size_limit) {
options_->set_max_html_parse_bytes(size_limit);
options_->EnableFilter(RewriteOptions::kHtmlWriterFilter);
RewriteTestBase::SetUp();
rewrite_driver()->AddFilters();
rewrite_driver()->SetWriter(&writer_);
}
void ClearAndResetDriver(int size_limit) {
delete rewrite_driver();
delete other_rewrite_driver();
output_.clear();
options_ = new RewriteOptions(factory()->thread_system());
other_options_ = new RewriteOptions(factory()->thread_system());
SetupDriver(size_limit);
}
void CheckOutput(int start_index, int end_index,
bool should_flush_before_size,
const GoogleString& input,
const GoogleString& expected_output) {
for (int i = start_index; i < end_index; ++i) {
ClearAndResetDriver(i);
if (should_flush_before_size && i > 2) {
html_parse()->StartParse("http://test.com/in.html");
int split = std::min(static_cast<int>(input.size()) - 1, i);
html_parse()->ParseText(input.substr(0, split));
html_parse()->Flush();
html_parse()->ParseText(input.substr(split, input.size() - 1));
html_parse()->FinishParse();
} else {
Parse("in", input);
}
EXPECT_EQ(expected_output, output_);
}
}
virtual bool AddHtmlTags() const { return false; }
virtual bool AddBody() const { return false; }
GoogleString output_;
private:
StringWriter writer_;
DISALLOW_COPY_AND_ASSIGN(RedirectOnSizeLimitFilterTest);
};
TEST_F(RedirectOnSizeLimitFilterTest, TestOneFlushWindow) {
static const char input[] =
"<html>" // 6 chars
"<input type=\"text\"/>" // 20 chars
"<script type=\"text/javascript\">alert('123');</script>" // 53 chars
"<!--[if IE]>...<![endif]-->" // 27 chars
"<table><tr><td>blah</td></tr></table>" // 37 chars
"</html>"; // 7 chars
SetupDriver(-1);
Parse("in", input);
EXPECT_EQ(input, output_);
CheckOutput(0, 1, false, input, input);
CheckOutput(1, 149, false, input, StringPrintf("<html>%s</html>", kScript));
CheckOutput(150, 180, false, input, input);
}
TEST_F(RedirectOnSizeLimitFilterTest, TestFlushBeforeLimit) {
const char input[] =
"<html>" // 6 chars
"<input type=\"text\"/>" // 20 chars
"<script type=\"text/javascript\">alert('123');</script>" // 53 chars
"<!--[if IE]>...<![endif]-->" // 27 chars
"<table><tr><td>blah</td></tr></table>" // 37 chars
"</html>"; // 7 chars
SetupDriver(-1);
Parse("in", input);
EXPECT_EQ(input, output_);
CheckOutput(0, 1, true, input, input);
CheckOutput(1, 6, true, input, StringPrintf("<html>%s</html>", kScript));
CheckOutput(6, 26, true, input,
StringPrintf("<html>%s<input type=\"text\"/></html>", kScript));
CheckOutput(26, 57, true, input,
StringPrintf("<html><input type=\"text\"/>%s"
"<script type=\"text/javascript\"></script></html>",
kScript));
CheckOutput(57, 79, true, input,
StringPrintf("<html><input type=\"text\"/>"
"%s<script type=\"text/javascript\">alert('123');</script>"
"</html>", kScript));
CheckOutput(79, 113, true, input,
StringPrintf("<html><input type=\"text\"/>"
"<script type=\"text/javascript\">alert('123');</script>"
"<!--[if IE]>...<![endif]-->%s<table></table></html>",
kScript));
CheckOutput(113, 117, true, input,
StringPrintf("<html><input type=\"text\"/>"
"<script type=\"text/javascript\">alert('123');</script>"
"<!--[if IE]>...<![endif]-->"
"<table>%s<tr></tr></table></html>", kScript));
CheckOutput(117, 121, true, input,
StringPrintf("<html><input type=\"text\"/>"
"<script type=\"text/javascript\">alert('123');</script>"
"<!--[if IE]>...<![endif]-->"
"<table><tr>%s<td></td></tr></table></html>", kScript));
CheckOutput(121, 130, true, input,
StringPrintf("<html><input type=\"text\"/>"
"<script type=\"text/javascript\">alert('123');</script>"
"<!--[if IE]>...<![endif]-->"
"<table><tr><td>blah</td>%s</tr></table></html>", kScript));
CheckOutput(130, 135, true, input,
StringPrintf("<html><input type=\"text\"/>"
"<script type=\"text/javascript\">alert('123');</script>"
"<!--[if IE]>...<![endif]-->"
"<table><tr><td>blah</td></tr>%s</table></html>", kScript));
CheckOutput(135, 150, true, input,
StringPrintf("<html><input type=\"text\"/>"
"<script type=\"text/javascript\">alert('123');</script>"
"<!--[if IE]>...<![endif]-->"
"<table><tr><td>blah</td></tr></table>%s</html>", kScript));
CheckOutput(150, 160, true, input, input);
}
TEST_F(RedirectOnSizeLimitFilterTest, TestEscapingAndFlush) {
SetupDriver(100);
// Depending on the version of Chromium GURL used, we get different quoting
// for a single-quote. Either is acceptable.
static const char kOutput[] =
"<html>"
"<input type=\"text\"/>"
"<script type=\"text/javascript\">"
"window.location=\"http://test.com/in.html?%27(&PageSpeed=off\";"
"</script>"
"<script type=\"text/javascript\">alert('123');</script>"
"</html>";
static const char kOutputAlt[] =
"<html>"
"<input type=\"text\"/>"
"<script type=\"text/javascript\">"
"window.location=\"http://test.com/in.html?\\'(&PageSpeed=off\";"
"</script>"
"<script type=\"text/javascript\">alert('123');</script>"
"</html>";
html_parse()->StartParse("http://test.com/in.html?'(");
html_parse()->ParseText(
"<html><input type=\"text\"/>"
"<script type=\"text/javascript\">");
html_parse()->Flush();
html_parse()->ParseText(
"alert('123');</script>"
"<!--[if IE]>...<![endif]-->"
"<table><tr><td>blah</td></tr></table></html>");
html_parse()->FinishParse();
EXPECT_TRUE((kOutput == output_) || (kOutputAlt == output_)) << output_;
}
} // namespace net_instaweb
<commit_msg>Simplify this to only support current revision, based on feedback.<commit_after>/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Author: nikhilmadan@google.com (Nikhil Madan)
#include "net/instaweb/rewriter/public/redirect_on_size_limit_filter.h"
#include <algorithm>
#include "net/instaweb/rewriter/public/rewrite_driver.h"
#include "net/instaweb/rewriter/public/rewrite_options.h"
#include "net/instaweb/rewriter/public/rewrite_test_base.h"
#include "net/instaweb/rewriter/public/test_rewrite_driver_factory.h"
#include "pagespeed/kernel/base/gtest.h"
#include "pagespeed/kernel/base/string.h"
#include "pagespeed/kernel/base/string_util.h"
#include "pagespeed/kernel/base/string_writer.h"
namespace net_instaweb {
namespace {
static const char kScript[] = "<script type=\"text/javascript\">"
"window.location=\"http://test.com/in.html?PageSpeed=off\";"
"</script>";
} // namespace
class RedirectOnSizeLimitFilterTest : public RewriteTestBase {
public:
RedirectOnSizeLimitFilterTest() : writer_(&output_) {}
protected:
virtual void SetUp() {}
void SetupDriver(int size_limit) {
options_->set_max_html_parse_bytes(size_limit);
options_->EnableFilter(RewriteOptions::kHtmlWriterFilter);
RewriteTestBase::SetUp();
rewrite_driver()->AddFilters();
rewrite_driver()->SetWriter(&writer_);
}
void ClearAndResetDriver(int size_limit) {
delete rewrite_driver();
delete other_rewrite_driver();
output_.clear();
options_ = new RewriteOptions(factory()->thread_system());
other_options_ = new RewriteOptions(factory()->thread_system());
SetupDriver(size_limit);
}
void CheckOutput(int start_index, int end_index,
bool should_flush_before_size,
const GoogleString& input,
const GoogleString& expected_output) {
for (int i = start_index; i < end_index; ++i) {
ClearAndResetDriver(i);
if (should_flush_before_size && i > 2) {
html_parse()->StartParse("http://test.com/in.html");
int split = std::min(static_cast<int>(input.size()) - 1, i);
html_parse()->ParseText(input.substr(0, split));
html_parse()->Flush();
html_parse()->ParseText(input.substr(split, input.size() - 1));
html_parse()->FinishParse();
} else {
Parse("in", input);
}
EXPECT_EQ(expected_output, output_);
}
}
virtual bool AddHtmlTags() const { return false; }
virtual bool AddBody() const { return false; }
GoogleString output_;
private:
StringWriter writer_;
DISALLOW_COPY_AND_ASSIGN(RedirectOnSizeLimitFilterTest);
};
TEST_F(RedirectOnSizeLimitFilterTest, TestOneFlushWindow) {
static const char input[] =
"<html>" // 6 chars
"<input type=\"text\"/>" // 20 chars
"<script type=\"text/javascript\">alert('123');</script>" // 53 chars
"<!--[if IE]>...<![endif]-->" // 27 chars
"<table><tr><td>blah</td></tr></table>" // 37 chars
"</html>"; // 7 chars
SetupDriver(-1);
Parse("in", input);
EXPECT_EQ(input, output_);
CheckOutput(0, 1, false, input, input);
CheckOutput(1, 149, false, input, StringPrintf("<html>%s</html>", kScript));
CheckOutput(150, 180, false, input, input);
}
TEST_F(RedirectOnSizeLimitFilterTest, TestFlushBeforeLimit) {
const char input[] =
"<html>" // 6 chars
"<input type=\"text\"/>" // 20 chars
"<script type=\"text/javascript\">alert('123');</script>" // 53 chars
"<!--[if IE]>...<![endif]-->" // 27 chars
"<table><tr><td>blah</td></tr></table>" // 37 chars
"</html>"; // 7 chars
SetupDriver(-1);
Parse("in", input);
EXPECT_EQ(input, output_);
CheckOutput(0, 1, true, input, input);
CheckOutput(1, 6, true, input, StringPrintf("<html>%s</html>", kScript));
CheckOutput(6, 26, true, input,
StringPrintf("<html>%s<input type=\"text\"/></html>", kScript));
CheckOutput(26, 57, true, input,
StringPrintf("<html><input type=\"text\"/>%s"
"<script type=\"text/javascript\"></script></html>",
kScript));
CheckOutput(57, 79, true, input,
StringPrintf("<html><input type=\"text\"/>"
"%s<script type=\"text/javascript\">alert('123');</script>"
"</html>", kScript));
CheckOutput(79, 113, true, input,
StringPrintf("<html><input type=\"text\"/>"
"<script type=\"text/javascript\">alert('123');</script>"
"<!--[if IE]>...<![endif]-->%s<table></table></html>",
kScript));
CheckOutput(113, 117, true, input,
StringPrintf("<html><input type=\"text\"/>"
"<script type=\"text/javascript\">alert('123');</script>"
"<!--[if IE]>...<![endif]-->"
"<table>%s<tr></tr></table></html>", kScript));
CheckOutput(117, 121, true, input,
StringPrintf("<html><input type=\"text\"/>"
"<script type=\"text/javascript\">alert('123');</script>"
"<!--[if IE]>...<![endif]-->"
"<table><tr>%s<td></td></tr></table></html>", kScript));
CheckOutput(121, 130, true, input,
StringPrintf("<html><input type=\"text\"/>"
"<script type=\"text/javascript\">alert('123');</script>"
"<!--[if IE]>...<![endif]-->"
"<table><tr><td>blah</td>%s</tr></table></html>", kScript));
CheckOutput(130, 135, true, input,
StringPrintf("<html><input type=\"text\"/>"
"<script type=\"text/javascript\">alert('123');</script>"
"<!--[if IE]>...<![endif]-->"
"<table><tr><td>blah</td></tr>%s</table></html>", kScript));
CheckOutput(135, 150, true, input,
StringPrintf("<html><input type=\"text\"/>"
"<script type=\"text/javascript\">alert('123');</script>"
"<!--[if IE]>...<![endif]-->"
"<table><tr><td>blah</td></tr></table>%s</html>", kScript));
CheckOutput(150, 160, true, input, input);
}
TEST_F(RedirectOnSizeLimitFilterTest, TestEscapingAndFlush) {
SetupDriver(100);
static const char kOutput[] =
"<html>"
"<input type=\"text\"/>"
"<script type=\"text/javascript\">"
"window.location=\"http://test.com/in.html?"
"\\'"
"(&PageSpeed=off\";"
"</script>"
"<script type=\"text/javascript\">alert('123');</script>"
"</html>";
html_parse()->StartParse("http://test.com/in.html?'(");
html_parse()->ParseText(
"<html><input type=\"text\"/>"
"<script type=\"text/javascript\">");
html_parse()->Flush();
html_parse()->ParseText(
"alert('123');</script>"
"<!--[if IE]>...<![endif]-->"
"<table><tr><td>blah</td></tr></table></html>");
html_parse()->FinishParse();
EXPECT_EQ(kOutput, output_);
}
} // namespace net_instaweb
<|endoftext|>
|
<commit_before>/**
* \file BaseFilter.cpp
*/
#include "BaseFilter.h"
#include <cassert>
#include <cstdint>
#include <iostream>
#include <stdexcept>
#if ATK_USE_THREADPOOL == 1
#include <tbb/task_group.h>
#endif
namespace ATK
{
BaseFilter::BaseFilter(unsigned int nb_input_ports, unsigned int nb_output_ports)
:nb_input_ports(nb_input_ports), nb_output_ports(nb_output_ports),
input_sampling_rate(0), output_sampling_rate(0),
connections(nb_input_ports, std::make_pair(-1, nullptr)), input_delay(0), output_delay(0),
latency(0), input_mandatory_connection(nb_input_ports), is_reset(false)
#if ATK_PROFILING == 1
, input_conversion_time(0), output_conversion_time(0), process_time(0)
#endif
{
}
BaseFilter::BaseFilter(BaseFilter&& other)
:nb_input_ports(other.nb_input_ports), nb_output_ports(other.nb_output_ports), input_sampling_rate(other.input_sampling_rate), output_sampling_rate(other.output_sampling_rate), connections(std::move(other.connections)), input_delay(other.input_delay), output_delay(std::move(other.output_delay)), latency(std::move(other.latency)), input_mandatory_connection(std::move(other.input_mandatory_connection)), is_reset(std::move(other.is_reset))
#if ATK_PROFILING == 1
, input_conversion_time(0), output_conversion_time(0), process_time(0)
#endif
{
}
BaseFilter::~BaseFilter()
{
#if ATK_PROFILING == 1
std::cerr << "Object of type " << class_name << std::endl;
std::cerr << "Input conversion time " << std::chrono::duration_cast<std::chrono::microseconds>(input_conversion_time).count() << "us" << std::endl;
std::cerr << "Output conversion time " << std::chrono::duration_cast<std::chrono::microseconds>(output_conversion_time).count() << "us" << std::endl;
std::cerr << "Process time " << std::chrono::duration_cast<std::chrono::microseconds>(process_time).count() << "us" << std::endl;
#endif
}
void BaseFilter::reset()
{
if (!is_reset)
{
for (auto it = connections.begin(); it != connections.end(); ++it)
{
if (it->second)
{
it->second->reset();
}
}
is_reset = true;
}
}
void BaseFilter::setup()
{
}
void BaseFilter::full_setup()
{
#if ATK_PROFILING == 1
class_name = typeid(*this).name();
#endif
setup();
}
void BaseFilter::set_input_port(unsigned int input_port, BaseFilter* filter, unsigned int output_port)
{
if(output_port >= filter->nb_output_ports)
{
throw std::runtime_error("Output port does not exist for this filter");
}
if(input_port < nb_input_ports)
{
connections[input_port] = std::make_pair(output_port, filter);
if(filter->get_output_sampling_rate() != get_input_sampling_rate())
{
throw std::runtime_error("Input sample rate from this filter must be equal to the output sample rate of the connected filter");
}
}
else
{
throw std::runtime_error("Input port doesn't exist for this filter");
}
}
void BaseFilter::set_input_sampling_rate(std::size_t rate)
{
input_sampling_rate = rate;
if(output_sampling_rate == 0)
{
output_sampling_rate = rate;
}
full_setup();
}
std::size_t BaseFilter::get_input_sampling_rate() const
{
return input_sampling_rate;
}
void BaseFilter::set_output_sampling_rate(std::size_t rate)
{
output_sampling_rate = rate;
full_setup();
}
std::size_t BaseFilter::get_output_sampling_rate() const
{
return output_sampling_rate;
}
std::size_t BaseFilter::get_input_delay() const
{
return input_delay;
}
std::size_t BaseFilter::get_output_delay() const
{
return output_delay;
}
void BaseFilter::process(std::size_t size)
{
reset();
process_conditionnally(size);
}
#if ATK_USE_THREADPOOL == 1
void BaseFilter::process_parallel(std::size_t size)
{
reset();
process_conditionnally_parallel(size);
}
#endif
void BaseFilter::process_conditionnally(std::size_t size)
{
if(size == 0)
{
return;
}
if(output_sampling_rate == 0)
{
throw std::runtime_error("Output sampling rate is 0, must be non 0 to compute the needed size for filters processing");
}
if(!is_reset)
{
return;
}
for(std::size_t port = 0; port < connections.size(); ++port)
{
if(connections[port].second == nullptr)
{
if(!input_mandatory_connection[port])
throw std::runtime_error("Input port " + std::to_string(port) + " is not connected");
}
else
{
assert(output_sampling_rate);
connections[port].second->process_conditionnally(uint64_t(size) * input_sampling_rate / output_sampling_rate);
}
}
#if ATK_PROFILING == 1
auto timer = std::chrono::steady_clock::now();
#endif
prepare_process(uint64_t(size) * input_sampling_rate / output_sampling_rate);
#if ATK_PROFILING == 1
auto timer2 = std::chrono::steady_clock::now();
input_conversion_time += (timer2 - timer);
timer = timer2;
#endif
prepare_outputs(size);
#if ATK_PROFILING == 1
timer2 = std::chrono::steady_clock::now();
output_conversion_time += (timer2 - timer);
timer = timer2;
#endif
process_impl(size);
#if ATK_PROFILING == 1
timer2 = std::chrono::steady_clock::now();
process_time += (timer2 - timer);
timer = timer2;
#endif
is_reset = false;
last_size = size;
}
#if ATK_USE_THREADPOOL == 1
void BaseFilter::process_conditionnally_parallel(std::size_t size)
{
if (size == 0)
{
return;
}
if (output_sampling_rate == 0)
{
throw std::runtime_error("Output sampling rate is 0, must be non 0 to compute the needed size for filters processing");
}
{ // lock this entire loop, as we only want to do the processing if we are not reseted
tbb::queuing_mutex::scoped_lock lock(mutex);
if (!is_reset)
{
return;
}
tbb::task_group g;
for(std::size_t port = 0; port < connections.size(); ++port)
{
if(connections[port].second == nullptr)
{
if(!input_mandatory_connection[port])
throw std::runtime_error("Input port " + std::to_string(port) + " is not connected");
}
else
{
assert(output_sampling_rate);
auto filter = connections[port];
g.run([=]{filter->process_conditionnally_parallel(size * input_sampling_rate / output_sampling_rate); });
}
}
g.wait();
#if ATK_PROFILING == 1
boost::timer::cpu_timer timer;
#endif
prepare_process(size * input_sampling_rate / output_sampling_rate);
#if ATK_PROFILING == 1
boost::timer::cpu_times const input_elapsed_times(timer.elapsed());
input_conversion_time += (input_elapsed_times.system + input_elapsed_times.user);
#endif
prepare_outputs(size);
#if ATK_PROFILING == 1
boost::timer::cpu_times const output_elapsed_times(timer.elapsed());
output_conversion_time += (output_elapsed_times.system + output_elapsed_times.user);
#endif
process_impl(size);
#if ATK_PROFILING == 1
boost::timer::cpu_times const process_elapsed_times(timer.elapsed());
process_time += (process_elapsed_times.system + process_elapsed_times.user);
#endif
is_reset = false;
last_size = size;
}
}
#endif
std::size_t BaseFilter::get_nb_input_ports() const
{
return nb_input_ports;
}
void BaseFilter::set_nb_input_ports(std::size_t nb_ports)
{
connections.resize(nb_ports, std::make_pair(-1, nullptr));
input_mandatory_connection.reset(nb_ports);
nb_input_ports = nb_ports;
}
void BaseFilter::allow_inactive_connection(unsigned int port)
{
input_mandatory_connection[port] = true;
}
std::size_t BaseFilter::get_nb_output_ports() const
{
return nb_output_ports;
}
void BaseFilter::set_nb_output_ports(std::size_t nb_ports)
{
nb_output_ports = nb_ports;
}
void BaseFilter::set_latency(std::size_t latency)
{
this->latency = latency;
}
std::size_t BaseFilter::get_latency() const
{
return latency;
}
std::size_t BaseFilter::get_global_latency() const
{
std::size_t global_latency = 0;
for(auto it = connections.begin(); it != connections.end(); ++it)
{
if(it->second == nullptr)
{
throw std::runtime_error("Input port " + std::to_string(it - connections.begin()) + " is not connected");
}
global_latency = std::max(global_latency, it->second->get_global_latency());
}
return global_latency + latency;
}
}
<commit_msg>Fix bitset resize<commit_after>/**
* \file BaseFilter.cpp
*/
#include "BaseFilter.h"
#include <cassert>
#include <cstdint>
#include <stdexcept>
#if ATK_PROFILING == 1
#include <iostream>
#endif
#if ATK_USE_THREADPOOL == 1
#include <tbb/task_group.h>
#endif
namespace ATK
{
BaseFilter::BaseFilter(unsigned int nb_input_ports, unsigned int nb_output_ports)
:nb_input_ports(nb_input_ports), nb_output_ports(nb_output_ports),
input_sampling_rate(0), output_sampling_rate(0),
connections(nb_input_ports, std::make_pair(-1, nullptr)), input_delay(0), output_delay(0),
latency(0), input_mandatory_connection(nb_input_ports), is_reset(false)
#if ATK_PROFILING == 1
, input_conversion_time(0), output_conversion_time(0), process_time(0)
#endif
{
}
BaseFilter::BaseFilter(BaseFilter&& other)
:nb_input_ports(other.nb_input_ports), nb_output_ports(other.nb_output_ports), input_sampling_rate(other.input_sampling_rate), output_sampling_rate(other.output_sampling_rate), connections(std::move(other.connections)), input_delay(other.input_delay), output_delay(std::move(other.output_delay)), latency(std::move(other.latency)), input_mandatory_connection(std::move(other.input_mandatory_connection)), is_reset(std::move(other.is_reset))
#if ATK_PROFILING == 1
, input_conversion_time(0), output_conversion_time(0), process_time(0)
#endif
{
}
BaseFilter::~BaseFilter()
{
#if ATK_PROFILING == 1
std::cerr << "Object of type " << class_name << std::endl;
std::cerr << "Input conversion time " << std::chrono::duration_cast<std::chrono::microseconds>(input_conversion_time).count() << "us" << std::endl;
std::cerr << "Output conversion time " << std::chrono::duration_cast<std::chrono::microseconds>(output_conversion_time).count() << "us" << std::endl;
std::cerr << "Process time " << std::chrono::duration_cast<std::chrono::microseconds>(process_time).count() << "us" << std::endl;
#endif
}
void BaseFilter::reset()
{
if (!is_reset)
{
for (auto it = connections.begin(); it != connections.end(); ++it)
{
if (it->second)
{
it->second->reset();
}
}
is_reset = true;
}
}
void BaseFilter::setup()
{
}
void BaseFilter::full_setup()
{
#if ATK_PROFILING == 1
class_name = typeid(*this).name();
#endif
setup();
}
void BaseFilter::set_input_port(unsigned int input_port, BaseFilter* filter, unsigned int output_port)
{
if(output_port >= filter->nb_output_ports)
{
throw std::runtime_error("Output port does not exist for this filter");
}
if(input_port < nb_input_ports)
{
connections[input_port] = std::make_pair(output_port, filter);
if(filter->get_output_sampling_rate() != get_input_sampling_rate())
{
throw std::runtime_error("Input sample rate from this filter must be equal to the output sample rate of the connected filter");
}
}
else
{
throw std::runtime_error("Input port doesn't exist for this filter");
}
}
void BaseFilter::set_input_sampling_rate(std::size_t rate)
{
input_sampling_rate = rate;
if(output_sampling_rate == 0)
{
output_sampling_rate = rate;
}
full_setup();
}
std::size_t BaseFilter::get_input_sampling_rate() const
{
return input_sampling_rate;
}
void BaseFilter::set_output_sampling_rate(std::size_t rate)
{
output_sampling_rate = rate;
full_setup();
}
std::size_t BaseFilter::get_output_sampling_rate() const
{
return output_sampling_rate;
}
std::size_t BaseFilter::get_input_delay() const
{
return input_delay;
}
std::size_t BaseFilter::get_output_delay() const
{
return output_delay;
}
void BaseFilter::process(std::size_t size)
{
reset();
process_conditionnally(size);
}
#if ATK_USE_THREADPOOL == 1
void BaseFilter::process_parallel(std::size_t size)
{
reset();
process_conditionnally_parallel(size);
}
#endif
void BaseFilter::process_conditionnally(std::size_t size)
{
if(size == 0)
{
return;
}
if(output_sampling_rate == 0)
{
throw std::runtime_error("Output sampling rate is 0, must be non 0 to compute the needed size for filters processing");
}
if(!is_reset)
{
return;
}
for(std::size_t port = 0; port < connections.size(); ++port)
{
if(connections[port].second == nullptr)
{
if(!input_mandatory_connection[port])
throw std::runtime_error("Input port " + std::to_string(port) + " is not connected");
}
else
{
assert(output_sampling_rate);
connections[port].second->process_conditionnally(uint64_t(size) * input_sampling_rate / output_sampling_rate);
}
}
#if ATK_PROFILING == 1
auto timer = std::chrono::steady_clock::now();
#endif
prepare_process(uint64_t(size) * input_sampling_rate / output_sampling_rate);
#if ATK_PROFILING == 1
auto timer2 = std::chrono::steady_clock::now();
input_conversion_time += (timer2 - timer);
timer = timer2;
#endif
prepare_outputs(size);
#if ATK_PROFILING == 1
timer2 = std::chrono::steady_clock::now();
output_conversion_time += (timer2 - timer);
timer = timer2;
#endif
process_impl(size);
#if ATK_PROFILING == 1
timer2 = std::chrono::steady_clock::now();
process_time += (timer2 - timer);
timer = timer2;
#endif
is_reset = false;
last_size = size;
}
#if ATK_USE_THREADPOOL == 1
void BaseFilter::process_conditionnally_parallel(std::size_t size)
{
if (size == 0)
{
return;
}
if (output_sampling_rate == 0)
{
throw std::runtime_error("Output sampling rate is 0, must be non 0 to compute the needed size for filters processing");
}
{ // lock this entire loop, as we only want to do the processing if we are not reseted
tbb::queuing_mutex::scoped_lock lock(mutex);
if (!is_reset)
{
return;
}
tbb::task_group g;
for(std::size_t port = 0; port < connections.size(); ++port)
{
if(connections[port].second == nullptr)
{
if(!input_mandatory_connection[port])
throw std::runtime_error("Input port " + std::to_string(port) + " is not connected");
}
else
{
assert(output_sampling_rate);
auto filter = connections[port];
g.run([=]{filter->process_conditionnally_parallel(size * input_sampling_rate / output_sampling_rate); });
}
}
g.wait();
#if ATK_PROFILING == 1
boost::timer::cpu_timer timer;
#endif
prepare_process(size * input_sampling_rate / output_sampling_rate);
#if ATK_PROFILING == 1
boost::timer::cpu_times const input_elapsed_times(timer.elapsed());
input_conversion_time += (input_elapsed_times.system + input_elapsed_times.user);
#endif
prepare_outputs(size);
#if ATK_PROFILING == 1
boost::timer::cpu_times const output_elapsed_times(timer.elapsed());
output_conversion_time += (output_elapsed_times.system + output_elapsed_times.user);
#endif
process_impl(size);
#if ATK_PROFILING == 1
boost::timer::cpu_times const process_elapsed_times(timer.elapsed());
process_time += (process_elapsed_times.system + process_elapsed_times.user);
#endif
is_reset = false;
last_size = size;
}
}
#endif
std::size_t BaseFilter::get_nb_input_ports() const
{
return nb_input_ports;
}
void BaseFilter::set_nb_input_ports(std::size_t nb_ports)
{
connections.resize(nb_ports, std::make_pair(-1, nullptr));
input_mandatory_connection.resize(nb_ports);
nb_input_ports = nb_ports;
}
void BaseFilter::allow_inactive_connection(unsigned int port)
{
input_mandatory_connection[port] = true;
}
std::size_t BaseFilter::get_nb_output_ports() const
{
return nb_output_ports;
}
void BaseFilter::set_nb_output_ports(std::size_t nb_ports)
{
nb_output_ports = nb_ports;
}
void BaseFilter::set_latency(std::size_t latency)
{
this->latency = latency;
}
std::size_t BaseFilter::get_latency() const
{
return latency;
}
std::size_t BaseFilter::get_global_latency() const
{
std::size_t global_latency = 0;
for(auto it = connections.begin(); it != connections.end(); ++it)
{
if(it->second == nullptr)
{
throw std::runtime_error("Input port " + std::to_string(it - connections.begin()) + " is not connected");
}
global_latency = std::max(global_latency, it->second->get_global_latency());
}
return global_latency + latency;
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2012. All rights reserved
*/
#include "../../StroikaPreComp.h"
#include "../../Characters/Format.h"
#include "Writer.h"
using namespace Stroika;
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Characters;
using namespace Stroika::Foundation::DataExchangeFormat;
using namespace Stroika::Foundation::DataExchangeFormat::XML;
/*
********************************************************************************
****************************** QuoteForXMLAttribute ****************************
********************************************************************************
*/
string XML::QuoteForXMLAttribute (const string& s)
{
string r;
r.reserve (s.size () * 6 / 5); // wild guess about good estimate
for (string::const_iterator i = s.begin (); i != s.end (); ++i) {
Containers::ReserveSpeedTweekAdd1 (r);
switch (*i) {
case '&':
r += "&";
break;
case '<':
r += "<";
break;
case '>':
r += ">";
break;
case '\"':
r += """;
break;
case '\'':
r += "'";
break;
default:
r.push_back (*i);
break;
}
}
return r;
}
string XML::QuoteForXMLAttribute (const wstring& s)
{
string r;
r.reserve (s.size () * 7 / 5); // wild guess about good estimate
for (wstring::const_iterator i = s.begin (); i != s.end (); ++i) {
Containers::ReserveSpeedTweekAdd1 (r);
switch (*i) {
case '&':
r += "&";
break;
case '<':
r += "<";
break;
case '>':
r += ">";
break;
case '\"':
r += """;
break;
case '\'':
r += "'";
break;
default: {
wchar_t ccode = *i;
if (ccode != '\t' and ccode != '\n' and ccode != '\r' and (ccode < 32 || ccode > 127)) {
r += Format ("&#%d;", ccode);
}
else {
r.push_back (static_cast<char> (ccode));
}
}
break;
}
}
return r;
}
string XML::QuoteForXMLAttribute (const String& s)
{
return QuoteForXMLAttribute (s.As<wstring> ());
}
string XML::QuoteForXMLAttribute (const Memory::Optional<String>& s)
{
if (s.empty ()) {
return string ();
}
return QuoteForXMLAttribute (*s);
}
wstring XML::QuoteForXMLAttributeW (const wstring& s)
{
string tmp = QuoteForXMLAttribute (s);
return NarrowSDKStringToWide (tmp);
}
/*
********************************************************************************
******************************** QuoteForXML ***********************************
********************************************************************************
*/
string XML::QuoteForXML (const string& s)
{
string r;
r.reserve (s.size () * 6 / 5); // wild guess about good estimate
for (string::const_iterator i = s.begin (); i != s.end (); ++i) {
Containers::ReserveSpeedTweekAdd1 (r);
switch (*i) {
case '&':
r += "&";
break;
case '<':
r += "<";
break;
case '>':
r += ">";
break;
case '-': {
// A 'dash' or 'minus-sign' can be dangerous in XML - if you get two in a row (start/end comment designator).
// So avoid any leading/trailing dash, and any double-dashes.
//
// NB: This code WOULD be simpler if we just always mapped, but then much ordinary and safe text with dashes becomes
// less readable (and produces huge diffs in my regression tests - but thats a one-time annoyance).
//
if ((i == s.begin ()) or (i + 1 == s.end ()) or (*(i - 1) == '-')) {
r += "-";
}
else {
r.push_back ('-');
}
}
break;
default:
r.push_back (*i);
break;
}
}
return r;
}
string XML::QuoteForXML (const wstring& s)
{
string r;
r.reserve (s.size () * 7 / 5); // wild guess about good estimate
for (wstring::const_iterator i = s.begin (); i != s.end (); ++i) {
Containers::ReserveSpeedTweekAdd1 (r);
switch (*i) {
case '&':
r += "&";
break;
case '<':
r += "<";
break;
case '>':
r += ">";
break;
case '-': {
// A 'dash' or 'minus-sign' can be dangerous in XML - if you get two in a row (start/end comment designator).
// So avoid any leading/trailing dash, and any double-dashes.
//
// NB: This code WOULD be simpler if we just always mapped, but then much ordinary and safe text with dashes becomes
// less readable (and produces huge diffs in my regression tests - but thats a one-time annoyance).
//
if ((i == s.begin ()) or (i + 1 == s.end ()) or (*(i - 1) == '-')) {
r += "-";
}
else {
r.push_back ('-');
}
}
break;
default: {
wchar_t ccode = *i;
if (ccode != '\t' and ccode != '\n' and ccode != '\r' and (ccode < 32 || ccode > 127)) {
r += Format ("&#%d;", ccode);
}
else {
r.push_back (static_cast<char> (ccode));
}
}
break;
}
}
return r;
}
wstring XML::QuoteForXMLW (const wstring& s)
{
string tmp = QuoteForXML (s);
return NarrowSDKStringToWide (tmp);
}
string XML::QuoteForXML (const String& s)
{
return QuoteForXML (s.As<wstring> ());
}
string XML::QuoteForXML (const Memory::Optional<String>& s)
{
if (s.empty ()) {
return string ();
}
return QuoteForXML (*s);
}
/*
********************************************************************************
****************************** XML::Indenter ***********************************
********************************************************************************
*/
Indenter::Indenter (const String& indentText)
: fTabS_ (indentText.AsUTF8<string> ())
, fTabW_ (indentText.As<wstring> ())
{
}
void Indenter::Indent (unsigned indentLevel, ostream& out) const
{
for (unsigned int i = 0; i < indentLevel; ++i) {
out << fTabS_;
}
}
void Indenter::Indent (unsigned int indentLevel, wostream& out) const
{
for (unsigned int i = 0; i < indentLevel; ++i) {
out << fTabW_;
}
}
string XML::Format4XML (bool v)
{
return v ? "true" : "false";
}
<commit_msg>added missing include (for gcc)<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2012. All rights reserved
*/
#include "../../StroikaPreComp.h"
#include <ostream>
#include "../../Characters/Format.h"
#include "Writer.h"
using namespace Stroika;
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Characters;
using namespace Stroika::Foundation::DataExchangeFormat;
using namespace Stroika::Foundation::DataExchangeFormat::XML;
/*
********************************************************************************
****************************** QuoteForXMLAttribute ****************************
********************************************************************************
*/
string XML::QuoteForXMLAttribute (const string& s)
{
string r;
r.reserve (s.size () * 6 / 5); // wild guess about good estimate
for (string::const_iterator i = s.begin (); i != s.end (); ++i) {
Containers::ReserveSpeedTweekAdd1 (r);
switch (*i) {
case '&':
r += "&";
break;
case '<':
r += "<";
break;
case '>':
r += ">";
break;
case '\"':
r += """;
break;
case '\'':
r += "'";
break;
default:
r.push_back (*i);
break;
}
}
return r;
}
string XML::QuoteForXMLAttribute (const wstring& s)
{
string r;
r.reserve (s.size () * 7 / 5); // wild guess about good estimate
for (wstring::const_iterator i = s.begin (); i != s.end (); ++i) {
Containers::ReserveSpeedTweekAdd1 (r);
switch (*i) {
case '&':
r += "&";
break;
case '<':
r += "<";
break;
case '>':
r += ">";
break;
case '\"':
r += """;
break;
case '\'':
r += "'";
break;
default: {
wchar_t ccode = *i;
if (ccode != '\t' and ccode != '\n' and ccode != '\r' and (ccode < 32 || ccode > 127)) {
r += Format ("&#%d;", ccode);
}
else {
r.push_back (static_cast<char> (ccode));
}
}
break;
}
}
return r;
}
string XML::QuoteForXMLAttribute (const String& s)
{
return QuoteForXMLAttribute (s.As<wstring> ());
}
string XML::QuoteForXMLAttribute (const Memory::Optional<String>& s)
{
if (s.empty ()) {
return string ();
}
return QuoteForXMLAttribute (*s);
}
wstring XML::QuoteForXMLAttributeW (const wstring& s)
{
string tmp = QuoteForXMLAttribute (s);
return NarrowSDKStringToWide (tmp);
}
/*
********************************************************************************
******************************** QuoteForXML ***********************************
********************************************************************************
*/
string XML::QuoteForXML (const string& s)
{
string r;
r.reserve (s.size () * 6 / 5); // wild guess about good estimate
for (string::const_iterator i = s.begin (); i != s.end (); ++i) {
Containers::ReserveSpeedTweekAdd1 (r);
switch (*i) {
case '&':
r += "&";
break;
case '<':
r += "<";
break;
case '>':
r += ">";
break;
case '-': {
// A 'dash' or 'minus-sign' can be dangerous in XML - if you get two in a row (start/end comment designator).
// So avoid any leading/trailing dash, and any double-dashes.
//
// NB: This code WOULD be simpler if we just always mapped, but then much ordinary and safe text with dashes becomes
// less readable (and produces huge diffs in my regression tests - but thats a one-time annoyance).
//
if ((i == s.begin ()) or (i + 1 == s.end ()) or (*(i - 1) == '-')) {
r += "-";
}
else {
r.push_back ('-');
}
}
break;
default:
r.push_back (*i);
break;
}
}
return r;
}
string XML::QuoteForXML (const wstring& s)
{
string r;
r.reserve (s.size () * 7 / 5); // wild guess about good estimate
for (wstring::const_iterator i = s.begin (); i != s.end (); ++i) {
Containers::ReserveSpeedTweekAdd1 (r);
switch (*i) {
case '&':
r += "&";
break;
case '<':
r += "<";
break;
case '>':
r += ">";
break;
case '-': {
// A 'dash' or 'minus-sign' can be dangerous in XML - if you get two in a row (start/end comment designator).
// So avoid any leading/trailing dash, and any double-dashes.
//
// NB: This code WOULD be simpler if we just always mapped, but then much ordinary and safe text with dashes becomes
// less readable (and produces huge diffs in my regression tests - but thats a one-time annoyance).
//
if ((i == s.begin ()) or (i + 1 == s.end ()) or (*(i - 1) == '-')) {
r += "-";
}
else {
r.push_back ('-');
}
}
break;
default: {
wchar_t ccode = *i;
if (ccode != '\t' and ccode != '\n' and ccode != '\r' and (ccode < 32 || ccode > 127)) {
r += Format ("&#%d;", ccode);
}
else {
r.push_back (static_cast<char> (ccode));
}
}
break;
}
}
return r;
}
wstring XML::QuoteForXMLW (const wstring& s)
{
string tmp = QuoteForXML (s);
return NarrowSDKStringToWide (tmp);
}
string XML::QuoteForXML (const String& s)
{
return QuoteForXML (s.As<wstring> ());
}
string XML::QuoteForXML (const Memory::Optional<String>& s)
{
if (s.empty ()) {
return string ();
}
return QuoteForXML (*s);
}
/*
********************************************************************************
****************************** XML::Indenter ***********************************
********************************************************************************
*/
Indenter::Indenter (const String& indentText)
: fTabS_ (indentText.AsUTF8<string> ())
, fTabW_ (indentText.As<wstring> ())
{
}
void Indenter::Indent (unsigned indentLevel, ostream& out) const
{
for (unsigned int i = 0; i < indentLevel; ++i) {
out << fTabS_;
}
}
void Indenter::Indent (unsigned int indentLevel, wostream& out) const
{
for (unsigned int i = 0; i < indentLevel; ++i) {
out << fTabW_;
}
}
string XML::Format4XML (bool v)
{
return v ? "true" : "false";
}
<|endoftext|>
|
<commit_before>/* Copyright (C) 2005-2007, Thorvald Natvig <thorvald@natvig.com>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
- Neither the name of the Mumble Developers 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 FOUNDATION 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 <QtXml>
#include "Server.h"
void Server::initRegister() {
http = NULL;
qssReg = NULL;
connect(&qtTick, SIGNAL(timeout()), this, SLOT(update()));
if (! qsRegName.isEmpty()) {
if ((! qsRegName.isEmpty()) && (! qsRegPassword.isEmpty()) && (qurlRegWeb.isValid()) && (qsPassword.isEmpty()))
qtTick.start(60 * 10);
else
log("Registration needs nonempty name, password and url, and the server must not be password protected.");
} else {
log("Not registering server as public");
}
}
void Server::abort() {
if (http) {
http->setSocket(NULL);
http->deleteLater();
http = NULL;
}
if (qssReg) {
qssReg->deleteLater();
qssReg = NULL;
}
}
void Server::update() {
abort();
qtTick.start(10 * 60 * 60);
QDomDocument doc;
QDomElement root=doc.createElement(QLatin1String("server"));
doc.appendChild(root);
QDomElement tag;
QDomText t;
tag=doc.createElement(QLatin1String("name"));
root.appendChild(tag);
t=doc.createTextNode(qsRegName);
tag.appendChild(t);
tag=doc.createElement(QLatin1String("host"));
root.appendChild(tag);
t=doc.createTextNode(qsRegHost);
tag.appendChild(t);
tag=doc.createElement(QLatin1String("password"));
root.appendChild(tag);
t=doc.createTextNode(qsRegPassword);
tag.appendChild(t);
tag=doc.createElement(QLatin1String("port"));
root.appendChild(tag);
t=doc.createTextNode(QString::number(iPort));
tag.appendChild(t);
tag=doc.createElement(QLatin1String("url"));
root.appendChild(tag);
t=doc.createTextNode(qurlRegWeb.toString());
tag.appendChild(t);
tag=doc.createElement(QLatin1String("digest"));
root.appendChild(tag);
t=doc.createTextNode(getDigest());
tag.appendChild(t);
qssReg = new QSslSocket(this);
qssReg->setLocalCertificate(qscCert);
qssReg->setPrivateKey(qskKey);
http = new QHttp(QLatin1String("mumble.hive.no"), QHttp::ConnectionModeHttps, 443, this);
http->setSocket(qssReg);
connect(http, SIGNAL(done(bool)), this, SLOT(done(bool)));
connect(http, SIGNAL(sslErrors ( const QList<QSslError> &)), this, SLOT(regSslError(const QList<QSslError> &)));
QHttpRequestHeader h(QLatin1String("POST"), QLatin1String("/register.cgi"));
h.setValue(QLatin1String("Connection"), QLatin1String("Keep-Alive"));
h.setValue(QLatin1String("Host"), QLatin1String("mumble.hive.no"));
h.setContentType(QLatin1String("text/xml"));
http->request(h, doc.toString().toUtf8());
}
void Server::done(bool err) {
if (! http || ! qssReg)
return;
if (err) {
log("Regstration failed: %s", qPrintable(http->errorString()));
} else {
QByteArray qba = http->readAll();
log("Registration: %s", qPrintable(QString(QLatin1String(qba))));
}
abort();
}
void Server::regSslError(const QList<QSslError> &errs) {
foreach(const QSslError &e, errs)
log("Registration: SSL Handshake error: %s", qPrintable(e.errorString()));
}
<commit_msg>Revert to seconds instead of centiseconds for registration delays<commit_after>/* Copyright (C) 2005-2007, Thorvald Natvig <thorvald@natvig.com>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
- Neither the name of the Mumble Developers 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 FOUNDATION 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 <QtXml>
#include "Server.h"
void Server::initRegister() {
http = NULL;
qssReg = NULL;
connect(&qtTick, SIGNAL(timeout()), this, SLOT(update()));
if (! qsRegName.isEmpty()) {
if ((! qsRegName.isEmpty()) && (! qsRegPassword.isEmpty()) && (qurlRegWeb.isValid()) && (qsPassword.isEmpty()))
qtTick.start(60 * 1000);
else
log("Registration needs nonempty name, password and url, and the server must not be password protected.");
} else {
log("Not registering server as public");
}
}
void Server::abort() {
if (http) {
http->setSocket(NULL);
http->deleteLater();
http = NULL;
}
if (qssReg) {
qssReg->deleteLater();
qssReg = NULL;
}
}
void Server::update() {
abort();
qtTick.start(1000 * 60 * 60);
QDomDocument doc;
QDomElement root=doc.createElement(QLatin1String("server"));
doc.appendChild(root);
QDomElement tag;
QDomText t;
tag=doc.createElement(QLatin1String("name"));
root.appendChild(tag);
t=doc.createTextNode(qsRegName);
tag.appendChild(t);
tag=doc.createElement(QLatin1String("host"));
root.appendChild(tag);
t=doc.createTextNode(qsRegHost);
tag.appendChild(t);
tag=doc.createElement(QLatin1String("password"));
root.appendChild(tag);
t=doc.createTextNode(qsRegPassword);
tag.appendChild(t);
tag=doc.createElement(QLatin1String("port"));
root.appendChild(tag);
t=doc.createTextNode(QString::number(iPort));
tag.appendChild(t);
tag=doc.createElement(QLatin1String("url"));
root.appendChild(tag);
t=doc.createTextNode(qurlRegWeb.toString());
tag.appendChild(t);
tag=doc.createElement(QLatin1String("digest"));
root.appendChild(tag);
t=doc.createTextNode(getDigest());
tag.appendChild(t);
qssReg = new QSslSocket(this);
qssReg->setLocalCertificate(qscCert);
qssReg->setPrivateKey(qskKey);
http = new QHttp(QLatin1String("mumble.hive.no"), QHttp::ConnectionModeHttps, 443, this);
http->setSocket(qssReg);
connect(http, SIGNAL(done(bool)), this, SLOT(done(bool)));
connect(http, SIGNAL(sslErrors ( const QList<QSslError> &)), this, SLOT(regSslError(const QList<QSslError> &)));
QHttpRequestHeader h(QLatin1String("POST"), QLatin1String("/register.cgi"));
h.setValue(QLatin1String("Connection"), QLatin1String("Keep-Alive"));
h.setValue(QLatin1String("Host"), QLatin1String("mumble.hive.no"));
h.setContentType(QLatin1String("text/xml"));
http->request(h, doc.toString().toUtf8());
}
void Server::done(bool err) {
if (! http || ! qssReg)
return;
if (err) {
log("Regstration failed: %s", qPrintable(http->errorString()));
} else {
QByteArray qba = http->readAll();
log("Registration: %s", qPrintable(QString(QLatin1String(qba))));
}
abort();
}
void Server::regSslError(const QList<QSslError> &errs) {
foreach(const QSslError &e, errs)
log("Registration: SSL Handshake error: %s", qPrintable(e.errorString()));
}
<|endoftext|>
|
<commit_before>#include <ModuleFramework/Module.h>
#include "ModuleFramework/ModuleManager.h"
#include "Tools/StrategyTools.h"
#include <gtest/gtest.h>
using namespace std;
class StrategyToolsTest : public ::testing::Test
{
public:
StrategyTools* strategyTools;
protected:
StrategyToolsTest(){}
virtual void SetUp()
{
}
};
TEST_F(StrategyToolsTest, arrangeRobots)
{
std::vector<Vector2d> setPiecePoints;
//input of positions
setPiecePoints.push_back(Vector2d(-1700.0, -1700.0));
setPiecePoints.push_back(Vector2d(-2400.0, 0.0));
setPiecePoints.push_back(Vector2d(-1700.0, 1700.0));
std::vector<int> placesToRobots(3);
// init
for(unsigned int i = 0; i < placesToRobots.size(); i++)
{
placesToRobots[i] = i;
}//end for
std::vector<Vector2d > playersPoints;
playersPoints.push_back(Vector2d(2400.0, 0.0));
playersPoints.push_back(Vector2d(3400.0, 500.0));
playersPoints.push_back(Vector2d(2800.0, -700.0));
playersPoints.push_back(Vector2d(-2500.0, 0.0));
playersPoints.push_back(Vector2d(-1600.0, 1600.0));
playersPoints.push_back(Vector2d(-1600.0, -1700.0));
strategyTools->arrangeRobots(playersPoints, setPiecePoints, placesToRobots);
std::vector<int> expectedPlacesToRobots;
expectedPlacesToRobots.push_back(0);
expectedPlacesToRobots.push_back(1);
expectedPlacesToRobots.push_back(2);
for(unsigned int i = 0; i < placesToRobots.size(); i++)
{
if(placesToRobots[i] != expectedPlacesToRobots[1])
{
cout << "Assignement Wrong" << endl;
}
}//end for
}//end testArrangeRobots<commit_msg>repaired Test<commit_after>#include <ModuleFramework/Module.h>
#include "ModuleFramework/ModuleManager.h"
#include "Tools/StrategyTools.h"
#include <gtest/gtest.h>
using namespace std;
class StrategyToolsTest : public ::testing::Test
{
public:
StrategyTools* strategyTools;
protected:
StrategyToolsTest(){}
virtual void SetUp()
{
}
};
TEST_F(StrategyToolsTest, arrangeRobots)
{
std::vector<Vector2d> setPiecePoints;
//input of positions
setPiecePoints.push_back(Vector2d(-1700.0, -1700.0));
setPiecePoints.push_back(Vector2d(-2400.0, 0.0));
setPiecePoints.push_back(Vector2d(-1700.0, 1700.0));
std::vector<int> placesToRobots(3);
// init
for(unsigned int i = 0; i < placesToRobots.size(); i++)
{
placesToRobots[i] = i;
}//end for
std::vector<Vector2d > playersPoints;
playersPoints.push_back(Vector2d(2400.0, 0.0));
playersPoints.push_back(Vector2d(3400.0, 500.0));
playersPoints.push_back(Vector2d(2800.0, -700.0));
playersPoints.push_back(Vector2d(-2500.0, 0.0));
playersPoints.push_back(Vector2d(-1600.0, 1600.0));
playersPoints.push_back(Vector2d(-1600.0, -1700.0));
strategyTools->arrangeRobots(playersPoints, setPiecePoints, placesToRobots);
std::vector<int> expectedPlacesToRobots;
expectedPlacesToRobots.push_back(5);
expectedPlacesToRobots.push_back(3);
expectedPlacesToRobots.push_back(4);
ASSERT_EQ(expectedPlacesToRobots[0], placesToRobots[0]);
ASSERT_EQ(expectedPlacesToRobots[1], placesToRobots[1]);
ASSERT_EQ(expectedPlacesToRobots[2], placesToRobots[2]);
}//end testArrangeRobots<|endoftext|>
|
<commit_before>#include "aquila/global.h"
#include "aquila/filter/MelFilter.h"
#include "aquila/filter/MelFilterBank.h"
#include <unittestpp.h>
#include <cstddef>
#include <vector>
template <std::size_t N>
void testMelFilterBankOutput()
{
Aquila::FrequencyType sampleFrequency = 44100.0;
Aquila::MelFilterBank filters(sampleFrequency, N);
for (std::size_t k = 0; k < filters.size(); ++k)
{
// create a single spectral peak at middle frequency of k-th Mel filter
Aquila::SpectrumType spectrum(N);
Aquila::FrequencyType melFrequency = 100.0 + k * 100.0;
Aquila::FrequencyType linearFrequency = Aquila::MelFilter::melToLinear(melFrequency);
std::size_t peakNumber = N * (linearFrequency / sampleFrequency);
spectrum[peakNumber] = 5000.0;
auto output = filters.applyAll(spectrum);
std::vector<double> expected(filters.size(), 0.0);
expected[k] = 5000.0;
CHECK_ARRAY_CLOSE(expected, output, filters.size(), 0.000001);
}
}
SUITE(MelFilter)
{
TEST(SampleFrequency)
{
Aquila::MelFilterBank filters(22050, 2048);
CHECK_EQUAL(22050, filters.getSampleFrequency());
}
TEST(SpectrumLength)
{
Aquila::MelFilterBank filters(22050, 2048);
CHECK_EQUAL(2048u, filters.getSpectrumLength());
}
TEST(FilterOutput1024)
{
testMelFilterBankOutput<1024>();
}
TEST(FilterOutput2048)
{
testMelFilterBankOutput<2048>();
}
TEST(FilterOutput4096)
{
testMelFilterBankOutput<4096>();
}
}
<commit_msg>Updated tests for MelFilterBank.<commit_after>#include "aquila/global.h"
#include "aquila/filter/MelFilter.h"
#include "aquila/filter/MelFilterBank.h"
#include <unittestpp.h>
#include <cstddef>
#include <vector>
template <std::size_t N>
void testMelFilterBankOutput()
{
Aquila::FrequencyType sampleFrequency = 44100.0;
Aquila::MelFilterBank filters(sampleFrequency, N);
for (std::size_t k = 0; k < filters.size(); ++k)
{
// create a single spectral peak at middle frequency of k-th Mel filter
Aquila::SpectrumType spectrum(N);
Aquila::FrequencyType melFrequency = 100.0 + k * 100.0;
Aquila::FrequencyType linearFrequency = Aquila::MelFilter::melToLinear(melFrequency);
std::size_t peakNumber = N * (linearFrequency / sampleFrequency);
spectrum[peakNumber] = 5000.0;
auto output = filters.applyAll(spectrum);
CHECK(output[k] > 0);
}
}
SUITE(MelFilter)
{
TEST(SampleFrequency)
{
Aquila::MelFilterBank filters(22050, 2048);
CHECK_EQUAL(22050, filters.getSampleFrequency());
}
TEST(SpectrumLength)
{
Aquila::MelFilterBank filters(22050, 2048);
CHECK_EQUAL(2048u, filters.getSpectrumLength());
}
TEST(FilterOutput1024)
{
testMelFilterBankOutput<1024>();
}
TEST(FilterOutput2048)
{
testMelFilterBankOutput<2048>();
}
TEST(FilterOutput4096)
{
testMelFilterBankOutput<4096>();
}
}
<|endoftext|>
|
<commit_before>// This test case fails unless an implementation of TLS backend is installed.
// (Exception caught: TLS support is not available.)
// Module glib-networking implements TLS backend.
//
// Even if glib-networking is installed, it's possible that glib does not find it.
// That's very probable if glib and glib-networking are installed with different
// directory prefixes, e.g. glib in /opt/gnome and glib-networking in /usr.
// You can fix that by setting the GIO_EXTRA_MODULES environment variable to
// the directory to search for implementations of gio extension points.
// Example:
// export GIO_EXTRA_MODULES=/usr/lib/x86_64-linux-gnu/gio/modules
// If you don't know where the implementations of gio extension points are stored,
// search for a file named giomodule.cache.
//
// https://developer.gnome.org/gio/stable/extending-gio.html (G_TLS_BACKEND_EXTENSION_POINT_NAME)
// https://developer.gnome.org/gio/stable/gio-Extension-Points.html
// https://developer.gnome.org/gio/stable/gio-querymodules.html
#include <giomm.h>
#include <iostream>
#include <cstdlib>
bool on_accept_certificate(const Glib::RefPtr<const Gio::TlsCertificate>& cert, Gio::TlsCertificateFlags)
{
std::cout << "Handshake is ocurring." << std::endl
<< "The server is requesting that its certificate be accepted." <<
std::endl;
std::cout << "Outputing certificate data:" << std::endl <<
cert->property_certificate_pem().get_value();
auto issuer = cert->get_issuer();
std::cout << "Outputing the issuer's certificate data:" << std::endl <<
issuer->property_certificate_pem().get_value();
std::cout << "Accepting the certificate (completing the handshake)." <<
std::endl;
return true;
}
int main(int, char**)
{
Gio::init();
const Glib::ustring test_host = "www.google.com";
std::vector< Glib::RefPtr<Gio::InetAddress> > inet_addresses;
try
{
inet_addresses =
Gio::Resolver::get_default()->lookup_by_name(test_host);
}
catch(const Gio::ResolverError& ex)
{
//This happens if it could not resolve the name,
//for instance if we are not connected to the internet.
//TODO: Change this test so it can do something useful and succeed even
//if the testing computer is not connected to the internet.
std::cerr << "Gio::Resolver::lookup_by_name() threw exception: " << ex.what() << std::endl;
return EXIT_FAILURE;
}
//Actually, it would throw an exception instead of reaching here with 0 addresses resolved.
if(inet_addresses.size() == 0)
{
std::cerr << "Could not resolve test host '" << test_host << "'." <<
std::endl;
return EXIT_FAILURE;
}
std::cout << "Successfully resolved address of test host '" << test_host <<
"'." << std::endl;
auto first_inet_address = inet_addresses[0];
std::cout << "First address of test host is " <<
first_inet_address->to_string() << "." << std::endl;
auto socket =
Gio::Socket::create(first_inet_address->get_family(),
Gio::SOCKET_TYPE_STREAM, Gio::SOCKET_PROTOCOL_TCP);
auto address =
Gio::InetSocketAddress::create(first_inet_address, 443);
try
{
socket->connect(address);
}
catch(const Gio::Error& ex)
{
std::cout << "Could not connect socket to " <<
address->get_address()->to_string() << ":" << address->get_port() <<
". Exception: " << ex.what() << std::endl;
return EXIT_FAILURE;
}
if(!socket->is_connected())
{
std::cout << "Could not connect socket to " <<
address->get_address()->to_string() << ":" << address->get_port() <<
"." << std::endl;
}
auto conn = Glib::RefPtr<Gio::TcpConnection>::cast_dynamic(Gio::SocketConnection::create(socket));
if(!conn || !conn->is_connected())
{
std::cout << "Could not establish connection to " <<
address->get_address()->to_string() << ":" << address->get_port() <<
"." << std::endl;
socket->close();
return EXIT_FAILURE;
}
std::cout << "Successfully established connection to " <<
address->get_address()->to_string() << ":" << address->get_port() <<
"." << std::endl;
try
{
auto tls_connection =
Gio::TlsClientConnection::create(conn, address);
tls_connection->signal_accept_certificate().connect(
sigc::ptr_fun(&on_accept_certificate));
tls_connection->handshake();
std::cout << "Attempting to get the issuer's certificate from the "
"connection." << std::endl;
auto issuer_certificate =
tls_connection->get_peer_certificate()->get_issuer();
if(!issuer_certificate)
{
std::cout << "Could not get the issuer's certificate of the peer." <<
std::endl;
return EXIT_FAILURE;
}
std::cout << "Successfully retrieved the issuer's certificate." <<
std::endl;
std::cout << "Attempting to use the connection's database." << std::endl;
auto database = tls_connection->get_database();
std::cout << "Looking up the certificate's issuer in the database." <<
std::endl;
auto db_certificate =
database->lookup_certificate_issuer(issuer_certificate);
if(!db_certificate)
{
std::cout << "The issuer's certificate was not found in the database." << std::endl;
}
else
{
std::cout << "Successfully found the issuer's certificate in the database." << std::endl;
}
}
catch (const Gio::TlsError& error)
{
std::cout << "Exception caught: " << error.what() << "." << std::endl;
return EXIT_FAILURE;
}
conn->close();
return EXIT_SUCCESS;
}
<commit_msg>tls_client test: Use gnome.org instead of google.org<commit_after>// This test case fails unless an implementation of TLS backend is installed.
// (Exception caught: TLS support is not available.)
// Module glib-networking implements TLS backend.
//
// Even if glib-networking is installed, it's possible that glib does not find it.
// That's very probable if glib and glib-networking are installed with different
// directory prefixes, e.g. glib in /opt/gnome and glib-networking in /usr.
// You can fix that by setting the GIO_EXTRA_MODULES environment variable to
// the directory to search for implementations of gio extension points.
// Example:
// export GIO_EXTRA_MODULES=/usr/lib/x86_64-linux-gnu/gio/modules
// If you don't know where the implementations of gio extension points are stored,
// search for a file named giomodule.cache.
//
// https://developer.gnome.org/gio/stable/extending-gio.html (G_TLS_BACKEND_EXTENSION_POINT_NAME)
// https://developer.gnome.org/gio/stable/gio-Extension-Points.html
// https://developer.gnome.org/gio/stable/gio-querymodules.html
#include <giomm.h>
#include <iostream>
#include <cstdlib>
bool on_accept_certificate(const Glib::RefPtr<const Gio::TlsCertificate>& cert, Gio::TlsCertificateFlags)
{
std::cout << "Handshake is ocurring." << std::endl
<< "The server is requesting that its certificate be accepted." <<
std::endl;
std::cout << "Outputing certificate data:" << std::endl <<
cert->property_certificate_pem().get_value();
auto issuer = cert->get_issuer();
std::cout << "Outputing the issuer's certificate data:" << std::endl <<
issuer->property_certificate_pem().get_value();
std::cout << "Accepting the certificate (completing the handshake)." <<
std::endl;
return true;
}
int main(int, char**)
{
Gio::init();
const Glib::ustring test_host = "www.gnome.org";
std::vector< Glib::RefPtr<Gio::InetAddress> > inet_addresses;
try
{
inet_addresses =
Gio::Resolver::get_default()->lookup_by_name(test_host);
}
catch(const Gio::ResolverError& ex)
{
//This happens if it could not resolve the name,
//for instance if we are not connected to the internet.
//TODO: Change this test so it can do something useful and succeed even
//if the testing computer is not connected to the internet.
std::cerr << "Gio::Resolver::lookup_by_name() threw exception: " << ex.what() << std::endl;
return EXIT_FAILURE;
}
//Actually, it would throw an exception instead of reaching here with 0 addresses resolved.
if(inet_addresses.size() == 0)
{
std::cerr << "Could not resolve test host '" << test_host << "'." <<
std::endl;
return EXIT_FAILURE;
}
std::cout << "Successfully resolved address of test host '" << test_host <<
"'." << std::endl;
auto first_inet_address = inet_addresses[0];
std::cout << "First address of test host is " <<
first_inet_address->to_string() << "." << std::endl;
auto socket =
Gio::Socket::create(first_inet_address->get_family(),
Gio::SOCKET_TYPE_STREAM, Gio::SOCKET_PROTOCOL_TCP);
auto address =
Gio::InetSocketAddress::create(first_inet_address, 443);
try
{
socket->connect(address);
}
catch(const Gio::Error& ex)
{
std::cout << "Could not connect socket to " <<
address->get_address()->to_string() << ":" << address->get_port() <<
". Exception: " << ex.what() << std::endl;
return EXIT_FAILURE;
}
if(!socket->is_connected())
{
std::cout << "Could not connect socket to " <<
address->get_address()->to_string() << ":" << address->get_port() <<
"." << std::endl;
}
auto conn = Glib::RefPtr<Gio::TcpConnection>::cast_dynamic(Gio::SocketConnection::create(socket));
if(!conn || !conn->is_connected())
{
std::cout << "Could not establish connection to " <<
address->get_address()->to_string() << ":" << address->get_port() <<
"." << std::endl;
socket->close();
return EXIT_FAILURE;
}
std::cout << "Successfully established connection to " <<
address->get_address()->to_string() << ":" << address->get_port() <<
"." << std::endl;
try
{
auto tls_connection =
Gio::TlsClientConnection::create(conn, address);
tls_connection->signal_accept_certificate().connect(
sigc::ptr_fun(&on_accept_certificate));
tls_connection->handshake();
std::cout << "Attempting to get the issuer's certificate from the "
"connection." << std::endl;
auto issuer_certificate =
tls_connection->get_peer_certificate()->get_issuer();
if(!issuer_certificate)
{
std::cout << "Could not get the issuer's certificate of the peer." <<
std::endl;
return EXIT_FAILURE;
}
std::cout << "Successfully retrieved the issuer's certificate." <<
std::endl;
std::cout << "Attempting to use the connection's database." << std::endl;
auto database = tls_connection->get_database();
std::cout << "Looking up the certificate's issuer in the database." <<
std::endl;
auto db_certificate =
database->lookup_certificate_issuer(issuer_certificate);
if(!db_certificate)
{
std::cout << "The issuer's certificate was not found in the database." << std::endl;
}
else
{
std::cout << "Successfully found the issuer's certificate in the database." << std::endl;
}
}
catch (const Gio::TlsError& error)
{
std::cout << "Exception caught: " << error.what() << "." << std::endl;
return EXIT_FAILURE;
}
conn->close();
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: filprp.cxx,v $
*
* $Revision: 1.1 $
*
* last change: $Author: kso $ $Date: 2000-10-16 14:53:36 $
*
* 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 _SHELL_HXX_
#include "shell.hxx"
#endif
#ifndef _PROV_HXX_
#include "prov.hxx"
#endif
#ifndef _FILPRP_HXX_
#include "filprp.hxx"
#endif
using namespace fileaccess;
using namespace com::sun::star;
using namespace com::sun::star::ucb;
#ifndef _FILINL_HXX_
#include "filinl.hxx"
#endif
XPropertySetInfo_impl::XPropertySetInfo_impl( shell* pMyShell,const rtl::OUString& aUnqPath )
: m_pMyShell( pMyShell ),
m_xProvider( pMyShell->m_pProvider ),
m_count( 0 ),
m_seq( 0 )
{
shell::ContentMap::iterator it = m_pMyShell->m_aContent.find( aUnqPath );
shell::PropertySet& properties = *(it->second.properties);
shell::PropertySet::iterator it1 = properties.begin();
m_seq.realloc( properties.size() );
while( it1 != properties.end() )
{
m_seq[ m_count++ ] = beans::Property( it1->getPropertyName(),
it1->getHandle(),
it1->getType(),
it1->getAttributes() );
++it1;
}
}
XPropertySetInfo_impl::XPropertySetInfo_impl( shell* pMyShell,const uno::Sequence< beans::Property >& seq )
: m_pMyShell( pMyShell ),
m_count( seq.getLength() ),
m_seq( seq )
{
}
XPropertySetInfo_impl::~XPropertySetInfo_impl()
{
m_pMyShell->m_pProvider->release();
}
void SAL_CALL
XPropertySetInfo_impl::acquire(
void )
throw( uno::RuntimeException )
{
OWeakObject::acquire();
}
void SAL_CALL
XPropertySetInfo_impl::release(
void )
throw( uno::RuntimeException )
{
OWeakObject::release();
}
uno::Any SAL_CALL
XPropertySetInfo_impl::queryInterface(
const uno::Type& rType )
throw( uno::RuntimeException )
{
uno::Any aRet = cppu::queryInterface( rType,
SAL_STATIC_CAST( beans::XPropertySetInfo*,this) );
return aRet.hasValue() ? aRet : OWeakObject::queryInterface( rType );
}
beans::Property SAL_CALL
XPropertySetInfo_impl::getPropertyByName(
const rtl::OUString& aName )
throw( beans::UnknownPropertyException,
uno::RuntimeException)
{
for( sal_Int32 i = 0; i < m_seq.getLength(); ++i )
if( m_seq[i].Name == aName ) return m_seq[i];
throw beans::UnknownPropertyException();
}
uno::Sequence< beans::Property > SAL_CALL
XPropertySetInfo_impl::getProperties(
void )
throw( uno::RuntimeException )
{
return m_seq;
}
sal_Bool SAL_CALL
XPropertySetInfo_impl::hasPropertyByName(
const rtl::OUString& aName )
throw( uno::RuntimeException )
{
for( sal_Int32 i = 0; i < m_seq.getLength(); ++i )
if( m_seq[i].Name == aName ) return true;
return false;
}
<commit_msg>Added missing acquire() of shell to XPropertySetInfo_impl ctors.<commit_after>/*************************************************************************
*
* $RCSfile: filprp.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: sb $ $Date: 2000-10-24 13:15:23 $
*
* 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 _SHELL_HXX_
#include "shell.hxx"
#endif
#ifndef _PROV_HXX_
#include "prov.hxx"
#endif
#ifndef _FILPRP_HXX_
#include "filprp.hxx"
#endif
using namespace fileaccess;
using namespace com::sun::star;
using namespace com::sun::star::ucb;
#ifndef _FILINL_HXX_
#include "filinl.hxx"
#endif
XPropertySetInfo_impl::XPropertySetInfo_impl( shell* pMyShell,const rtl::OUString& aUnqPath )
: m_pMyShell( pMyShell ),
m_xProvider( pMyShell->m_pProvider ),
m_count( 0 ),
m_seq( 0 )
{
m_pMyShell->m_pProvider->acquire();
shell::ContentMap::iterator it = m_pMyShell->m_aContent.find( aUnqPath );
shell::PropertySet& properties = *(it->second.properties);
shell::PropertySet::iterator it1 = properties.begin();
m_seq.realloc( properties.size() );
while( it1 != properties.end() )
{
m_seq[ m_count++ ] = beans::Property( it1->getPropertyName(),
it1->getHandle(),
it1->getType(),
it1->getAttributes() );
++it1;
}
}
XPropertySetInfo_impl::XPropertySetInfo_impl( shell* pMyShell,const uno::Sequence< beans::Property >& seq )
: m_pMyShell( pMyShell ),
m_count( seq.getLength() ),
m_seq( seq )
{
m_pMyShell->m_pProvider->acquire();
}
XPropertySetInfo_impl::~XPropertySetInfo_impl()
{
m_pMyShell->m_pProvider->release();
}
void SAL_CALL
XPropertySetInfo_impl::acquire(
void )
throw( uno::RuntimeException )
{
OWeakObject::acquire();
}
void SAL_CALL
XPropertySetInfo_impl::release(
void )
throw( uno::RuntimeException )
{
OWeakObject::release();
}
uno::Any SAL_CALL
XPropertySetInfo_impl::queryInterface(
const uno::Type& rType )
throw( uno::RuntimeException )
{
uno::Any aRet = cppu::queryInterface( rType,
SAL_STATIC_CAST( beans::XPropertySetInfo*,this) );
return aRet.hasValue() ? aRet : OWeakObject::queryInterface( rType );
}
beans::Property SAL_CALL
XPropertySetInfo_impl::getPropertyByName(
const rtl::OUString& aName )
throw( beans::UnknownPropertyException,
uno::RuntimeException)
{
for( sal_Int32 i = 0; i < m_seq.getLength(); ++i )
if( m_seq[i].Name == aName ) return m_seq[i];
throw beans::UnknownPropertyException();
}
uno::Sequence< beans::Property > SAL_CALL
XPropertySetInfo_impl::getProperties(
void )
throw( uno::RuntimeException )
{
return m_seq;
}
sal_Bool SAL_CALL
XPropertySetInfo_impl::hasPropertyByName(
const rtl::OUString& aName )
throw( uno::RuntimeException )
{
for( sal_Int32 i = 0; i < m_seq.getLength(); ++i )
if( m_seq[i].Name == aName ) return true;
return false;
}
<|endoftext|>
|
<commit_before>/* bzflag
* Copyright (c) 1993 - 2005 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 MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/* interface header */
#include "AdnsHandler.h"
/* system implementation headers */
#include <errno.h>
/* common implementation headers */
#include "network.h"
#ifdef HAVE_ADNS_H
adns_state AdnsHandler::adnsState;
AdnsHandler::AdnsHandler(int _index, struct sockaddr *clientAddr)
: index(_index), hostname(NULL), adnsQuery(NULL), status(None) {
// launch the asynchronous query to look up this hostname
if (adns_submit_reverse
(adnsState, clientAddr, adns_r_ptr,
(adns_queryflags)(adns_qf_quoteok_cname|adns_qf_cname_loose), 0,
&adnsQuery) != 0) {
DEBUG1("Player [%d] failed to submit reverse resolve query: errno %d\n",
index, getErrno());
adnsQuery = NULL;
status = Failed;
} else {
DEBUG2("Player [%d] submitted reverse resolve query\n", index);
status = Pending;
}
}
AdnsHandler::~AdnsHandler() {
if (adnsQuery) {
adns_cancel(adnsQuery);
adnsQuery = NULL;
}
if (hostname) {
free(hostname);
hostname = NULL;
}
}
void AdnsHandler::checkDNSResolution() {
if (!adnsQuery)
return;
// check to see if query has completed
adns_answer *answer;
if (adns_check(adnsState, &adnsQuery, &answer, 0) != 0) {
if (getErrno() != EAGAIN) {
DEBUG1("Player [%d] failed to resolve: errno %d\n", index, getErrno());
adnsQuery = NULL;
status = Failed;
}
return;
}
// we got our reply.
if (answer->status != adns_s_ok) {
DEBUG1("Player [%d] got bad status from resolver: %s\n", index,
adns_strerror(answer->status));
free(answer);
adnsQuery = NULL;
status = Failed;
return;
}
if (hostname)
free(hostname); // shouldn't happen, but just in case
hostname = strdup(*answer->rrs.str);
DEBUG1("Player [%d] resolved to hostname: %s\n", index, hostname);
free(answer);
adnsQuery = NULL;
status = Succeeded;
return;
}
const char *AdnsHandler::getHostname() {
if (status == Pending) {
checkDNSResolution();
}
return hostname;
}
void AdnsHandler::startupResolver() {
/* start up our resolver if we have ADNS */
if (adns_init(&adnsState, adns_if_nosigpipe, 0) < 0) {
perror("ADNS init failed");
exit(1);
}
}
#endif
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>only return hostname if lookup has succeeded<commit_after>/* bzflag
* Copyright (c) 1993 - 2005 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 MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/* interface header */
#include "AdnsHandler.h"
/* system implementation headers */
#include <errno.h>
/* common implementation headers */
#include "network.h"
#ifdef HAVE_ADNS_H
adns_state AdnsHandler::adnsState;
AdnsHandler::AdnsHandler(int _index, struct sockaddr *clientAddr)
: index(_index), hostname(NULL), adnsQuery(NULL), status(None) {
// launch the asynchronous query to look up this hostname
if (adns_submit_reverse
(adnsState, clientAddr, adns_r_ptr,
(adns_queryflags)(adns_qf_quoteok_cname|adns_qf_cname_loose), 0,
&adnsQuery) != 0) {
DEBUG1("Player [%d] failed to submit reverse resolve query: errno %d\n",
index, getErrno());
adnsQuery = NULL;
status = Failed;
} else {
DEBUG2("Player [%d] submitted reverse resolve query\n", index);
status = Pending;
}
}
AdnsHandler::~AdnsHandler() {
if (adnsQuery) {
adns_cancel(adnsQuery);
adnsQuery = NULL;
}
if (hostname) {
free(hostname);
hostname = NULL;
}
}
void AdnsHandler::checkDNSResolution() {
if (!adnsQuery)
return;
// check to see if query has completed
adns_answer *answer;
if (adns_check(adnsState, &adnsQuery, &answer, 0) != 0) {
if (getErrno() != EAGAIN) {
DEBUG1("Player [%d] failed to resolve: errno %d\n", index, getErrno());
adnsQuery = NULL;
status = Failed;
}
return;
}
// we got our reply.
if (answer->status != adns_s_ok) {
DEBUG1("Player [%d] got bad status from resolver: %s\n", index,
adns_strerror(answer->status));
free(answer);
adnsQuery = NULL;
status = Failed;
return;
}
if (hostname)
free(hostname); // shouldn't happen, but just in case
hostname = strdup(*answer->rrs.str);
DEBUG1("Player [%d] resolved to hostname: %s\n", index, hostname);
free(answer);
adnsQuery = NULL;
status = Succeeded;
return;
}
const char *AdnsHandler::getHostname() {
if (status == Pending) {
checkDNSResolution();
}
if (status == Succeeded)
return hostname;
return NULL;
}
void AdnsHandler::startupResolver() {
/* start up our resolver if we have ADNS */
if (adns_init(&adnsState, adns_if_nosigpipe, 0) < 0) {
perror("ADNS init failed");
exit(1);
}
}
#endif
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|>
|
<commit_before>// request.cpp
//
#include "request.h"
#include "requestfields.h"
#include "player.h"
#include "event/types.h"
#include "network/response.h"
#include <string>
namespace xim {
namespace network {
using namespace xim::event;
/*
* Excerpt from the Official Unwrittten Boostcraft Style Guide:
*
* Preprocessor Macros
* -------------------
* These are to be eschewed whenever there is a reasonable alternative. Macros
* have many pitfalls, including obfuscation of source code and loss of type
* safety. If there's a way to accomplish your goal without using macros, don't
* use macros.
*
* Here are some great things to NOT use macros for:
*
* Preprocessor Macro Use Punishment
* ---------------------------------------------------------------------------
* #defining constants Slap on the wrist
* "Inlining" function-like code That's a paddling
* Hiding ugly code Twenty lashes
* Generic programming Waterboarding
* Implementing mini-DSLs in the preprocessor Firing squad
*
* That said, sometimes using macros can really improve the readability and
* maintainability of a piece of code. When that happens, and there's not any
* obvious way of refactoring the code to obviate the need for macros, just use
* some macros rather than write ugly code.
*
* So, with that in mind...
*/
/**
* Ugly code-hiding mini-DSL for packet field specs!
*
* These macros ease the definition of data layouts for request packets. They
* can only be used in the body of Request subclasses.
*
* BEGIN_FIELDS Marks the start of fields section in a Request class.
* END_FIELDS REQUIRED to end the fields section.
* BYTE,SHORT,ETC. Binds a member variable of the class to a typed position
* in the packet's data layout.
*
* Example:
*
* struct SomePacket : public Request {
* int32_t theNumber;
* std::string theString;
* BEGIN_FIELDS
* INT (theNumber)
* STRING_UTF8 (theString)
* END_FIELDS
* };
*/
#define BEGIN_FIELDS size_t read(boost::asio::streambuf & buf) \
{ \
int cur_field = 0; \
#define FIELD(type,v) if (this->fields_read_ == cur_field++) { \
size_t needed = type(buf, v); \
if (needed) \
return needed; \
else \
++this->fields_read_; \
}
#define END_FIELDS return 0; \
}
#define BOOLEAN(v) FIELD(readBool, v)
#define BYTE(v) FIELD(readByte, v)
#define SHORT(v) FIELD(readShort, v)
#define INT(v) FIELD(readInt, v)
#define LONG(v) FIELD(readLong, v)
#define FLOAT(v) FIELD(readFloat, v)
#define DOUBLE(v) FIELD(readDouble, v)
#define STRING_UTF8(v) FIELD(readStringUtf8, v)
#define STRING_UCS2(v) FIELD(readStringUcs2, v)
namespace packets {
/*
* 0x00 KEEP ALIVE
*/
struct KeepAlive : public Request
{
size_t read(boost::asio::streambuf&) { return 0; }
void dispatch(player_ptr p) const
{
// No event dispatch on keepalive; just ping back
p->deliver(keepalive());
}
};
/*
* 0x01 LOGIN REQUEST
*/
struct LoginRequest : public Request
{
int32_t version;
std::string username;
int64_t seed;
int8_t dimension;
BEGIN_FIELDS
INT (version)
STRING_UCS2 (username)
LONG (seed)
BYTE (dimension)
END_FIELDS
void dispatch(player_ptr p) const
{
LoginRequestEvent e(p, username, version);
async_fire(e);
}
};
/*
* 0x02 HANDSHAKE
*/
struct Handshake : public Request
{
std::string username;
BEGIN_FIELDS
STRING_UCS2 (username)
END_FIELDS
void dispatch(player_ptr p) const
{
p->handshake(username);
}
};
/*
* 0x03 CHAT MESSAGE
*/
struct ChatMessage : public Request
{
std::string message;
BEGIN_FIELDS
STRING_UCS2 (message)
END_FIELDS
void dispatch(player_ptr p) const
{
ChatEvent e(p, message);
async_fire(e);
}
};
/*
* 0x07 USE ENTITY
*/
struct UseEntity : public Request
{
int32_t user;
int32_t target;
bool leftclick;
BEGIN_FIELDS
INT (user)
INT (target)
BOOLEAN (leftclick)
END_FIELDS
void dispatch(player_ptr p) const
{
// TODO: implement dispatch
}
};
/*
* 0x09 RESPAWN
*/
struct Respawn : public Request
{
int8_t world;
BEGIN_FIELDS
BYTE (world)
END_FIELDS
void dispatch(player_ptr p) const
{
// TODO: respawn event
}
};
/*
* 0x0A PLAYER ONGROUND
*/
struct PlayerOnGround : public Request
{
bool onground;
BEGIN_FIELDS
BOOLEAN (onground)
END_FIELDS
void dispatch(player_ptr p) const
{
PlayerOnGroundEvent e(p, onground);
async_fire(e);
}
};
/*
* 0x0B PLAYER POSITION
*/
struct PlayerPosition : public Request
{
double x, y, z, stance;
bool onground;
BEGIN_FIELDS
DOUBLE (x)
DOUBLE (y)
DOUBLE (stance)
DOUBLE (z)
BOOLEAN (onground)
END_FIELDS
void dispatch(player_ptr p) const
{
p->updatePosition({x, z, y});
PlayerOnGroundEvent g(p, onground);
async_fire(g);
PlayerPositionEvent e(p, {x, z, y});
async_fire(e);
}
};
/*
* 0x0C PLAYER LOOK
*/
struct PlayerLook : public Request
{
float pitch, yaw;
bool onground;
BEGIN_FIELDS
FLOAT (yaw)
FLOAT (pitch)
BOOLEAN (onground)
END_FIELDS
void dispatch(player_ptr p) const
{
PlayerOnGroundEvent g(p, onground);
async_fire(g);
PlayerLookEvent e(p, yaw, pitch);
async_fire(e);
}
};
/*
* 0x0D PLAYER POSITION AND LOOK
*/
struct PlayerPositionAndLook : public Request
{
double x, y, z, stance;
float pitch, yaw;
bool onground;
BEGIN_FIELDS
DOUBLE (x)
DOUBLE (y)
DOUBLE (stance)
DOUBLE (z)
FLOAT (yaw)
FLOAT (pitch)
BOOLEAN (onground)
END_FIELDS
void dispatch(player_ptr p) const
{
p->updatePosition({x, z, y});
PlayerOnGroundEvent g(p, onground);
async_fire(g);
PlayerLookEvent l(p, yaw, pitch);
async_fire(l);
PlayerPositionEvent e(p, {x, z, y});
async_fire(e);
}
};
/*
* 0x0E PLAYER DIGGING
*/
struct Digging : public Request
{
int8_t status;
int32_t x;
int8_t y;
int32_t z;
int8_t face;
BEGIN_FIELDS
BYTE (status)
INT (x)
BYTE (y)
INT (z)
BYTE (face)
END_FIELDS
void dispatch(player_ptr p) const
{
if (status == 0)
p->deliver(chatmessage("I'm a dwarf and I'm digging a hole!"));
else if (status == 2)
p->deliver(chatmessage("Diggy diggy hole!"));
else if (status == 4)
p->deliver(chatmessage("Give a hoot; don't pollute!"));
}
};
/*
* 0x0F PLAYER BLOCK PLACEMENT
*/
struct BlockPlacement : public Request
{
int32_t x, z;
int8_t y;
int8_t direction;
int16_t itemid;
int8_t amount;
int16_t damage;
BEGIN_FIELDS
INT (x)
BYTE (y)
INT (z)
BYTE (direction)
SHORT (itemid)
if (itemid != -1) {
BYTE (amount)
SHORT (damage)
}
END_FIELDS
void dispatch(player_ptr p) const
{
}
};
/*
* 0x10 HOLDING CHANGE
*/
struct HoldingChange : public Request
{
int16_t slot;
BEGIN_FIELDS
SHORT (slot)
END_FIELDS
void dispatch(player_ptr p) const
{
// TODO: implement dispatch
Response r;
r << (int8_t)0x36;
r << (int32_t)0 << (int16_t)1 << (int32_t)0;
r << (int8_t)0 << (int8_t)16;
p->deliver(r);
}
};
/*
* 0x12 ENTITY ANIMATION
*/
struct Animation : public Request
{
int32_t eid;
int8_t anim;
BEGIN_FIELDS
INT (eid)
BYTE (anim)
END_FIELDS
void dispatch(player_ptr p) const
{
// TODO: implement dispatch
}
};
/*
* 0x13 STANCE CHANGE
*/
struct Stance : public Request
{
int32_t eid;
int8_t action; // 1 = crouch, 2 = uncrouch, 3 = leave bed
BEGIN_FIELDS
INT (eid)
BYTE (action)
END_FIELDS
void dispatch(player_ptr p) const
{
// TODO: implement dispatch
}
};
/*
* 0x65 CLOSE WINDOW
*/
struct CloseWindow : public Request
{
int8_t windowid;
BEGIN_FIELDS
BYTE (windowid)
END_FIELDS
void dispatch(player_ptr p) const
{
// TODO: implement dispatch
}
};
/*
* 0x66 WINDOW CLICK
*/
struct ClickWindow : public Request
{
int8_t windowid;
int16_t slot;
bool rclick;
bool shift;
int16_t actionid;
int16_t itemid;
int8_t itemcount;
int16_t itemuses;
BEGIN_FIELDS
BYTE (windowid)
SHORT (slot)
BOOLEAN (rclick)
SHORT (actionid)
BOOLEAN (shift)
SHORT (itemid)
if (itemid != -1)
{
BYTE (itemcount)
SHORT (itemuses)
}
END_FIELDS
void dispatch(player_ptr p) const
{
// TODO: implement dispatch
}
};
/*
* 0xFF DISCONNECT
*/
struct Disconnect : public Request
{
std::string message;
BEGIN_FIELDS
STRING_UCS2 (message)
END_FIELDS
void dispatch(player_ptr p) const
{
p->stop(message);
}
};
} // namespace packets
#define REQUEST_CASE(num, type) case num: return ptr(new type());
std::unique_ptr<Request> makerequest(int type)
{
typedef std::unique_ptr<Request> ptr;
using namespace packets;
switch(type)
{
REQUEST_CASE(0x00, KeepAlive)
REQUEST_CASE(0x01, LoginRequest)
REQUEST_CASE(0x02, Handshake)
REQUEST_CASE(0x03, ChatMessage)
REQUEST_CASE(0x07, UseEntity)
REQUEST_CASE(0x09, Respawn)
REQUEST_CASE(0x0A, PlayerOnGround)
REQUEST_CASE(0x0B, PlayerPosition)
REQUEST_CASE(0x0C, PlayerLook)
REQUEST_CASE(0x0D, PlayerPositionAndLook)
REQUEST_CASE(0x0E, Digging)
REQUEST_CASE(0x0F, BlockPlacement)
REQUEST_CASE(0x10, HoldingChange)
REQUEST_CASE(0x12, Animation)
REQUEST_CASE(0x13, Stance)
REQUEST_CASE(0x65, CloseWindow)
REQUEST_CASE(0x66, ClickWindow)
REQUEST_CASE(0xFF, Disconnect)
default:
{
std::stringstream ss;
ss << "Unrecognized packet ID " << std::hex << type;
throw std::runtime_error(ss.str());
}
}
}
}} // namespace xim::network
<commit_msg>Store player's yaw and pitch<commit_after>// request.cpp
//
#include "request.h"
#include "requestfields.h"
#include "player.h"
#include "event/types.h"
#include "network/response.h"
#include <string>
namespace xim {
namespace network {
using namespace xim::event;
/*
* Excerpt from the Official Unwrittten Boostcraft Style Guide:
*
* Preprocessor Macros
* -------------------
* These are to be eschewed whenever there is a reasonable alternative. Macros
* have many pitfalls, including obfuscation of source code and loss of type
* safety. If there's a way to accomplish your goal without using macros, don't
* use macros.
*
* Here are some great things to NOT use macros for:
*
* Preprocessor Macro Use Punishment
* ---------------------------------------------------------------------------
* #defining constants Slap on the wrist
* "Inlining" function-like code That's a paddling
* Hiding ugly code Twenty lashes
* Generic programming Waterboarding
* Implementing mini-DSLs in the preprocessor Firing squad
*
* That said, sometimes using macros can really improve the readability and
* maintainability of a piece of code. When that happens, and there's not any
* obvious way of refactoring the code to obviate the need for macros, just use
* some macros rather than write ugly code.
*
* So, with that in mind...
*/
/**
* Ugly code-hiding mini-DSL for packet field specs!
*
* These macros ease the definition of data layouts for request packets. They
* can only be used in the body of Request subclasses.
*
* BEGIN_FIELDS Marks the start of fields section in a Request class.
* END_FIELDS REQUIRED to end the fields section.
* BYTE,SHORT,ETC. Binds a member variable of the class to a typed position
* in the packet's data layout.
*
* Example:
*
* struct SomePacket : public Request {
* int32_t theNumber;
* std::string theString;
* BEGIN_FIELDS
* INT (theNumber)
* STRING_UTF8 (theString)
* END_FIELDS
* };
*/
#define BEGIN_FIELDS size_t read(boost::asio::streambuf & buf) \
{ \
int cur_field = 0; \
#define FIELD(type,v) if (this->fields_read_ == cur_field++) { \
size_t needed = type(buf, v); \
if (needed) \
return needed; \
else \
++this->fields_read_; \
}
#define END_FIELDS return 0; \
}
#define BOOLEAN(v) FIELD(readBool, v)
#define BYTE(v) FIELD(readByte, v)
#define SHORT(v) FIELD(readShort, v)
#define INT(v) FIELD(readInt, v)
#define LONG(v) FIELD(readLong, v)
#define FLOAT(v) FIELD(readFloat, v)
#define DOUBLE(v) FIELD(readDouble, v)
#define STRING_UTF8(v) FIELD(readStringUtf8, v)
#define STRING_UCS2(v) FIELD(readStringUcs2, v)
namespace packets {
/*
* 0x00 KEEP ALIVE
*/
struct KeepAlive : public Request
{
size_t read(boost::asio::streambuf&) { return 0; }
void dispatch(player_ptr p) const
{
// No event dispatch on keepalive; just ping back
p->deliver(keepalive());
}
};
/*
* 0x01 LOGIN REQUEST
*/
struct LoginRequest : public Request
{
int32_t version;
std::string username;
int64_t seed;
int8_t dimension;
BEGIN_FIELDS
INT (version)
STRING_UCS2 (username)
LONG (seed)
BYTE (dimension)
END_FIELDS
void dispatch(player_ptr p) const
{
LoginRequestEvent e(p, username, version);
async_fire(e);
}
};
/*
* 0x02 HANDSHAKE
*/
struct Handshake : public Request
{
std::string username;
BEGIN_FIELDS
STRING_UCS2 (username)
END_FIELDS
void dispatch(player_ptr p) const
{
p->handshake(username);
}
};
/*
* 0x03 CHAT MESSAGE
*/
struct ChatMessage : public Request
{
std::string message;
BEGIN_FIELDS
STRING_UCS2 (message)
END_FIELDS
void dispatch(player_ptr p) const
{
ChatEvent e(p, message);
async_fire(e);
}
};
/*
* 0x07 USE ENTITY
*/
struct UseEntity : public Request
{
int32_t user;
int32_t target;
bool leftclick;
BEGIN_FIELDS
INT (user)
INT (target)
BOOLEAN (leftclick)
END_FIELDS
void dispatch(player_ptr p) const
{
// TODO: implement dispatch
}
};
/*
* 0x09 RESPAWN
*/
struct Respawn : public Request
{
int8_t world;
BEGIN_FIELDS
BYTE (world)
END_FIELDS
void dispatch(player_ptr p) const
{
// TODO: respawn event
}
};
/*
* 0x0A PLAYER ONGROUND
*/
struct PlayerOnGround : public Request
{
bool onground;
BEGIN_FIELDS
BOOLEAN (onground)
END_FIELDS
void dispatch(player_ptr p) const
{
PlayerOnGroundEvent e(p, onground);
async_fire(e);
}
};
/*
* 0x0B PLAYER POSITION
*/
struct PlayerPosition : public Request
{
double x, y, z, stance;
bool onground;
BEGIN_FIELDS
DOUBLE (x)
DOUBLE (y)
DOUBLE (stance)
DOUBLE (z)
BOOLEAN (onground)
END_FIELDS
void dispatch(player_ptr p) const
{
p->updatePosition({x, z, y});
PlayerOnGroundEvent g(p, onground);
async_fire(g);
PlayerPositionEvent e(p, {x, z, y});
async_fire(e);
}
};
/*
* 0x0C PLAYER LOOK
*/
struct PlayerLook : public Request
{
float pitch, yaw;
bool onground;
BEGIN_FIELDS
FLOAT (yaw)
FLOAT (pitch)
BOOLEAN (onground)
END_FIELDS
void dispatch(player_ptr p) const
{
p->updateLook(yaw, pitch);
PlayerOnGroundEvent g(p, onground);
async_fire(g);
PlayerLookEvent e(p, yaw, pitch);
async_fire(e);
}
};
/*
* 0x0D PLAYER POSITION AND LOOK
*/
struct PlayerPositionAndLook : public Request
{
double x, y, z, stance;
float pitch, yaw;
bool onground;
BEGIN_FIELDS
DOUBLE (x)
DOUBLE (y)
DOUBLE (stance)
DOUBLE (z)
FLOAT (yaw)
FLOAT (pitch)
BOOLEAN (onground)
END_FIELDS
void dispatch(player_ptr p) const
{
p->updatePosition({x, z, y});
p->updateLook(yaw, pitch);
PlayerOnGroundEvent g(p, onground);
async_fire(g);
PlayerLookEvent l(p, yaw, pitch);
async_fire(l);
PlayerPositionEvent e(p, {x, z, y});
async_fire(e);
}
};
/*
* 0x0E PLAYER DIGGING
*/
struct Digging : public Request
{
int8_t status;
int32_t x;
int8_t y;
int32_t z;
int8_t face;
BEGIN_FIELDS
BYTE (status)
INT (x)
BYTE (y)
INT (z)
BYTE (face)
END_FIELDS
void dispatch(player_ptr p) const
{
if (status == 0)
p->deliver(chatmessage("I'm a dwarf and I'm digging a hole!"));
else if (status == 2)
p->deliver(chatmessage("Diggy diggy hole!"));
else if (status == 4)
p->deliver(chatmessage("Give a hoot; don't pollute!"));
}
};
/*
* 0x0F PLAYER BLOCK PLACEMENT
*/
struct BlockPlacement : public Request
{
int32_t x, z;
int8_t y;
int8_t direction;
int16_t itemid;
int8_t amount;
int16_t damage;
BEGIN_FIELDS
INT (x)
BYTE (y)
INT (z)
BYTE (direction)
SHORT (itemid)
if (itemid != -1) {
BYTE (amount)
SHORT (damage)
}
END_FIELDS
void dispatch(player_ptr p) const
{
}
};
/*
* 0x10 HOLDING CHANGE
*/
struct HoldingChange : public Request
{
int16_t slot;
BEGIN_FIELDS
SHORT (slot)
END_FIELDS
void dispatch(player_ptr p) const
{
// TODO: implement dispatch
Response r;
r << (int8_t)0x36;
r << (int32_t)0 << (int16_t)1 << (int32_t)0;
r << (int8_t)0 << (int8_t)16;
p->deliver(r);
}
};
/*
* 0x12 ENTITY ANIMATION
*/
struct Animation : public Request
{
int32_t eid;
int8_t anim;
BEGIN_FIELDS
INT (eid)
BYTE (anim)
END_FIELDS
void dispatch(player_ptr p) const
{
// TODO: implement dispatch
}
};
/*
* 0x13 STANCE CHANGE
*/
struct Stance : public Request
{
int32_t eid;
int8_t action; // 1 = crouch, 2 = uncrouch, 3 = leave bed
BEGIN_FIELDS
INT (eid)
BYTE (action)
END_FIELDS
void dispatch(player_ptr p) const
{
// TODO: implement dispatch
}
};
/*
* 0x65 CLOSE WINDOW
*/
struct CloseWindow : public Request
{
int8_t windowid;
BEGIN_FIELDS
BYTE (windowid)
END_FIELDS
void dispatch(player_ptr p) const
{
// TODO: implement dispatch
}
};
/*
* 0x66 WINDOW CLICK
*/
struct ClickWindow : public Request
{
int8_t windowid;
int16_t slot;
bool rclick;
bool shift;
int16_t actionid;
int16_t itemid;
int8_t itemcount;
int16_t itemuses;
BEGIN_FIELDS
BYTE (windowid)
SHORT (slot)
BOOLEAN (rclick)
SHORT (actionid)
BOOLEAN (shift)
SHORT (itemid)
if (itemid != -1)
{
BYTE (itemcount)
SHORT (itemuses)
}
END_FIELDS
void dispatch(player_ptr p) const
{
// TODO: implement dispatch
}
};
/*
* 0xFF DISCONNECT
*/
struct Disconnect : public Request
{
std::string message;
BEGIN_FIELDS
STRING_UCS2 (message)
END_FIELDS
void dispatch(player_ptr p) const
{
p->stop(message);
}
};
} // namespace packets
#define REQUEST_CASE(num, type) case num: return ptr(new type());
std::unique_ptr<Request> makerequest(int type)
{
typedef std::unique_ptr<Request> ptr;
using namespace packets;
switch(type)
{
REQUEST_CASE(0x00, KeepAlive)
REQUEST_CASE(0x01, LoginRequest)
REQUEST_CASE(0x02, Handshake)
REQUEST_CASE(0x03, ChatMessage)
REQUEST_CASE(0x07, UseEntity)
REQUEST_CASE(0x09, Respawn)
REQUEST_CASE(0x0A, PlayerOnGround)
REQUEST_CASE(0x0B, PlayerPosition)
REQUEST_CASE(0x0C, PlayerLook)
REQUEST_CASE(0x0D, PlayerPositionAndLook)
REQUEST_CASE(0x0E, Digging)
REQUEST_CASE(0x0F, BlockPlacement)
REQUEST_CASE(0x10, HoldingChange)
REQUEST_CASE(0x12, Animation)
REQUEST_CASE(0x13, Stance)
REQUEST_CASE(0x65, CloseWindow)
REQUEST_CASE(0x66, ClickWindow)
REQUEST_CASE(0xFF, Disconnect)
default:
{
std::stringstream ss;
ss << "Unrecognized packet ID " << std::hex << type;
throw std::runtime_error(ss.str());
}
}
}
}} // namespace xim::network
<|endoftext|>
|
<commit_before>#ifndef MJOLNIR_TEST_MAKE_EMPTY_INPUT_HPP
#define MJOLNIR_TEST_MAKE_EMPTY_INPUT_HPP
#include <extlib/toml/toml.hpp>
#include <mjolnir/util/string.hpp>
namespace mjolnir
{
namespace test
{
// make a minimal input file that contains no particle, no forcefield.
// It contains only parameters that are needed to pass read_input() functions.
inline toml::value make_empty_input()
{
using namespace toml::literals::toml_literals;
return u8R"(
[files]
output.prefix = "empty"
output.format = "xyz"
output.path = "./"
[units]
length = "angstrom"
energy = "kcal/mol"
[simulator]
type = "MolecularDynamics"
precision = "double"
boundary_type = "Unlimited"
total_step = 1
save_step = 1
delta_t = 0.1
integrator.type = "VelocityVerlet"
[[systems]]
attributes.temperature = 300.0
boundary_shape = {}
particles = []
[[forcefields]]
# nothing!
)"_toml;
}
} // test
} // mjolnir
#endif// MJOLNIR_TEST_MAKE_EMPTY_INPUT_HPP
<commit_msg>test: update template sample input<commit_after>#ifndef MJOLNIR_TEST_MAKE_EMPTY_INPUT_HPP
#define MJOLNIR_TEST_MAKE_EMPTY_INPUT_HPP
#include <extlib/toml/toml.hpp>
#include <mjolnir/util/string.hpp>
namespace mjolnir
{
namespace test
{
// make a minimal input file that contains no particle, no forcefield.
// It contains only parameters that are needed to pass read_input() functions.
inline toml::value make_empty_input()
{
using namespace toml::literals::toml_literals;
return u8R"(
[files]
output.prefix = "empty"
output.format = "xyz"
output.path = "./"
[units]
length = "angstrom"
energy = "kcal/mol"
[simulator]
type = "MolecularDynamics"
precision = "double"
boundary_type = "Unlimited"
seed = 1
total_step = 1
save_step = 1
delta_t = 0.1
integrator.type = "VelocityVerlet"
[[systems]]
attributes.temperature = 300.0
boundary_shape = {}
particles = []
[[forcefields]]
# nothing!
)"_toml;
}
} // test
} // mjolnir
#endif// MJOLNIR_TEST_MAKE_EMPTY_INPUT_HPP
<|endoftext|>
|
<commit_before>/*
* Copyright 2016 CodiLime
*
* 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 "mock_sampler.h"
#include "util/concurrency/threadpool.h"
namespace veles {
namespace util {
using testing::Mock;
using testing::Return;
using testing::Expectation;
using testing::_;
/*****************************************************************************/
/* Helpers */
/*****************************************************************************/
QByteArray prepare_data(size_t size) {
QByteArray result;
for (size_t i = 0; i < size; ++i) {
result.push_back(static_cast<char>(i % 127));
}
return result;
}
int MockCallback::getCallCount() {
return calls_;
}
void MockCallback::resetCallCount() {
calls_ = 0;
}
void MockCallback::operator()() {
++calls_;
}
/*****************************************************************************/
/* Small data (no sampling required) */
/*****************************************************************************/
TEST(ISamplerSmallData, basic) {
auto data = prepare_data(100);
testing::StrictMock<MockSampler> sampler(data);
sampler.setSampleSize(120);
ASSERT_EQ(100, sampler.getSampleSize());
ASSERT_EQ(data[0], sampler[0]);
ASSERT_EQ(data[10], sampler[10]);
ASSERT_EQ(data[99], sampler[sampler.getSampleSize() - 1]);
}
TEST(ISamplerSmallData, setRange) {
auto data = prepare_data(100);
testing::StrictMock<MockSampler> sampler(data);
sampler.setSampleSize(120);
sampler.setRange(40, 50);
ASSERT_EQ(10, sampler.getSampleSize());
ASSERT_EQ(40, sampler.getRange().first);
ASSERT_EQ(50, sampler.getRange().second);
for (int i = 0; i < 10; ++i) {
ASSERT_EQ(data[i + 40], sampler[i]);
}
}
TEST(ISamplerSmallData, offsets) {
auto data = prepare_data(100);
testing::StrictMock<MockSampler> sampler(data);
sampler.setSampleSize(120);
ASSERT_EQ(0, sampler.getFileOffset(0));
ASSERT_EQ(33, sampler.getFileOffset(33));
ASSERT_EQ(99, sampler.getFileOffset(99));
ASSERT_EQ(0, sampler.getSampleOffset(0));
ASSERT_EQ(33, sampler.getSampleOffset(33));
ASSERT_EQ(99, sampler.getSampleOffset(99));
}
TEST(ISamplerSmallData, offsetsAfterSetRange) {
auto data = prepare_data(100);
testing::StrictMock<MockSampler> sampler(data);
sampler.setSampleSize(120);
sampler.setRange(40, 50);
ASSERT_EQ(40, sampler.getFileOffset(0));
ASSERT_EQ(45, sampler.getFileOffset(5));
ASSERT_EQ(49, sampler.getFileOffset(9));
ASSERT_EQ(0, sampler.getSampleOffset(40));
ASSERT_EQ(5, sampler.getSampleOffset(45));
ASSERT_EQ(9, sampler.getSampleOffset(49));
}
/*****************************************************************************/
/* Synchronous sampling */
/*****************************************************************************/
TEST(ISamplerWithSampling, basic) {
auto data = prepare_data(100);
testing::NiceMock<MockSampler> sampler(data);
Expectation init1 = EXPECT_CALL(sampler, prepareResample(_));
Expectation init2 = EXPECT_CALL(sampler, applyResample(_))
.After(init1);
sampler.setSampleSize(10);
EXPECT_CALL(sampler, getRealSampleSize())
.After(init2)
.WillRepeatedly(Return(10));
ASSERT_EQ(10, sampler.getSampleSize());
EXPECT_CALL(sampler, getSampleByte(0))
.WillOnce(Return(0));
ASSERT_EQ(data[0], sampler[0]);
EXPECT_CALL(sampler, getSampleByte(5))
.WillOnce(Return(33));
ASSERT_EQ(data[33], sampler[5]);
EXPECT_CALL(sampler, getSampleByte(9))
.WillOnce(Return(99));
ASSERT_EQ(data[99], sampler[9]);
}
TEST(ISamplerWithSampling, offsets) {
auto data = prepare_data(100);
testing::NiceMock<MockSampler> sampler(data);
sampler.setSampleSize(10);
ON_CALL(sampler, getRealSampleSize())
.WillByDefault(Return(10));
EXPECT_CALL(sampler, getFileOffsetImpl(5))
.Times(1)
.WillOnce(Return(50));
ASSERT_EQ(0, sampler.getFileOffset(0));
ASSERT_EQ(99, sampler.getFileOffset(9));
ASSERT_EQ(50, sampler.getFileOffset(5));
EXPECT_CALL(sampler, getSampleOffsetImpl(50))
.Times(1)
.WillOnce(Return(5));
ASSERT_EQ(0, sampler.getSampleOffset(0));
ASSERT_EQ(9, sampler.getSampleOffset(99));
ASSERT_EQ(5, sampler.getSampleOffset(50));
}
TEST(ISamplerWithSampling, offsetsAfterSetRange) {
auto data = prepare_data(100);
testing::NiceMock<MockSampler> sampler(data);
sampler.setSampleSize(10);
sampler.setRange(40, 60);
ON_CALL(sampler, getRealSampleSize())
.WillByDefault(Return(10));
EXPECT_CALL(sampler, getFileOffsetImpl(5))
.Times(1)
.WillOnce(Return(10));
ASSERT_EQ(40, sampler.getFileOffset(0));
ASSERT_EQ(59, sampler.getFileOffset(9));
ASSERT_EQ(50, sampler.getFileOffset(5));
EXPECT_CALL(sampler, getSampleOffsetImpl(10))
.Times(1)
.WillOnce(Return(5));
ASSERT_EQ(0, sampler.getSampleOffset(40));
ASSERT_EQ(9, sampler.getSampleOffset(59));
ASSERT_EQ(5, sampler.getSampleOffset(50));
}
TEST(ISamplerWithSampling, getDataFromIsampler) {
auto data = prepare_data(100);
testing::StrictMock<MockSampler> sampler(data);
Expectation init1 = EXPECT_CALL(sampler, prepareResample(_));
Expectation init2 = EXPECT_CALL(sampler, applyResample(_))
.After(init1);
sampler.setSampleSize(10);
ASSERT_EQ(100, sampler.proxy_getDataSize());
ASSERT_EQ(0, sampler.proxy_getDataByte(0));
ASSERT_EQ(5, sampler.proxy_getDataByte(5));
ASSERT_EQ(99, sampler.proxy_getDataByte(99));
Mock::VerifyAndClear(&sampler);
Expectation update1 = EXPECT_CALL(sampler, prepareResample(_));
Expectation update2 = EXPECT_CALL(sampler, applyResample(_))
.After(update1);
sampler.setRange(40, 60);
ASSERT_EQ(20, sampler.proxy_getDataSize());
ASSERT_EQ(40, sampler.proxy_getDataByte(0));
ASSERT_EQ(45, sampler.proxy_getDataByte(5));
ASSERT_EQ(59, sampler.proxy_getDataByte(19));
}
/*****************************************************************************/
/* Asynchronous interface */
/*****************************************************************************/
TEST(ISamplerAsynchronous, addAndClearCallbacks) {
threadpool::mockTopic("visualisation");
auto data = prepare_data(100);
MockCallback mc1, mc2, mc3;
mc1.resetCallCount();
mc2.resetCallCount();
mc3.resetCallCount();
testing::NiceMock<MockSampler> sampler(data);
sampler.setSampleSize(10);
sampler.allowAsynchronousResampling(true);
sampler.registerResampleCallback(std::ref(mc1));
auto cb2_id = sampler.registerResampleCallback(std::ref(mc2));
sampler.registerResampleCallback(std::ref(mc3));
sampler.resample();
ASSERT_EQ(1, mc1.getCallCount());
ASSERT_EQ(1, mc2.getCallCount());
ASSERT_EQ(1, mc3.getCallCount());
mc1.resetCallCount();
mc2.resetCallCount();
mc3.resetCallCount();
sampler.removeResampleCallback(cb2_id);
sampler.resample();
ASSERT_EQ(1, mc1.getCallCount());
ASSERT_EQ(0, mc2.getCallCount());
ASSERT_EQ(1, mc3.getCallCount());
mc1.resetCallCount();
mc2.resetCallCount();
mc3.resetCallCount();
sampler.clearResampleCallbacks();
sampler.resample();
ASSERT_EQ(0, mc1.getCallCount());
ASSERT_EQ(0, mc2.getCallCount());
ASSERT_EQ(0, mc3.getCallCount());
}
TEST(ISamplerAsynchronous, prepareAndApplySample) {
threadpool::mockTopic("visualisation");
auto data = prepare_data(100);
MockCallback mc;
mc.resetCallCount();
testing::StrictMock<MockSampler> sampler(data);
EXPECT_CALL(sampler, prepareResample(_))
.WillOnce(Return(nullptr));
EXPECT_CALL(sampler, applyResample(nullptr));
sampler.setSampleSize(10);
sampler.wait();
ASSERT_TRUE(sampler.isFinished());
}
} // namespace util
} // namespace veles
<commit_msg>Fix renaming bug<commit_after>/*
* Copyright 2016 CodiLime
*
* 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 "mock_sampler.h"
#include "util/concurrency/threadpool.h"
namespace veles {
namespace util {
using testing::Mock;
using testing::Return;
using testing::Expectation;
using testing::_;
/*****************************************************************************/
/* Helpers */
/*****************************************************************************/
QByteArray prepare_data(size_t size) {
QByteArray result;
for (size_t i = 0; i < size; ++i) {
result.push_back(static_cast<char>(i % 127));
}
return result;
}
int MockCallback::getCallCount() {
return calls_;
}
void MockCallback::resetCallCount() {
calls_ = 0;
}
void MockCallback::operator()() {
++calls_;
}
/*****************************************************************************/
/* Small data (no sampling required) */
/*****************************************************************************/
TEST(ISamplerSmallData, basic) {
auto data = prepare_data(100);
testing::StrictMock<MockSampler> sampler(data);
sampler.setSampleSize(120);
ASSERT_EQ(100, sampler.getSampleSize());
ASSERT_EQ(data[0], sampler[0]);
ASSERT_EQ(data[10], sampler[10]);
ASSERT_EQ(data[99], sampler[sampler.getSampleSize() - 1]);
}
TEST(ISamplerSmallData, setRange) {
auto data = prepare_data(100);
testing::StrictMock<MockSampler> sampler(data);
sampler.setSampleSize(120);
sampler.setRange(40, 50);
ASSERT_EQ(10, sampler.getSampleSize());
ASSERT_EQ(40, sampler.getRange().first);
ASSERT_EQ(50, sampler.getRange().second);
for (int i = 0; i < 10; ++i) {
ASSERT_EQ(data[i + 40], sampler[i]);
}
}
TEST(ISamplerSmallData, offsets) {
auto data = prepare_data(100);
testing::StrictMock<MockSampler> sampler(data);
sampler.setSampleSize(120);
ASSERT_EQ(0, sampler.getFileOffset(0));
ASSERT_EQ(33, sampler.getFileOffset(33));
ASSERT_EQ(99, sampler.getFileOffset(99));
ASSERT_EQ(0, sampler.getSampleOffset(0));
ASSERT_EQ(33, sampler.getSampleOffset(33));
ASSERT_EQ(99, sampler.getSampleOffset(99));
}
TEST(ISamplerSmallData, offsetsAfterSetRange) {
auto data = prepare_data(100);
testing::StrictMock<MockSampler> sampler(data);
sampler.setSampleSize(120);
sampler.setRange(40, 50);
ASSERT_EQ(40, sampler.getFileOffset(0));
ASSERT_EQ(45, sampler.getFileOffset(5));
ASSERT_EQ(49, sampler.getFileOffset(9));
ASSERT_EQ(0, sampler.getSampleOffset(40));
ASSERT_EQ(5, sampler.getSampleOffset(45));
ASSERT_EQ(9, sampler.getSampleOffset(49));
}
/*****************************************************************************/
/* Synchronous sampling */
/*****************************************************************************/
TEST(ISamplerWithSampling, basic) {
auto data = prepare_data(100);
testing::NiceMock<MockSampler> sampler(data);
Expectation init1 = EXPECT_CALL(sampler, prepareResample(_));
Expectation init2 = EXPECT_CALL(sampler, applyResample(_))
.After(init1);
sampler.setSampleSize(10);
EXPECT_CALL(sampler, getRealSampleSize())
.After(init2)
.WillRepeatedly(Return(10));
ASSERT_EQ(10, sampler.getSampleSize());
EXPECT_CALL(sampler, getSampleByte(0))
.WillOnce(Return(0));
ASSERT_EQ(data[0], sampler[0]);
EXPECT_CALL(sampler, getSampleByte(5))
.WillOnce(Return(33));
ASSERT_EQ(data[33], sampler[5]);
EXPECT_CALL(sampler, getSampleByte(9))
.WillOnce(Return(99));
ASSERT_EQ(data[99], sampler[9]);
}
TEST(ISamplerWithSampling, offsets) {
auto data = prepare_data(100);
testing::NiceMock<MockSampler> sampler(data);
sampler.setSampleSize(10);
ON_CALL(sampler, getRealSampleSize())
.WillByDefault(Return(10));
EXPECT_CALL(sampler, getFileOffsetImpl(5))
.Times(1)
.WillOnce(Return(50));
ASSERT_EQ(0, sampler.getFileOffset(0));
ASSERT_EQ(99, sampler.getFileOffset(9));
ASSERT_EQ(50, sampler.getFileOffset(5));
EXPECT_CALL(sampler, getSampleOffsetImpl(50))
.Times(1)
.WillOnce(Return(5));
ASSERT_EQ(0, sampler.getSampleOffset(0));
ASSERT_EQ(9, sampler.getSampleOffset(99));
ASSERT_EQ(5, sampler.getSampleOffset(50));
}
TEST(ISamplerWithSampling, offsetsAfterSetRange) {
auto data = prepare_data(100);
testing::NiceMock<MockSampler> sampler(data);
sampler.setSampleSize(10);
sampler.setRange(40, 60);
ON_CALL(sampler, getRealSampleSize())
.WillByDefault(Return(10));
EXPECT_CALL(sampler, getFileOffsetImpl(5))
.Times(1)
.WillOnce(Return(10));
ASSERT_EQ(40, sampler.getFileOffset(0));
ASSERT_EQ(59, sampler.getFileOffset(9));
ASSERT_EQ(50, sampler.getFileOffset(5));
EXPECT_CALL(sampler, getSampleOffsetImpl(10))
.Times(1)
.WillOnce(Return(5));
ASSERT_EQ(0, sampler.getSampleOffset(40));
ASSERT_EQ(9, sampler.getSampleOffset(59));
ASSERT_EQ(5, sampler.getSampleOffset(50));
}
TEST(ISamplerWithSampling, getDataFromIsampler) {
auto data = prepare_data(100);
testing::StrictMock<MockSampler> sampler(data);
Expectation init1 = EXPECT_CALL(sampler, prepareResample(_));
Expectation init2 = EXPECT_CALL(sampler, applyResample(_))
.After(init1);
sampler.setSampleSize(10);
ASSERT_EQ(100, sampler.proxy_getDataSize());
ASSERT_EQ(0, sampler.proxy_getDataByte(0));
ASSERT_EQ(5, sampler.proxy_getDataByte(5));
ASSERT_EQ(99, sampler.proxy_getDataByte(99));
Mock::VerifyAndClear(&sampler);
Expectation update1 = EXPECT_CALL(sampler, prepareResample(_));
Expectation update2 = EXPECT_CALL(sampler, applyResample(_))
.After(update1);
sampler.setRange(40, 60);
ASSERT_EQ(20, sampler.proxy_getDataSize());
ASSERT_EQ(40, sampler.proxy_getDataByte(0));
ASSERT_EQ(45, sampler.proxy_getDataByte(5));
ASSERT_EQ(59, sampler.proxy_getDataByte(19));
}
/*****************************************************************************/
/* Asynchronous interface */
/*****************************************************************************/
TEST(ISamplerAsynchronous, addAndClearCallbacks) {
threadpool::mockTopic("visualization");
auto data = prepare_data(100);
MockCallback mc1, mc2, mc3;
mc1.resetCallCount();
mc2.resetCallCount();
mc3.resetCallCount();
testing::NiceMock<MockSampler> sampler(data);
sampler.setSampleSize(10);
sampler.allowAsynchronousResampling(true);
sampler.registerResampleCallback(std::ref(mc1));
auto cb2_id = sampler.registerResampleCallback(std::ref(mc2));
sampler.registerResampleCallback(std::ref(mc3));
sampler.resample();
ASSERT_EQ(1, mc1.getCallCount());
ASSERT_EQ(1, mc2.getCallCount());
ASSERT_EQ(1, mc3.getCallCount());
mc1.resetCallCount();
mc2.resetCallCount();
mc3.resetCallCount();
sampler.removeResampleCallback(cb2_id);
sampler.resample();
ASSERT_EQ(1, mc1.getCallCount());
ASSERT_EQ(0, mc2.getCallCount());
ASSERT_EQ(1, mc3.getCallCount());
mc1.resetCallCount();
mc2.resetCallCount();
mc3.resetCallCount();
sampler.clearResampleCallbacks();
sampler.resample();
ASSERT_EQ(0, mc1.getCallCount());
ASSERT_EQ(0, mc2.getCallCount());
ASSERT_EQ(0, mc3.getCallCount());
}
TEST(ISamplerAsynchronous, prepareAndApplySample) {
threadpool::mockTopic("visualization");
auto data = prepare_data(100);
MockCallback mc;
mc.resetCallCount();
testing::StrictMock<MockSampler> sampler(data);
EXPECT_CALL(sampler, prepareResample(_))
.WillOnce(Return(nullptr));
EXPECT_CALL(sampler, applyResample(nullptr));
sampler.setSampleSize(10);
sampler.wait();
ASSERT_TRUE(sampler.isFinished());
}
} // namespace util
} // namespace veles
<|endoftext|>
|
<commit_before>/** \copyright
* Copyright (c) 2013, 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 AsyncIf.hxx
*
* Asynchronous NMRAnet interface.
*
* @author Balazs Racz
* @date 3 Dec 2013
*/
#ifndef _NMRAnetAsyncIf_hxx_
#define _NMRAnetAsyncIf_hxx_
/// @todo(balazs.racz) remove this dep
#include <string>
#include "nmranet/NMRAnetAsyncNode.hxx"
#include "nmranet/NMRAnetIf.hxx"
#include "executor/Dispatcher.hxx"
#include "executor/Service.hxx"
#include "executor/Executor.hxx"
#include "utils/BufferQueue.hxx"
#include "utils/Map.hxx"
namespace NMRAnet
{
class AsyncNode;
/** Convenience function to render a 48-bit NMRAnet node ID into a new buffer.
*
* @param id is the 48-bit ID to render.
* @returns a new buffer (from the main pool) with 6 bytes of used space, a
* big-endian representation of the node ID.
*/
extern string node_id_to_buffer(NodeID id);
/** Converts a 6-byte-long buffer to a node ID.
*
* @param buf is a buffer that has to have exactly 6 bytes used, filled with a
* big-endian node id.
* @returns the node id (in host endian).
*/
extern NodeID buffer_to_node_id(const string& buf);
/** This class is used in the dispatching of incoming or outgoing NMRAnet
* messages to the message handlers at the protocol-agnostic level (i.e. not
* CAN or TCP-specific).
*
* TODO(balazs.racz) There shall be one instance of this class that will be
* sent to all handlers that expressed interest in that MTI. When all those
* handlers are done, the instance should be freed. Currently the instance is
* copied by the dispatcher separately for each handler. */
struct NMRAnetMessage
{
void reset(If::MTI mti, NodeID src, NodeHandle dst, const string &payload)
{
this->mti = mti;
this->src = {src, 0};
this->dst = dst;
this->payload = payload;
}
void reset(If::MTI mti, NodeID src, const string &payload)
{
this->mti = mti;
this->src = {src, 0};
this->dst = {0, 0};
this->payload = payload;
}
/// OpenLCB MTI of the incoming message.
If::MTI mti;
/// Source node.
NodeHandle src;
/// Destination node.
NodeHandle dst;
/// If the destination node is local, this value is non-NULL.
AsyncNode *dstNode;
/// Data content in the message body. Owned by the dispatcher.
/// @todo(balazs.racz) figure out a better container.
string payload;
typedef uint32_t id_type;
id_type id() const
{
return static_cast<uint32_t>(mti);
}
};
typedef FlowInterface<Buffer<NMRAnetMessage>> MessageHandler;
#if 0
/** @todo(balazs.racz) delete this class */
class WriteFlow : public ControlFlow
{
public:
WriteFlow(Executor *e, Notifiable *done) : ControlFlow(e, done)
{
}
/** Initiates sending an addressed message onto the NMRAnet bus.
*
* Must only be called if *this is an addressed flow.
*
* @param mti of the message to send
* @param src is the NodeID of the originating node
* @param dst is the destination node (cannot be 0,0)
* @param data is the message payload (may be null), takes ownership
* @param done will be notified when the message is enqueued for sending.
* May be set to nullptr.
*/
virtual void WriteAddressedMessage(If::MTI mti, NodeID src, NodeHandle dst,
Buffer *data, Notifiable *done) = 0;
/** Initiates sending an unaddressed (global) message onto the NMRAnet bus.
*
* Must only be called if *this is a global flow.
*
* @param mti of the message to send
* @param src is the NodeID of the originating node
* @param data is the message payload (may be null), takes ownership
* @param done will be notified when the message is enqueued for sending.
* May be set to nullptr.
*/
virtual void WriteGlobalMessage(If::MTI mti, NodeID src, Buffer *data,
Notifiable *done) = 0;
};
#endif
class AsyncIf : public Service
{
public:
/** Constructs an NMRAnet interface.
* @param executor is the thread that will be used for all processing on
* this interface.
* @param local_nodes_count is the maximum number of virtual nodes that
* this interface will support. */
AsyncIf(ExecutorBase *executor, int local_nodes_count);
/** Destructor */
virtual ~AsyncIf()
{
}
/** @return Flow to send global messages to the NMRAnet bus. */
MessageHandler *global_message_write_flow()
{
HASSERT(globalWriteFlow_);
return globalWriteFlow_;
}
/** @return Flow to send addressed messages to the NMRAnet bus. */
MessageHandler *addressed_message_write_flow()
{
HASSERT(addressedWriteFlow_);
return addressedWriteFlow_;
}
/** Type of the dispatcher of incoming NMRAnet messages. */
typedef DispatchFlow<Buffer<NMRAnetMessage>, 4> MessageDispatchFlow;
/** @return Dispatcher of incoming NMRAnet messages. */
MessageDispatchFlow *dispatcher()
{
return &dispatcher_;
}
/** Transfers ownership of a module to the interface. It will be brought
* down in the destructor. The destruction order is guaranteed such that
* all supporting structures are still available when the flow is destryed,
* but incoming messages can not come in anymore.
*
* @todo(balazs.racz) revise whether this needs to be virtual. */
virtual void add_owned_flow(Executable *e) = 0;
/** Registers a new local node on this interface. This function must be
* called from the interface's executor.
*
* @param node is the node to register.
*/
void add_local_node(AsyncNode *node)
{
NodeID id = node->node_id();
HASSERT(localNodes_.find(id) == localNodes_.end());
localNodes_[id] = node;
}
/** Removes a local node from this interface. This function must be called
* from the interface's executor.
*
* @param node is the node to delete.
*/
void delete_local_node(AsyncNode *node)
{
HASSERT(0);
/*
auto it = localNodes_.find(node->node_id());
HASSERT(it != localNodes_.end());
localNodes_.erase(it);*/
}
/** Looks up a node ID in the local nodes' registry. This function must be
* called from the interface's executor.
*
* @param id is the 48-bit NMRAnet node ID to look up.
* @returns the node pointer or NULL if the node is not registered.
*/
AsyncNode *lookup_local_node(NodeID id)
{
auto it = localNodes_.find(id);
if (it == localNodes_.end())
{
return nullptr;
}
return it->second;
}
protected:
/// Allocator containing the global write flows.
MessageHandler *globalWriteFlow_;
/// Allocator containing the addressed write flows.
MessageHandler *addressedWriteFlow_;
private:
/// Flow responsible for routing incoming messages to handlers.
MessageDispatchFlow dispatcher_;
typedef Map<NodeID, AsyncNode *> VNodeMap;
/// Local virtual nodes registered on this interface.
VNodeMap localNodes_;
friend class VerifyNodeIdHandler;
DISALLOW_COPY_AND_ASSIGN(AsyncIf);
};
/** Base class for incoming message handler flows. */
class IncomingMessageStateFlow
: public StateFlow<Buffer<NMRAnetMessage>, QList<4>>
{
public:
IncomingMessageStateFlow(AsyncIf *interface)
: StateFlow<Buffer<NMRAnetMessage>, QList<4>>(interface)
{
}
AsyncIf *interface()
{
return static_cast<AsyncIf *>(service());
}
};
} // namespace NMRAnet
#endif // _NMRAnetAsyncIf_hxx_
<commit_msg>Initializes dstNode with nullptr as well.<commit_after>/** \copyright
* Copyright (c) 2013, 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 AsyncIf.hxx
*
* Asynchronous NMRAnet interface.
*
* @author Balazs Racz
* @date 3 Dec 2013
*/
#ifndef _NMRAnetAsyncIf_hxx_
#define _NMRAnetAsyncIf_hxx_
/// @todo(balazs.racz) remove this dep
#include <string>
#include "nmranet/NMRAnetAsyncNode.hxx"
#include "nmranet/NMRAnetIf.hxx"
#include "executor/Dispatcher.hxx"
#include "executor/Service.hxx"
#include "executor/Executor.hxx"
#include "utils/BufferQueue.hxx"
#include "utils/Map.hxx"
namespace NMRAnet
{
class AsyncNode;
/** Convenience function to render a 48-bit NMRAnet node ID into a new buffer.
*
* @param id is the 48-bit ID to render.
* @returns a new buffer (from the main pool) with 6 bytes of used space, a
* big-endian representation of the node ID.
*/
extern string node_id_to_buffer(NodeID id);
/** Converts a 6-byte-long buffer to a node ID.
*
* @param buf is a buffer that has to have exactly 6 bytes used, filled with a
* big-endian node id.
* @returns the node id (in host endian).
*/
extern NodeID buffer_to_node_id(const string& buf);
/** This class is used in the dispatching of incoming or outgoing NMRAnet
* messages to the message handlers at the protocol-agnostic level (i.e. not
* CAN or TCP-specific).
*
* TODO(balazs.racz) There shall be one instance of this class that will be
* sent to all handlers that expressed interest in that MTI. When all those
* handlers are done, the instance should be freed. Currently the instance is
* copied by the dispatcher separately for each handler. */
struct NMRAnetMessage
{
void reset(If::MTI mti, NodeID src, NodeHandle dst, const string &payload)
{
this->mti = mti;
this->src = {src, 0};
this->dst = dst;
this->payload = payload;
this->dstNode = nullptr;
}
void reset(If::MTI mti, NodeID src, const string &payload)
{
this->mti = mti;
this->src = {src, 0};
this->dst = {0, 0};
this->payload = payload;
this->dstNode = nullptr;
}
/// OpenLCB MTI of the incoming message.
If::MTI mti;
/// Source node.
NodeHandle src;
/// Destination node.
NodeHandle dst;
/// If the destination node is local, this value is non-NULL.
AsyncNode *dstNode;
/// Data content in the message body. Owned by the dispatcher.
/// @todo(balazs.racz) figure out a better container.
string payload;
typedef uint32_t id_type;
id_type id() const
{
return static_cast<uint32_t>(mti);
}
};
typedef FlowInterface<Buffer<NMRAnetMessage>> MessageHandler;
#if 0
/** @todo(balazs.racz) delete this class */
class WriteFlow : public ControlFlow
{
public:
WriteFlow(Executor *e, Notifiable *done) : ControlFlow(e, done)
{
}
/** Initiates sending an addressed message onto the NMRAnet bus.
*
* Must only be called if *this is an addressed flow.
*
* @param mti of the message to send
* @param src is the NodeID of the originating node
* @param dst is the destination node (cannot be 0,0)
* @param data is the message payload (may be null), takes ownership
* @param done will be notified when the message is enqueued for sending.
* May be set to nullptr.
*/
virtual void WriteAddressedMessage(If::MTI mti, NodeID src, NodeHandle dst,
Buffer *data, Notifiable *done) = 0;
/** Initiates sending an unaddressed (global) message onto the NMRAnet bus.
*
* Must only be called if *this is a global flow.
*
* @param mti of the message to send
* @param src is the NodeID of the originating node
* @param data is the message payload (may be null), takes ownership
* @param done will be notified when the message is enqueued for sending.
* May be set to nullptr.
*/
virtual void WriteGlobalMessage(If::MTI mti, NodeID src, Buffer *data,
Notifiable *done) = 0;
};
#endif
class AsyncIf : public Service
{
public:
/** Constructs an NMRAnet interface.
* @param executor is the thread that will be used for all processing on
* this interface.
* @param local_nodes_count is the maximum number of virtual nodes that
* this interface will support. */
AsyncIf(ExecutorBase *executor, int local_nodes_count);
/** Destructor */
virtual ~AsyncIf()
{
}
/** @return Flow to send global messages to the NMRAnet bus. */
MessageHandler *global_message_write_flow()
{
HASSERT(globalWriteFlow_);
return globalWriteFlow_;
}
/** @return Flow to send addressed messages to the NMRAnet bus. */
MessageHandler *addressed_message_write_flow()
{
HASSERT(addressedWriteFlow_);
return addressedWriteFlow_;
}
/** Type of the dispatcher of incoming NMRAnet messages. */
typedef DispatchFlow<Buffer<NMRAnetMessage>, 4> MessageDispatchFlow;
/** @return Dispatcher of incoming NMRAnet messages. */
MessageDispatchFlow *dispatcher()
{
return &dispatcher_;
}
/** Transfers ownership of a module to the interface. It will be brought
* down in the destructor. The destruction order is guaranteed such that
* all supporting structures are still available when the flow is destryed,
* but incoming messages can not come in anymore.
*
* @todo(balazs.racz) revise whether this needs to be virtual. */
virtual void add_owned_flow(Executable *e) = 0;
/** Registers a new local node on this interface. This function must be
* called from the interface's executor.
*
* @param node is the node to register.
*/
void add_local_node(AsyncNode *node)
{
NodeID id = node->node_id();
HASSERT(localNodes_.find(id) == localNodes_.end());
localNodes_[id] = node;
}
/** Removes a local node from this interface. This function must be called
* from the interface's executor.
*
* @param node is the node to delete.
*/
void delete_local_node(AsyncNode *node)
{
HASSERT(0);
/*
auto it = localNodes_.find(node->node_id());
HASSERT(it != localNodes_.end());
localNodes_.erase(it);*/
}
/** Looks up a node ID in the local nodes' registry. This function must be
* called from the interface's executor.
*
* @param id is the 48-bit NMRAnet node ID to look up.
* @returns the node pointer or NULL if the node is not registered.
*/
AsyncNode *lookup_local_node(NodeID id)
{
auto it = localNodes_.find(id);
if (it == localNodes_.end())
{
return nullptr;
}
return it->second;
}
protected:
/// Allocator containing the global write flows.
MessageHandler *globalWriteFlow_;
/// Allocator containing the addressed write flows.
MessageHandler *addressedWriteFlow_;
private:
/// Flow responsible for routing incoming messages to handlers.
MessageDispatchFlow dispatcher_;
typedef Map<NodeID, AsyncNode *> VNodeMap;
/// Local virtual nodes registered on this interface.
VNodeMap localNodes_;
friend class VerifyNodeIdHandler;
DISALLOW_COPY_AND_ASSIGN(AsyncIf);
};
/** Base class for incoming message handler flows. */
class IncomingMessageStateFlow
: public StateFlow<Buffer<NMRAnetMessage>, QList<4>>
{
public:
IncomingMessageStateFlow(AsyncIf *interface)
: StateFlow<Buffer<NMRAnetMessage>, QList<4>>(interface)
{
}
AsyncIf *interface()
{
return static_cast<AsyncIf *>(service());
}
/// Returns the NMRAnet message we received.
NMRAnetMessage *nmsg()
{
return message()->data();
}
};
} // namespace NMRAnet
#endif // _NMRAnetAsyncIf_hxx_
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2013-2015, The University of Oxford
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of the University of Oxford nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <apps/lib/oskar_OptionParser.h>
#include <oskar_log.h>
#include <oskar_get_error_string.h>
#include <oskar_vis.h>
#include <oskar_version_string.h>
#include <string>
#include <vector>
#include <cmath>
#include <iostream>
#include <cstdio>
#include <cfloat>
using namespace std;
//------------------------------------------------------------------------------
void set_options(oskar_OptionParser& opt);
bool check_options(oskar_OptionParser& opt, int argc, char** argv);
void check_error(int status);
//------------------------------------------------------------------------------
int main(int argc, char** argv)
{
int status = OSKAR_SUCCESS;
// Register options.
oskar_OptionParser opt("oskar_vis_stats", oskar_version_string());
set_options(opt);
if (!check_options(opt, argc, argv))
return OSKAR_FAIL;
// Retrieve options.
vector<string> vis_filename = opt.getArgs();
bool verbose = opt.isSet("-v") ? true : false;
int num_files = (int)vis_filename.size();
int disp_width = (num_files == 1) ? 1 : (int)log10(num_files)+1;
oskar_Log* log = 0;
oskar_log_section(log, 'M', "OSKAR-%s starting at %s.", OSKAR_VERSION_STR,
oskar_log_system_clock_string(0));
for (int i = 0; i < num_files; ++i)
{
oskar_Binary* h = oskar_binary_create(vis_filename[i].c_str(), 'r',
&status);
oskar_Vis* vis = oskar_vis_read(h, &status);
oskar_binary_free(h);
check_error(status);
int vis_type = oskar_mem_type(oskar_vis_amplitude(vis));
int num_vis = (int)oskar_mem_length(oskar_vis_amplitude(vis));
double abs_min = DBL_MAX;
double abs_max = -DBL_MAX;
double2 min;
min.x = DBL_MAX;
min.y = DBL_MAX;
double2 max;
max.x = -DBL_MAX;
max.y = -DBL_MAX;
double2 sum;
sum.x = 0.0;
sum.y = 0.0;
double sumsq = 0.0;
size_t num_zero = 0;
double rms = 0.0;
double2 mean;
mean.x = 0.0;
mean.y = 0.0;
if (vis_type == OSKAR_SINGLE_COMPLEX_MATRIX)
{
float4c* amp = oskar_mem_float4c(oskar_vis_amplitude(vis), &status);
for (int i = 0; i < num_vis; ++i)
{
double2 I; // I = 0.5 (XX + YY)
I.x = 0.5 * (amp[i].a.x + amp[i].d.x);
I.y = 0.5 * (amp[i].a.y + amp[i].d.y);
sum.x += I.x;
sum.y += I.y;
double absI = sqrt(I.x*I.x + I.y*I.y);
if (absI < DBL_MIN) num_zero++;
if (absI > abs_max) {
abs_max = absI;
max.x = I.x;
max.y = I.y;
}
if (absI < abs_min) {
abs_min = absI;
min.x = I.x;
min.y = I.y;
}
sumsq += absI * absI;
}
mean.x = sum.x / num_vis;
mean.y = sum.y / num_vis;
rms = sqrt(sumsq / num_vis);
}
else if (vis_type == OSKAR_DOUBLE_COMPLEX_MATRIX)
{
double4c* amp = oskar_mem_double4c(oskar_vis_amplitude(vis), &status);
for (int i = 0; i < num_vis; ++i)
{
double2 I; // I = 0.5 (XX + YY)
I.x = 0.5 * (amp[i].a.x + amp[i].d.x);
I.y = 0.5 * (amp[i].a.y + amp[i].d.y);
sum.x += I.x;
sum.y += I.y;
double absI = sqrt(I.x*I.x + I.y*I.y);
if (absI < DBL_MIN) num_zero++;
if (absI > abs_max) {
abs_max = absI;
max.x = I.x;
max.y = I.y;
}
if (absI < abs_min) {
abs_min = absI;
min.x = I.x;
min.y = I.y;
}
sumsq += absI * absI;
}
mean.x = sum.x / num_vis;
mean.y = sum.y / num_vis;
rms = sqrt(sumsq / num_vis);
}
else if (vis_type == OSKAR_SINGLE_COMPLEX)
{
float2* amp = oskar_mem_float2(oskar_vis_amplitude(vis), &status);
for (int i = 0; i < num_vis; ++i)
{
double2 I;
I.x = amp[i].x;
I.y = amp[i].y;
sum.x += I.x;
sum.y += I.y;
double absI = sqrt(I.x*I.x + I.y*I.y);
if (absI < DBL_MIN) num_zero++;
if (absI > abs_max) {
abs_max = absI;
max.x = I.x;
max.y = I.y;
}
if (absI < abs_min) {
abs_min = absI;
min.x = I.x;
min.y = I.y;
}
sumsq += absI * absI;
}
mean.x = sum.x / num_vis;
mean.y = sum.y / num_vis;
rms = sqrt(sumsq / num_vis);
}
else if (vis_type == OSKAR_DOUBLE_COMPLEX)
{
double2* amp = oskar_mem_double2(oskar_vis_amplitude(vis), &status);
for (int i = 0; i < num_vis; ++i)
{
double2 I;
I.x = amp[i].x;
I.y = amp[i].y;
sum.x += I.x;
sum.y += I.y;
double absI = sqrt(I.x*I.x + I.y*I.y);
if (absI < DBL_MIN) num_zero++;
if (absI > abs_max) {
abs_max = absI;
max.x = I.x;
max.y = I.y;
}
if (absI < abs_min) {
abs_min = absI;
min.x = I.x;
min.y = I.y;
}
sumsq += absI * absI;
}
mean.x = sum.x / num_vis;
mean.y = sum.y / num_vis;
rms = sqrt(sumsq / num_vis);
}
else
{
oskar_log_error(log, "Incompatible or invalid visibility data type.");
return OSKAR_ERR_BAD_DATA_TYPE;
}
oskar_log_message(log, 'M', 0, "%s [%0*i/%i]", vis_filename[i].c_str(),
disp_width, i+1, num_files);
if (verbose)
{
oskar_log_message(log, 'S', 1, "No. baselines : %i",
oskar_vis_num_baselines(vis));
oskar_log_message(log, 'S', 1, "No. times : %i",
oskar_vis_num_times(vis));
oskar_log_message(log, 'S', 1, "No. channels : %i",
oskar_vis_num_channels(vis));
}
oskar_log_message(log, 'M', 1, "Stokes-I:");
oskar_log_message(log, 'M', 2, "Minimum : % 6.3e % +6.3ej Jy",
min.x, min.y);
oskar_log_message(log, 'M', 2, "Maximum : % 6.3e % +6.3ej Jy",
max.x, max.y);
oskar_log_message(log, 'M', 2, "Mean : % 6.3e % +6.3ej Jy",
mean.x, mean.y);
oskar_log_message(log, 'M', 2, "RMS : % 6.3e Jy", rms);
oskar_log_message(log, 'M', 2, "Zeros : %i/%i (%.1f%%)",
num_zero, num_vis, (double)(num_zero/num_vis)*100.0);
// Free visibility data.
oskar_vis_free(vis, &status);
} // end of loop over visibility files
oskar_log_section(log, 'M', "OSKAR-%s starting at %s.", OSKAR_VERSION_STR,
oskar_log_system_clock_string(0));
return status;
}
//------------------------------------------------------------------------------
void set_options(oskar_OptionParser& opt)
{
opt.setDescription("Application to generate some stats from an OSKAR visibility file.");
opt.addRequired("OSKAR visibility file(s)...");
opt.addFlag("-v", "Verbose");
}
bool check_options(oskar_OptionParser& opt, int argc, char** argv)
{
if (!opt.check_options(argc, argv))
return false;
return true;
}
void check_error(int status)
{
if (status != OSKAR_SUCCESS) {
cout << "ERROR: code[" << status << "] ";
cout << oskar_get_error_string(status) << endl;
exit(status);
}
}
<commit_msg>fixed integer div bug in vis stats printing<commit_after>/*
* Copyright (c) 2013-2015, The University of Oxford
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of the University of Oxford nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <apps/lib/oskar_OptionParser.h>
#include <oskar_log.h>
#include <oskar_get_error_string.h>
#include <oskar_vis.h>
#include <oskar_version_string.h>
#include <string>
#include <vector>
#include <cmath>
#include <iostream>
#include <cstdio>
#include <cfloat>
using namespace std;
//------------------------------------------------------------------------------
void set_options(oskar_OptionParser& opt);
bool check_options(oskar_OptionParser& opt, int argc, char** argv);
void check_error(int status);
//------------------------------------------------------------------------------
int main(int argc, char** argv)
{
int status = OSKAR_SUCCESS;
// Register options.
oskar_OptionParser opt("oskar_vis_stats", oskar_version_string());
set_options(opt);
if (!check_options(opt, argc, argv))
return OSKAR_FAIL;
// Retrieve options.
vector<string> vis_filename = opt.getArgs();
bool verbose = opt.isSet("-v") ? true : false;
int num_files = (int)vis_filename.size();
int disp_width = (num_files == 1) ? 1 : (int)log10(num_files)+1;
oskar_Log* log = 0;
oskar_log_section(log, 'M', "OSKAR-%s starting at %s.", OSKAR_VERSION_STR,
oskar_log_system_clock_string(0));
for (int i = 0; i < num_files; ++i)
{
oskar_Binary* h = oskar_binary_create(vis_filename[i].c_str(), 'r',
&status);
oskar_Vis* vis = oskar_vis_read(h, &status);
oskar_binary_free(h);
check_error(status);
int vis_type = oskar_mem_type(oskar_vis_amplitude(vis));
int num_vis = (int)oskar_mem_length(oskar_vis_amplitude(vis));
double abs_min = DBL_MAX;
double abs_max = -DBL_MAX;
double2 min;
min.x = DBL_MAX;
min.y = DBL_MAX;
double2 max;
max.x = -DBL_MAX;
max.y = -DBL_MAX;
double2 sum;
sum.x = 0.0;
sum.y = 0.0;
double sumsq = 0.0;
size_t num_zero = 0;
double rms = 0.0;
double2 mean;
mean.x = 0.0;
mean.y = 0.0;
if (vis_type == OSKAR_SINGLE_COMPLEX_MATRIX)
{
float4c* amp = oskar_mem_float4c(oskar_vis_amplitude(vis), &status);
for (int i = 0; i < num_vis; ++i)
{
double2 I; // I = 0.5 (XX + YY)
I.x = 0.5 * (amp[i].a.x + amp[i].d.x);
I.y = 0.5 * (amp[i].a.y + amp[i].d.y);
sum.x += I.x;
sum.y += I.y;
double absI = sqrt(I.x*I.x + I.y*I.y);
if (absI < DBL_MIN) num_zero++;
if (absI > abs_max) {
abs_max = absI;
max.x = I.x;
max.y = I.y;
}
if (absI < abs_min) {
abs_min = absI;
min.x = I.x;
min.y = I.y;
}
sumsq += absI * absI;
}
mean.x = sum.x / num_vis;
mean.y = sum.y / num_vis;
rms = sqrt(sumsq / num_vis);
}
else if (vis_type == OSKAR_DOUBLE_COMPLEX_MATRIX)
{
double4c* amp = oskar_mem_double4c(oskar_vis_amplitude(vis), &status);
for (int i = 0; i < num_vis; ++i)
{
double2 I; // I = 0.5 (XX + YY)
I.x = 0.5 * (amp[i].a.x + amp[i].d.x);
I.y = 0.5 * (amp[i].a.y + amp[i].d.y);
sum.x += I.x;
sum.y += I.y;
double absI = sqrt(I.x*I.x + I.y*I.y);
if (absI < DBL_MIN) num_zero++;
if (absI > abs_max) {
abs_max = absI;
max.x = I.x;
max.y = I.y;
}
if (absI < abs_min) {
abs_min = absI;
min.x = I.x;
min.y = I.y;
}
sumsq += absI * absI;
}
mean.x = sum.x / num_vis;
mean.y = sum.y / num_vis;
rms = sqrt(sumsq / num_vis);
}
else if (vis_type == OSKAR_SINGLE_COMPLEX)
{
float2* amp = oskar_mem_float2(oskar_vis_amplitude(vis), &status);
for (int i = 0; i < num_vis; ++i)
{
double2 I;
I.x = amp[i].x;
I.y = amp[i].y;
sum.x += I.x;
sum.y += I.y;
double absI = sqrt(I.x*I.x + I.y*I.y);
if (absI < DBL_MIN) num_zero++;
if (absI > abs_max) {
abs_max = absI;
max.x = I.x;
max.y = I.y;
}
if (absI < abs_min) {
abs_min = absI;
min.x = I.x;
min.y = I.y;
}
sumsq += absI * absI;
}
mean.x = sum.x / num_vis;
mean.y = sum.y / num_vis;
rms = sqrt(sumsq / num_vis);
}
else if (vis_type == OSKAR_DOUBLE_COMPLEX)
{
double2* amp = oskar_mem_double2(oskar_vis_amplitude(vis), &status);
for (int i = 0; i < num_vis; ++i)
{
double2 I;
I.x = amp[i].x;
I.y = amp[i].y;
sum.x += I.x;
sum.y += I.y;
double absI = sqrt(I.x*I.x + I.y*I.y);
if (absI < DBL_MIN) num_zero++;
if (absI > abs_max) {
abs_max = absI;
max.x = I.x;
max.y = I.y;
}
if (absI < abs_min) {
abs_min = absI;
min.x = I.x;
min.y = I.y;
}
sumsq += absI * absI;
}
mean.x = sum.x / num_vis;
mean.y = sum.y / num_vis;
rms = sqrt(sumsq / num_vis);
}
else
{
oskar_log_error(log, "Incompatible or invalid visibility data type.");
return OSKAR_ERR_BAD_DATA_TYPE;
}
oskar_log_message(log, 'M', 0, "%s [%0*i/%i]", vis_filename[i].c_str(),
disp_width, i+1, num_files);
if (verbose)
{
oskar_log_message(log, 'S', 1, "No. baselines : %i",
oskar_vis_num_baselines(vis));
oskar_log_message(log, 'S', 1, "No. times : %i",
oskar_vis_num_times(vis));
oskar_log_message(log, 'S', 1, "No. channels : %i",
oskar_vis_num_channels(vis));
}
oskar_log_message(log, 'M', 1, "Stokes-I:");
oskar_log_message(log, 'M', 2, "Minimum : % 6.3e % +6.3ej Jy",
min.x, min.y);
oskar_log_message(log, 'M', 2, "Maximum : % 6.3e % +6.3ej Jy",
max.x, max.y);
oskar_log_message(log, 'M', 2, "Mean : % 6.3e % +6.3ej Jy",
mean.x, mean.y);
oskar_log_message(log, 'M', 2, "RMS : % 6.3e Jy", rms);
oskar_log_message(log, 'M', 2, "Zeros : %i/%i (%.1f%%)",
num_zero, num_vis, ((double)num_zero/num_vis)*100.0);
// Free visibility data.
oskar_vis_free(vis, &status);
} // end of loop over visibility files
oskar_log_section(log, 'M', "OSKAR-%s starting at %s.", OSKAR_VERSION_STR,
oskar_log_system_clock_string(0));
return status;
}
//------------------------------------------------------------------------------
void set_options(oskar_OptionParser& opt)
{
opt.setDescription("Application to generate some stats from an OSKAR visibility file.");
opt.addRequired("OSKAR visibility file(s)...");
opt.addFlag("-v", "Verbose");
}
bool check_options(oskar_OptionParser& opt, int argc, char** argv)
{
if (!opt.check_options(argc, argv))
return false;
return true;
}
void check_error(int status)
{
if (status != OSKAR_SUCCESS) {
cout << "ERROR: code[" << status << "] ";
cout << oskar_get_error_string(status) << endl;
exit(status);
}
}
<|endoftext|>
|
<commit_before>/**
* @file ProcessTest.cpp
* @brief Process & PipeProcess class tester.
* @author zer0
* @date 2016-05-19
*/
#include <gtest/gtest.h>
#include <libtbag/process/Process.hpp>
#include <libtbag/process/PipeProcess.hpp>
#include <libtbag/filesystem/Path.hpp>
#include <libtbag/predef.hpp>
#include <fstream>
constexpr char const * const getProcessTestFileName() noexcept
{
#if __OS_WINDOWS__
return "process_test.exe";
#else
return "process_test";
#endif
}
using namespace libtbag;
using namespace libtbag::filesystem;
using namespace libtbag::process;
static bool runTestProgram(Process * process
, std::string const & arg1
, std::string const & arg2)
{
Path exe_dir = Path(common::getExeDir());
Path test_program = exe_dir / getProcessTestFileName();
std::vector<std::string> args;
args.push_back(arg1);
if (arg2.empty() == false) {
args.push_back(arg2);
}
process->setExecuteFile(test_program);
process->setArguments(args);
process->setWorkingDirectory(exe_dir);
process->setFlags(0);
return process->exe();
}
TEST(PipeProcessTest, StandardOutput)
{
std::string const TEST_STRING = "TEST_OUTPUT_MESSAGE";
std::string const EMPTY_STRING = "";
PipeProcess process;
ASSERT_TRUE(runTestProgram(&process, "out", TEST_STRING));
ASSERT_EQ(process.getExitStatus(), 0);
ASSERT_EQ(process.getTerminateSignal(), 0);
ASSERT_EQ(process.getStandardOutput(), TEST_STRING);
ASSERT_EQ(process.getStandardError(), EMPTY_STRING);
}
TEST(PipeProcessTest, StandardInput)
{
std::string const TEST_STRING = "TEST_INPUT";
std::string const INPUT_STRING = TEST_STRING + "\n";
std::string const EMPTY_STRING = "";
PipeProcess process;
process.setStandardInput(INPUT_STRING);
ASSERT_TRUE(runTestProgram(&process, "out", EMPTY_STRING));
ASSERT_EQ(process.getExitStatus(), 0);
ASSERT_EQ(process.getTerminateSignal(), 0);
ASSERT_EQ(process.getStandardOutput(), TEST_STRING);
ASSERT_EQ(process.getStandardError(), EMPTY_STRING);
}
TEST(PipeProcessTest, StandardError)
{
std::string const TEST_STRING = "TEST_ERROR_MESSAGE";
std::string const EMPTY_STRING = "";
PipeProcess process;
ASSERT_TRUE(runTestProgram(&process, "err", TEST_STRING));
ASSERT_EQ(process.getExitStatus(), 0);
ASSERT_EQ(process.getTerminateSignal(), 0);
ASSERT_EQ(process.getStandardOutput(), EMPTY_STRING);
ASSERT_EQ(process.getStandardError(), TEST_STRING);
}
TEST(PipeProcessTest, FileOutput)
{
filesystem::Path const TEST_FILE("__process_test_file.txt");
if (filesystem::common::existsFile(TEST_FILE)) {
filesystem::common::remove(TEST_FILE);
}
ASSERT_FALSE(filesystem::common::existsFile(TEST_FILE));
std::string const TEST_STRING = "TEST";
std::string const EMPTY_STRING = "";
PipeProcess process;
ASSERT_TRUE(runTestProgram(&process, "file", TEST_STRING));
ASSERT_EQ(process.getExitStatus(), 0);
ASSERT_EQ(process.getTerminateSignal(), 0);
ASSERT_EQ(process.getStandardOutput(), EMPTY_STRING);
ASSERT_EQ(process.getStandardError(), EMPTY_STRING);
ASSERT_TRUE(filesystem::common::existsFile(TEST_FILE));
ASSERT_TRUE(filesystem::common::isRegularFile(TEST_FILE));
std::ifstream file(TEST_FILE.getString());
std::string file_body;
file >> file_body;
file.close();
ASSERT_EQ(file_body, TEST_STRING);
}
TEST(ProcessTest, exit_code_failure)
{
Process process;
ASSERT_TRUE(runTestProgram(&process, "unknown", "unknown"));
ASSERT_EQ(process.getExitStatus(), 1);
ASSERT_EQ(process.getTerminateSignal(), 0);
}
<commit_msg>Set comment to ProcessTest.<commit_after>/**
* @file ProcessTest.cpp
* @brief Process & PipeProcess class tester.
* @author zer0
* @date 2016-05-19
*/
#include <gtest/gtest.h>
//#include <libtbag/process/Process.hpp>
//#include <libtbag/process/PipeProcess.hpp>
//#include <libtbag/filesystem/Path.hpp>
//#include <libtbag/predef.hpp>
//
//#include <fstream>
//
//constexpr char const * const getProcessTestFileName() noexcept
//{
//#if __OS_WINDOWS__
// return "process_test.exe";
//#else
// return "process_test";
//#endif
//}
//
//using namespace libtbag;
//using namespace libtbag::filesystem;
//using namespace libtbag::process;
//
//static bool runTestProgram(Process * process
// , std::string const & arg1
// , std::string const & arg2)
//{
// Path exe_dir = Path(common::getExeDir());
// Path test_program = exe_dir / getProcessTestFileName();
//
// std::vector<std::string> args;
// args.push_back(arg1);
// if (arg2.empty() == false) {
// args.push_back(arg2);
// }
//
// process->setExecuteFile(test_program);
// process->setArguments(args);
// process->setWorkingDirectory(exe_dir);
// process->setFlags(0);
//
// return process->exe();
//}
//
//TEST(PipeProcessTest, StandardOutput)
//{
// std::string const TEST_STRING = "TEST_OUTPUT_MESSAGE";
// std::string const EMPTY_STRING = "";
//
// PipeProcess process;
// ASSERT_TRUE(runTestProgram(&process, "out", TEST_STRING));
//
// ASSERT_EQ(process.getExitStatus(), 0);
// ASSERT_EQ(process.getTerminateSignal(), 0);
// ASSERT_EQ(process.getStandardOutput(), TEST_STRING);
// ASSERT_EQ(process.getStandardError(), EMPTY_STRING);
//}
//
//TEST(PipeProcessTest, StandardInput)
//{
// std::string const TEST_STRING = "TEST_INPUT";
// std::string const INPUT_STRING = TEST_STRING + "\n";
// std::string const EMPTY_STRING = "";
//
// PipeProcess process;
// process.setStandardInput(INPUT_STRING);
// ASSERT_TRUE(runTestProgram(&process, "out", EMPTY_STRING));
//
// ASSERT_EQ(process.getExitStatus(), 0);
// ASSERT_EQ(process.getTerminateSignal(), 0);
// ASSERT_EQ(process.getStandardOutput(), TEST_STRING);
// ASSERT_EQ(process.getStandardError(), EMPTY_STRING);
//}
//
//TEST(PipeProcessTest, StandardError)
//{
// std::string const TEST_STRING = "TEST_ERROR_MESSAGE";
// std::string const EMPTY_STRING = "";
//
// PipeProcess process;
// ASSERT_TRUE(runTestProgram(&process, "err", TEST_STRING));
//
// ASSERT_EQ(process.getExitStatus(), 0);
// ASSERT_EQ(process.getTerminateSignal(), 0);
// ASSERT_EQ(process.getStandardOutput(), EMPTY_STRING);
// ASSERT_EQ(process.getStandardError(), TEST_STRING);
//}
//
//TEST(PipeProcessTest, FileOutput)
//{
// filesystem::Path const TEST_FILE("__process_test_file.txt");
// if (filesystem::common::existsFile(TEST_FILE)) {
// filesystem::common::remove(TEST_FILE);
// }
// ASSERT_FALSE(filesystem::common::existsFile(TEST_FILE));
//
// std::string const TEST_STRING = "TEST";
// std::string const EMPTY_STRING = "";
//
// PipeProcess process;
// ASSERT_TRUE(runTestProgram(&process, "file", TEST_STRING));
//
// ASSERT_EQ(process.getExitStatus(), 0);
// ASSERT_EQ(process.getTerminateSignal(), 0);
// ASSERT_EQ(process.getStandardOutput(), EMPTY_STRING);
// ASSERT_EQ(process.getStandardError(), EMPTY_STRING);
//
// ASSERT_TRUE(filesystem::common::existsFile(TEST_FILE));
// ASSERT_TRUE(filesystem::common::isRegularFile(TEST_FILE));
//
// std::ifstream file(TEST_FILE.getString());
// std::string file_body;
// file >> file_body;
// file.close();
//
// ASSERT_EQ(file_body, TEST_STRING);
//}
//
//TEST(ProcessTest, exit_code_failure)
//{
// Process process;
// ASSERT_TRUE(runTestProgram(&process, "unknown", "unknown"));
//
// ASSERT_EQ(process.getExitStatus(), 1);
// ASSERT_EQ(process.getTerminateSignal(), 0);
//}
<|endoftext|>
|
<commit_before>#ifndef Cropping
#define Cropping
#define _CRT_SECURE_NO_DEPRECATE
#include "croppingTool.h"
#include "ClassifierTraining.h"
#include "opencv2/objdetect.hpp"
//#include "opencv2/videoio.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/imgproc.hpp"
#include <iostream>
#include <stdio.h>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
void detectAndDisplay(Mat frame);
void cropImageAndSave(Mat frame);
CascadeClassifier car_cascade;
String window_name = "Capture - detection";
//String car_cascade_name = "../data/xml/cascade-bee.xml";
int counter;
int posCount;
int negCount;
void nms(const vector<Rect>& srcRects,vector<cv::Rect>& resRects,float thresh)
{
resRects.clear();
const size_t size = srcRects.size();
if (!size)
{
return;
}
// Sort the bounding boxes by the bottom - right y - coordinate of the bounding box
std::multimap<int, size_t> idxs;
for (size_t i = 0; i < size; ++i)
{
idxs.insert(std::pair<int, size_t>(srcRects[i].br().y, i));
}
// keep looping while some indexes still remain in the indexes list
while (idxs.size() > 0)
{
// grab the last rectangle
auto lastElem = --std::end(idxs);
const cv::Rect& rect1 = srcRects[lastElem->second];
resRects.push_back(rect1);
idxs.erase(lastElem);
for (auto pos = std::begin(idxs); pos != std::end(idxs); )
{
// grab the current rectangle
const cv::Rect& rect2 = srcRects[pos->second];
float intArea = (rect1 & rect2).area();
float unionArea = rect1.area() + rect2.area() - intArea;
float overlap = intArea / unionArea;
// if there is sufficient overlap, suppress the current bounding box
if (overlap > thresh)
{
pos = idxs.erase(pos);
}
else
{
++pos;
}
}
}
}
void cropImageAndSave(Mat frame) {
Mat cleanFrame = frame.clone();
Mat croppedImage;
String cropped_window = "Cropped image";
String filename = "pos/image-";
string input = ""; // std string for input
Rect slidingWindow = Rect(0, 0, 300, 300);
bool saved = false;
bool forceQuit = false;
// how much to much the windows (x and y)
int shiftXBy = slidingWindow.width/10; int shiftYBy = slidingWindow.height/10;
for (int row = 0; slidingWindow.y + slidingWindow.height <= frame.size().height && !forceQuit; row++)
{
cout << "row" << endl;
for (int col = 0; slidingWindow.x + slidingWindow.width <= frame.size().width && !forceQuit; col++)
{
cout << slidingWindow << endl;
// get smaller image from original frame "clean" version (no rectangle)
croppedImage = cleanFrame(slidingWindow);
// show for user to confirm and label
imshow(cropped_window, croppedImage);
// show rectangles on image
if (col % 2 == row % 2) {
rectangle(frame, slidingWindow, Scalar(255, 0, 0), 1, 8, 0);
}
else {
rectangle(frame, slidingWindow, Scalar(0, 255, 0), 1, 8, 0);
}
imshow(window_name, frame);
char c = (char)waitKey(0);
if (c == 27) { forceQuit = true; break; } // escape
while (!saved) {
if (c == 'q') {
saved = true;
forceQuit = true;
}
else if (c == 'g') {
cout << "positive" << endl;
imwrite("images/pos/pos-img" + std::to_string(posCount) + ".jpg", croppedImage);
posCount++;
saved = true;
}
else if (c == 'f') {
cout << "negative" << endl;
imwrite("images/neg/neg-img" + std::to_string(negCount) + ".jpg", croppedImage);
negCount++;
saved = true;
}
else if (c == 's') {
cout << "skipping" << endl;
saved = true;
}
else
{
c = (char)waitKey(0);
if (c == 27) { forceQuit = true; break; }
}
}
// move sliding window to the right
slidingWindow.x += shiftXBy;
// new cropped image to save
saved = false;
}
// reset x for new row
slidingWindow.x = 0;
// move sliding window to the right
slidingWindow.y += shiftYBy;
}
}
void detectAndDisplay(Mat frame)
{
Mat frame_gray;
Mat resized_frame;
Mat resized_frame_gray;
std::vector<Rect> beesFound;
// useScaling == detect on small image and draw on bigger one
bool useScaling = true; // for detecting
bool drawOnOriginal = true; // for drawing
const int scale = 4;
// ==========================================================
// scale down image and find objects ========================
if (useScaling) {
// scale down the image by factor of variable "scale"
resized_frame = Mat(cvRound(frame.rows / scale), cvRound(frame.cols / scale), CV_8UC1);
resize(frame, resized_frame, resized_frame.size());
// turn to grayscale
cvtColor(resized_frame, resized_frame_gray, COLOR_BGR2GRAY);
equalizeHist(resized_frame_gray, resized_frame_gray);
//-- Detect beesFound on scaled image
car_cascade.detectMultiScale(resized_frame_gray, beesFound, 1.5, 2, 0 | CASCADE_SCALE_IMAGE, Size(30, 30));
}
else {
// turn to grayscale
cvtColor(frame, frame_gray, COLOR_BGR2GRAY);
equalizeHist(frame_gray, frame_gray);
// no scaling
car_cascade.detectMultiScale(frame_gray, beesFound, 1.5, 2, 0 | CASCADE_SCALE_IMAGE, Size(30, 30));
// original values
//face_cascade.detectMultiScale(frame_gray, beesFound, 1.1, 2, 0 | CASCADE_SCALE_IMAGE, Size(30, 30));
}
// ==========================================================
// draw on the image to show the items ======================
for (size_t i = 0; i < beesFound.size(); i++)
{
// print values for objects found
cout << "x : " << beesFound[i].x << " | y : " << beesFound[i].y << " | width : " << beesFound[i].width << " | height : " << beesFound[i].height << endl;
// draw on non-scaled image
if (drawOnOriginal) {
// draw rectangle
rectangle(frame, Rect((beesFound[i].x*scale), (beesFound[i].y*scale), (beesFound[i].width*scale), (beesFound[i].height*scale)), Scalar(0, 245, 0), 1 * scale, 8, 0);
}
else {
// draw rectangle
rectangle(resized_frame, Rect(beesFound[i].x, beesFound[i].y, beesFound[i].width, beesFound[i].height), Scalar(0, 245, 0), 1, 8, 0);
}
}
//-- Show what you got
if (drawOnOriginal)
cv::imshow(window_name, frame);
else
cv::imshow(window_name, resized_frame);
}
Mat DetectInFrame(Mat frame)
{
vector<cv::Rect> srcRects;
Size size(0, 0);
vector<cv::Rect> resRects;
int scale = 3;
int slidefactor = 4;
Mat cleanFrame = frame.clone();
Mat croppedImage;
char c;
//String cropped_window = "Cropped image";
//String filename = "pos/image-";
//string input = ""; // std string for input
//bool saved = false;
//bool forceQuit = false;
/*imshow("clean frame", cleanFrame);
c = waitKey(0);*/
Mat resized_frame(cvRound(frame.rows / scale), cvRound(frame.cols / scale), CV_32FC1);
resize(frame, resized_frame, resized_frame.size());
cleanFrame = resized_frame.clone();
Rect slidingWindow = Rect(0, 0, getImageHeight(), getImageHeight());
int box_counter = 0;
// how much to much the windows (x and y)
int shiftXBy = slidingWindow.width / slidefactor; int shiftYBy = slidingWindow.height / slidefactor;
for (int row = 0; slidingWindow.y + slidingWindow.height <= resized_frame.size().height; row++)
{
//cout << "row" << endl;
for (int col = 0; slidingWindow.x + slidingWindow.width <= resized_frame.size().width; col++)
{
//cout << slidingWindow << endl;
// get smaller image from original frame "clean" version (no rectangle)
croppedImage = cleanFrame(slidingWindow);
/*imshow("cropped", croppedImage);
c = waitKey(0);*/
// move sliding window to the right
if (isBee(croppedImage))
{
Rect scaled_sliding = Rect(slidingWindow.x * scale, slidingWindow.y * scale, slidingWindow.width * scale, slidingWindow.height * scale);
srcRects.push_back(scaled_sliding);
//rectangle(frame, scaled_sliding, Scalar(255, 0, 0), 1, 8, 0);
//box_counter++;
}
slidingWindow.x += shiftXBy;
}
// reset x for new row
slidingWindow.x = 0;
// move sliding window to the right
slidingWindow.y += shiftYBy;
}
nms(srcRects, resRects, 0.1f);
for (auto r : resRects)
{
rectangle(frame, r, Scalar(0, 255, 0), 2);
box_counter++;
}
putText(frame, to_string(box_counter), cvPoint(30, 150), FONT_HERSHEY_COMPLEX_SMALL, 10, cvScalar(0, 255, 0), 1, CV_AA);
//cout << box_counter << endl;
return frame;
}
#endif<commit_msg>start of using parallel_for loop in croppingTool<commit_after>#ifndef Cropping
#define Cropping
#define _CRT_SECURE_NO_DEPRECATE
#include "croppingTool.h"
#include "ClassifierTraining.h"
#include "opencv2/objdetect.hpp"
//#include "opencv2/videoio.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/imgproc.hpp"
#include <iostream>
#include <stdio.h>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
void detectAndDisplay(Mat frame);
void cropImageAndSave(Mat frame);
CascadeClassifier car_cascade;
String window_name = "Capture - detection";
//String car_cascade_name = "../data/xml/cascade-bee.xml";
int counter;
int posCount;
int negCount;
class Scanloop : public ParallelLoopBody
{
public:
Scanloop(Rect slidingWindow, Mat &croppedImage, Mat &cleanFrame, int scale, Mat &resized_frame, int shiftXBy, vector<Rect>& srcRects)
: slidingWindow_l(slidingWindow_l), croppedImage_l(croppedImage), cleanFrame_l(cleanFrame), scale_l(scale), resized_frame_l(resized_frame), shiftXBy_l(shiftXBy), srcRects_l(srcRects)
{
}
void operator()(const Range& range) const override
{
Mat croppedclone = croppedImage_l.clone();
Rect slidingwindowclone = slidingWindow_l;
for (int col = 0; slidingWindow_l.x + slidingWindow_l.width <= resized_frame_l.size().width; col++)
{
//cout << slidingWindow << endl;
// get smaller image from original frame "clean" version (no rectangle)
croppedclone = cleanFrame_l(slidingWindow_l);
/*imshow("cropped", croppedImage);
c = waitKey(0);*/
// check if there is a bee in the cropped area
if (isBee(croppedImage_l))
{
// move sliding window to the right
Rect scaled_sliding = Rect(slidingWindow_l.x * scale_l, slidingWindow_l.y * scale_l, slidingWindow_l.width * scale_l, slidingWindow_l.height * scale_l);
// save the rectangles
srcRects_l .push_back(scaled_sliding);
//rectangle(frame, scaled_sliding, Scalar(255, 0, 0), 1, 8, 0);
//box_counter++;
}
slidingwindowclone.x += shiftXBy_l;
}
}
private:
Rect slidingWindow_l;
Mat croppedImage_l;
Mat cleanFrame_l;
int scale_l;
Mat resized_frame_l;
int shiftXBy_l;
vector<Rect>& srcRects_l;
};
void nms(const vector<Rect>& srcRects,vector<cv::Rect>& resRects,float thresh)
{
resRects.clear();
const size_t size = srcRects.size();
if (!size)
{
return;
}
// Sort the bounding boxes by the bottom - right y - coordinate of the bounding box
std::multimap<int, size_t> idxs;
for (size_t i = 0; i < size; ++i)
{
idxs.insert(std::pair<int, size_t>(srcRects[i].br().y, i));
}
// keep looping while some indexes still remain in the indexes list
while (idxs.size() > 0)
{
// grab the last rectangle
auto lastElem = --std::end(idxs);
const cv::Rect& rect1 = srcRects[lastElem->second];
resRects.push_back(rect1);
idxs.erase(lastElem);
for (auto pos = std::begin(idxs); pos != std::end(idxs); )
{
// grab the current rectangle
const cv::Rect& rect2 = srcRects[pos->second];
float intArea = (rect1 & rect2).area();
float unionArea = rect1.area() + rect2.area() - intArea;
float overlap = intArea / unionArea;
// if there is sufficient overlap, suppress the current bounding box
if (overlap > thresh)
{
pos = idxs.erase(pos);
}
else
{
++pos;
}
}
}
}
void cropImageAndSave(Mat frame) {
Mat cleanFrame = frame.clone();
Mat croppedImage;
String cropped_window = "Cropped image";
String filename = "pos/image-";
string input = ""; // std string for input
Rect slidingWindow = Rect(0, 0, 300, 300);
bool saved = false;
bool forceQuit = false;
// how much to much the windows (x and y)
int shiftXBy = slidingWindow.width/10; int shiftYBy = slidingWindow.height/10;
for (int row = 0; slidingWindow.y + slidingWindow.height <= frame.size().height && !forceQuit; row++)
{
cout << "row" << endl;
for (int col = 0; slidingWindow.x + slidingWindow.width <= frame.size().width && !forceQuit; col++)
{
cout << slidingWindow << endl;
// get smaller image from original frame "clean" version (no rectangle)
croppedImage = cleanFrame(slidingWindow);
// show for user to confirm and label
imshow(cropped_window, croppedImage);
// show rectangles on image
if (col % 2 == row % 2) {
rectangle(frame, slidingWindow, Scalar(255, 0, 0), 1, 8, 0);
}
else {
rectangle(frame, slidingWindow, Scalar(0, 255, 0), 1, 8, 0);
}
imshow(window_name, frame);
char c = (char)waitKey(0);
if (c == 27) { forceQuit = true; break; } // escape
while (!saved) {
if (c == 'q') {
saved = true;
forceQuit = true;
}
else if (c == 'g') {
cout << "positive" << endl;
imwrite("images/pos/pos-img" + std::to_string(posCount) + ".jpg", croppedImage);
posCount++;
saved = true;
}
else if (c == 'f') {
cout << "negative" << endl;
imwrite("images/neg/neg-img" + std::to_string(negCount) + ".jpg", croppedImage);
negCount++;
saved = true;
}
else if (c == 's') {
cout << "skipping" << endl;
saved = true;
}
else
{
c = (char)waitKey(0);
if (c == 27) { forceQuit = true; break; }
}
}
// move sliding window to the right
slidingWindow.x += shiftXBy;
// new cropped image to save
saved = false;
}
// reset x for new row
slidingWindow.x = 0;
// move sliding window to the right
slidingWindow.y += shiftYBy;
}
}
void detectAndDisplay(Mat frame)
{
Mat frame_gray;
Mat resized_frame;
Mat resized_frame_gray;
std::vector<Rect> beesFound;
// useScaling == detect on small image and draw on bigger one
bool useScaling = true; // for detecting
bool drawOnOriginal = true; // for drawing
const int scale = 4;
// ==========================================================
// scale down image and find objects ========================
if (useScaling) {
// scale down the image by factor of variable "scale"
resized_frame = Mat(cvRound(frame.rows / scale), cvRound(frame.cols / scale), CV_8UC1);
resize(frame, resized_frame, resized_frame.size());
// turn to grayscale
cvtColor(resized_frame, resized_frame_gray, COLOR_BGR2GRAY);
equalizeHist(resized_frame_gray, resized_frame_gray);
//-- Detect beesFound on scaled image
car_cascade.detectMultiScale(resized_frame_gray, beesFound, 1.5, 2, 0 | CASCADE_SCALE_IMAGE, Size(30, 30));
}
else {
// turn to grayscale
cvtColor(frame, frame_gray, COLOR_BGR2GRAY);
equalizeHist(frame_gray, frame_gray);
// no scaling
car_cascade.detectMultiScale(frame_gray, beesFound, 1.5, 2, 0 | CASCADE_SCALE_IMAGE, Size(30, 30));
// original values
//face_cascade.detectMultiScale(frame_gray, beesFound, 1.1, 2, 0 | CASCADE_SCALE_IMAGE, Size(30, 30));
}
// ==========================================================
// draw on the image to show the items ======================
for (size_t i = 0; i < beesFound.size(); i++)
{
// print values for objects found
cout << "x : " << beesFound[i].x << " | y : " << beesFound[i].y << " | width : " << beesFound[i].width << " | height : " << beesFound[i].height << endl;
// draw on non-scaled image
if (drawOnOriginal) {
// draw rectangle
rectangle(frame, Rect((beesFound[i].x*scale), (beesFound[i].y*scale), (beesFound[i].width*scale), (beesFound[i].height*scale)), Scalar(0, 245, 0), 1 * scale, 8, 0);
}
else {
// draw rectangle
rectangle(resized_frame, Rect(beesFound[i].x, beesFound[i].y, beesFound[i].width, beesFound[i].height), Scalar(0, 245, 0), 1, 8, 0);
}
}
//-- Show what you got
if (drawOnOriginal)
cv::imshow(window_name, frame);
else
cv::imshow(window_name, resized_frame);
}
Mat DetectInFrame(Mat frame)
{
vector<cv::Rect> srcRects;
Size size(0, 0);
vector<cv::Rect> resRects;
int scale = 3;
int slidefactor = 4;
Mat cleanFrame = frame.clone();
Mat croppedImage;
char c;
//String cropped_window = "Cropped image";
//String filename = "pos/image-";
//string input = ""; // std string for input
//bool saved = false;
//bool forceQuit = false;
/*imshow("clean frame", cleanFrame);
c = waitKey(0);*/
Mat resized_frame(cvRound(frame.rows / scale), cvRound(frame.cols / scale), CV_32FC1);
resize(frame, resized_frame, resized_frame.size());
cleanFrame = resized_frame.clone();
Rect slidingWindow = Rect(0, 0, getImageHeight(), getImageHeight());
int box_counter = 0;
// how much to much the windows (x and y)
int shiftXBy = slidingWindow.width / slidefactor; int shiftYBy = slidingWindow.height / slidefactor;
for (int row = 0; slidingWindow.y + slidingWindow.height <= resized_frame.size().height; row++)
{
///attempt at parallizing
/*Scanloop parallelScan(slidingWindow,croppedImage, cleanFrame, scale, resized_frame, shiftXBy, srcRects);
parallel_for_(Range{ slidingWindow.x + slidingWindow.width,resized_frame.size().width }, parallelScan);*/
//cout << "row" << endl;
for (int col = 0; slidingWindow.x + slidingWindow.width <= resized_frame.size().width; col++)
{
//cout << slidingWindow << endl;
// get smaller image from original frame "clean" version (no rectangle)
croppedImage = cleanFrame(slidingWindow);
/*imshow("cropped", croppedImage);
c = waitKey(0);*/
// check if there is a bee in the cropped area
if (isBee(croppedImage))
{
// move sliding window to the right
Rect scaled_sliding = Rect(slidingWindow.x * scale, slidingWindow.y * scale, slidingWindow.width * scale, slidingWindow.height * scale);
// save the rectangles
srcRects.push_back(scaled_sliding);
//rectangle(frame, scaled_sliding, Scalar(255, 0, 0), 1, 8, 0);
//box_counter++;
}
slidingWindow.x += shiftXBy;
}
// reset x for new row
slidingWindow.x = 0;
// move sliding window to the right
slidingWindow.y += shiftYBy;
}
// perform non-maximum suppression (reduce rect)
nms(srcRects, resRects, 0.1f);
// draw the rectangles
for (auto r : resRects)
{
rectangle(frame, r, Scalar(0, 255, 0), 2);
box_counter++;
}
// display rect number
putText(frame, to_string(box_counter), cvPoint(30, 150), FONT_HERSHEY_COMPLEX_SMALL, 10, cvScalar(0, 255, 0), 1, CV_AA);
//cout << box_counter << endl;
return frame;
}
#endif<|endoftext|>
|
<commit_before>#ifndef __EVENT_HXX
#define __EVENT_HXX
#include <sal/types.h>
#include <cppuhelper/implbase1.hxx>
#include <cppuhelper/implbase2.hxx>
#include <cppuhelper/implbase3.hxx>
#include <com/sun/star/uno/Reference.h>
#include <com/sun/star/uno/Exception.hpp>
#include <com/sun/star/xml/dom/events/XEventTarget.hpp>
#include <com/sun/star/util/Time.hpp>
#include "../dom/node.hxx"
#include <libxml/tree.h>
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::xml::dom;
using namespace com::sun::star::xml::dom::events;
namespace DOM {namespace events
{
class CEvent : public cppu::WeakImplHelper1< XEvent >
{
friend class CEventDispatcher;
friend class CNode;
friend class CDocument;
friend class CElement;
friend class CText;
friend class CCharacterData;
friend class CAttr;
private:
sal_Bool m_canceled;
protected:
OUString m_eventType;
Reference< XEventTarget > m_target;
Reference< XEventTarget > m_currentTarget;
//xmlNodePtr m_target;
//xmlNodePtr m_currentTarget;
PhaseType m_phase;
sal_Bool m_bubbles;
sal_Bool m_cancelable;
com::sun::star::util::Time m_time;
public:
CEvent() : m_canceled(sal_False){}
virtual ~CEvent();
virtual OUString SAL_CALL getType() throw (RuntimeException);
virtual Reference< XEventTarget > SAL_CALL getTarget() throw (RuntimeException);
virtual Reference< XEventTarget > SAL_CALL getCurrentTarget() throw (RuntimeException);
virtual PhaseType SAL_CALL getEventPhase() throw (RuntimeException);
virtual sal_Bool SAL_CALL getBubbles() throw (RuntimeException);
virtual sal_Bool SAL_CALL getCancelable() throw (RuntimeException);
virtual com::sun::star::util::Time SAL_CALL getTimeStamp() throw (RuntimeException);
virtual void SAL_CALL stopPropagation() throw (RuntimeException);
virtual void SAL_CALL preventDefault() throw (RuntimeException);
virtual void SAL_CALL initEvent(
const OUString& eventTypeArg,
sal_Bool canBubbleArg,
sal_Bool cancelableArg) throw (RuntimeException);
};
}}
#endif
<commit_msg>INTEGRATION: CWS updchk10 (1.3.70); FILE MERGED 2007/09/14 16:19:52 lo 1.3.70.1: #i81589# xml serialization<commit_after>#ifndef __EVENT_HXX
#define __EVENT_HXX
#include <sal/types.h>
#include <cppuhelper/implbase1.hxx>
#include <cppuhelper/implbase2.hxx>
#include <cppuhelper/implbase3.hxx>
#include <com/sun/star/uno/Reference.h>
#include <com/sun/star/uno/Exception.hpp>
#include <com/sun/star/xml/dom/events/XEventTarget.hpp>
#include <com/sun/star/util/Time.hpp>
#include "../dom/node.hxx"
#include <libxml/tree.h>
using namespace com::sun::star::uno;
using namespace com::sun::star::xml::dom;
using namespace com::sun::star::xml::dom::events;
namespace DOM {namespace events
{
class CEvent : public cppu::WeakImplHelper1< XEvent >
{
friend class CEventDispatcher;
friend class CNode;
friend class CDocument;
friend class CElement;
friend class CText;
friend class CCharacterData;
friend class CAttr;
private:
sal_Bool m_canceled;
protected:
OUString m_eventType;
Reference< XEventTarget > m_target;
Reference< XEventTarget > m_currentTarget;
//xmlNodePtr m_target;
//xmlNodePtr m_currentTarget;
PhaseType m_phase;
sal_Bool m_bubbles;
sal_Bool m_cancelable;
com::sun::star::util::Time m_time;
public:
CEvent() : m_canceled(sal_False){}
virtual ~CEvent();
virtual OUString SAL_CALL getType() throw (RuntimeException);
virtual Reference< XEventTarget > SAL_CALL getTarget() throw (RuntimeException);
virtual Reference< XEventTarget > SAL_CALL getCurrentTarget() throw (RuntimeException);
virtual PhaseType SAL_CALL getEventPhase() throw (RuntimeException);
virtual sal_Bool SAL_CALL getBubbles() throw (RuntimeException);
virtual sal_Bool SAL_CALL getCancelable() throw (RuntimeException);
virtual com::sun::star::util::Time SAL_CALL getTimeStamp() throw (RuntimeException);
virtual void SAL_CALL stopPropagation() throw (RuntimeException);
virtual void SAL_CALL preventDefault() throw (RuntimeException);
virtual void SAL_CALL initEvent(
const OUString& eventTypeArg,
sal_Bool canBubbleArg,
sal_Bool cancelableArg) throw (RuntimeException);
};
}}
#endif
<|endoftext|>
|
<commit_before>/////////////////////////////////////////////////////////////////////////////
// Original authors: SangGi Do(sanggido@unist.ac.kr), Mingyu Woo(mwoo@eng.ucsd.edu)
// (respective Ph.D. advisors: Seokhyeong Kang, Andrew B. Kahng)
// Rewrite by James Cherry, Parallax Software, Inc.
// BSD 3-Clause License
//
// Copyright (c) 2019, James Cherry, Parallax Software, Inc.
// Copyright (c) 2018, SangGi Do and Mingyu Woo
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
///////////////////////////////////////////////////////////////////////////////
#include <cmath>
#include <limits>
#include "openroad/Error.hh"
#include "opendp/Opendp.h"
namespace opendp {
using std::cerr;
using std::cout;
using std::endl;
using std::max;
using std::min;
using std::abs;
using std::round;
using std::numeric_limits;
using ord::error;
void Opendp::initGrid() {
// Make pixel grid
grid_ = makeGrid();
// Fragmented Row Handling
for(auto db_row : block_->getRows()) {
int orig_x, orig_y;
db_row->getOrigin(orig_x, orig_y);
int x_start = (orig_x - core_.xMin()) / site_width_;
int y_start = (orig_y - core_.yMin()) / row_height_;
int x_end = x_start + db_row->getSiteCount();
int y_end = y_start + 1;
for(int i = x_start; i < x_end; i++) {
for(int j = y_start; j < y_end; j++) {
grid_[j][i].is_valid = true;
}
}
}
// fixed cell marking
fixed_cell_assign();
// group mapping & x_axis dummycell insertion
group_pixel_assign2();
// y axis dummycell insertion
group_pixel_assign();
}
Grid *
Opendp::makeGrid()
{
Grid *grid = new Pixel*[row_count_];
for(int i = 0; i < row_count_; i++) {
grid[i] = new Pixel[row_site_count_];
for(int j = 0; j < row_site_count_; j++) {
Pixel &pixel = grid[i][j];
pixel.grid_y_ = i;
pixel.grid_x_ = j;
pixel.cell = nullptr;
pixel.group_ = nullptr;
pixel.util = 0.0;
pixel.is_valid = false;
}
}
return grid;
}
void
Opendp::deleteGrid(Grid *grid)
{
if (grid) {
for(int i = 0; i < row_count_; i++) {
delete [] grid[i];
}
delete grid;
}
}
////////////////////////////////////////////////////////////////
void Opendp::fixed_cell_assign() {
for(Cell &cell : cells_) {
if(isFixed(&cell)) {
int y_start = gridY(&cell);
int y_end = gridEndY(&cell);
int x_start = gridPaddedX(&cell);
int x_end = gridPaddedEndX(&cell);
int y_start_rf = 0;
int y_end_rf = gridEndY();
int x_start_rf = 0;
int x_end_rf = gridEndX();
y_start = max(y_start, y_start_rf);
y_end = min(y_end, y_end_rf);
x_start = max(x_start, x_start_rf);
x_end = min(x_end, x_end_rf);
#ifdef ODP_DEBUG
cout << "FixedCellAssign: cell_name : "
<< cell.name() << endl;
cout << "FixedCellAssign: y_start : " << y_start << endl;
cout << "FixedCellAssign: y_end : " << y_end << endl;
cout << "FixedCellAssign: x_start : " << x_start << endl;
cout << "FixedCellAssign: x_end : " << x_end << endl;
#endif
for(int j = y_start; j < y_end; j++) {
for(int k = x_start; k < x_end; k++) {
Pixel &pixel = grid_[j][k];
pixel.cell = &cell;
pixel.util = 1.0;
}
}
}
}
}
void Opendp::group_cell_region_assign() {
for(Group& group : groups_) {
int64_t site_count = 0;
for(int j = 0; j < row_count_; j++) {
for(int k = 0; k < row_site_count_; k++) {
Pixel &pixel = grid_[j][k];
if(pixel.is_valid
&& pixel.group_ == &group)
site_count++;
}
}
int64_t area = site_count * site_width_ * row_height_;
int64_t cell_area = 0;
for(Cell* cell : group.cells_) {
cell_area += cell->area();
for(Rect &rect : group.regions) {
if (check_inside(cell, &rect))
cell->region_ = ▭
}
if(cell->region_ == nullptr)
cell->region_ = &group.regions[0];
}
group.util = static_cast<double>(cell_area) / area;
}
}
void Opendp::group_pixel_assign2() {
for(int i = 0; i < row_count_; i++) {
for(int j = 0; j < row_site_count_; j++) {
Rect sub;
sub.init(j * site_width_, i * row_height_,
(j + 1) * site_width_, (i + 1) * row_height_);
for(Group& group : groups_) {
for(Rect &rect : group.regions) {
if(!check_inside(sub, rect) &&
check_overlap(sub, rect)) {
Pixel &pixel = grid_[i][j];
pixel.util = 0.0;
pixel.cell = &dummy_cell_;
pixel.is_valid = false;
}
}
}
}
}
}
void Opendp::group_pixel_assign() {
for(int i = 0; i < row_count_; i++) {
for(int j = 0; j < row_site_count_; j++) {
grid_[i][j].util = 0.0;
}
}
for(Group& group : groups_) {
for(Rect &rect : group.regions) {
int row_start = divCeil(rect.yMin(), row_height_);
int row_end = divFloor(rect.yMax(), row_height_);
for(int k = row_start; k < row_end; k++) {
int col_start = divCeil(rect.xMin(), site_width_);
int col_end = divFloor(rect.xMax(), site_width_);
for(int l = col_start; l < col_end; l++) {
grid_[k][l].util += 1.0;
}
if(rect.xMin() % site_width_ != 0) {
grid_[k][col_start].util -=
(rect.xMin() % site_width_) / static_cast<double>(site_width_);
}
if(rect.xMax() % site_width_ != 0) {
grid_[k][col_end - 1].util -=
((site_width_ - rect.xMax()) % site_width_) / static_cast<double>(site_width_);
}
}
}
for(Rect& rect : group.regions) {
int row_start = divCeil(rect.yMin(), row_height_);
int row_end = divFloor(rect.yMax(), row_height_);
for(int k = row_start; k < row_end; k++) {
int col_start = divCeil(rect.xMin(), site_width_);
int col_end = divFloor(rect.xMax(), site_width_);
// Assign group to each pixel.
for(int l = col_start; l < col_end; l++) {
Pixel &pixel = grid_[k][l];
if(pixel.util == 1.0) {
pixel.group_ = &group;
pixel.is_valid = true;
pixel.util = 1.0;
}
else if(pixel.util > 0.0 && pixel.util < 1.0) {
pixel.cell = &dummy_cell_;
pixel.util = 0.0;
pixel.is_valid = false;
}
}
}
}
}
}
void Opendp::erase_pixel(Cell* cell) {
if(!(isFixed(cell) || !cell->is_placed_)) {
int x_step = gridPaddedWidth(cell);
int y_step = gridHeight(cell);
for(int i = gridY(cell); i < gridY(cell) + y_step; i++) {
for(int j = gridPaddedX(cell); j < gridPaddedX(cell) + x_step; j++) {
Pixel &pixel = grid_[i][j];
pixel.cell = nullptr;
pixel.util = 0;
}
}
cell->x_ = 0;
cell->y_ = 0;
cell->is_placed_ = false;
cell->hold_ = false;
}
}
void Opendp::paint_pixel(Cell* cell, int grid_x, int grid_y) {
assert(!cell->is_placed_);
int x_step = gridPaddedWidth(cell);
int y_step = gridHeight(cell);
setGridPaddedLoc(cell, grid_x, grid_y);
cell->is_placed_ = true;
#ifdef ODP_DEBUG
cout << "paint cell : " << cell->name() << endl;
cout << "x_ - y_ : " << cell->x_ << " - "
<< cell->y_ << endl;
cout << "x_step - y_step : " << x_step << " - " << y_step << endl;
cout << "grid_x - grid_y : " << grid_x << " - " << grid_y << endl;
#endif
for(int i = grid_y; i < grid_y + y_step; i++) {
for(int j = grid_x; j < grid_x + x_step; j++) {
Pixel &pixel = grid_[i][j];
if(pixel.cell != nullptr) {
error("Cannot paint grid because it is already occupied.");
}
else {
pixel.cell = cell;
pixel.util = 1.0;
}
}
}
if(max_cell_height_ > 1) {
if(y_step % 2 == 1) {
if(rowTopPower(grid_y) != topPower(cell))
cell->orient_ = dbOrientType::MX;
else
cell->orient_ = dbOrientType::R0;
}
}
else {
cell->orient_ = rowOrient(grid_y);
}
}
} // namespace opendp
<commit_msg>opendp erase_pixel do not zero xy<commit_after>/////////////////////////////////////////////////////////////////////////////
// Original authors: SangGi Do(sanggido@unist.ac.kr), Mingyu Woo(mwoo@eng.ucsd.edu)
// (respective Ph.D. advisors: Seokhyeong Kang, Andrew B. Kahng)
// Rewrite by James Cherry, Parallax Software, Inc.
// BSD 3-Clause License
//
// Copyright (c) 2019, James Cherry, Parallax Software, Inc.
// Copyright (c) 2018, SangGi Do and Mingyu Woo
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
///////////////////////////////////////////////////////////////////////////////
#include <cmath>
#include <limits>
#include "openroad/Error.hh"
#include "opendp/Opendp.h"
namespace opendp {
using std::cerr;
using std::cout;
using std::endl;
using std::max;
using std::min;
using std::abs;
using std::round;
using std::numeric_limits;
using ord::error;
void Opendp::initGrid() {
// Make pixel grid
grid_ = makeGrid();
// Fragmented Row Handling
for(auto db_row : block_->getRows()) {
int orig_x, orig_y;
db_row->getOrigin(orig_x, orig_y);
int x_start = (orig_x - core_.xMin()) / site_width_;
int y_start = (orig_y - core_.yMin()) / row_height_;
int x_end = x_start + db_row->getSiteCount();
int y_end = y_start + 1;
for(int i = x_start; i < x_end; i++) {
for(int j = y_start; j < y_end; j++) {
grid_[j][i].is_valid = true;
}
}
}
// fixed cell marking
fixed_cell_assign();
// group mapping & x_axis dummycell insertion
group_pixel_assign2();
// y axis dummycell insertion
group_pixel_assign();
}
Grid *
Opendp::makeGrid()
{
Grid *grid = new Pixel*[row_count_];
for(int i = 0; i < row_count_; i++) {
grid[i] = new Pixel[row_site_count_];
for(int j = 0; j < row_site_count_; j++) {
Pixel &pixel = grid[i][j];
pixel.grid_y_ = i;
pixel.grid_x_ = j;
pixel.cell = nullptr;
pixel.group_ = nullptr;
pixel.util = 0.0;
pixel.is_valid = false;
}
}
return grid;
}
void
Opendp::deleteGrid(Grid *grid)
{
if (grid) {
for(int i = 0; i < row_count_; i++) {
delete [] grid[i];
}
delete grid;
}
}
////////////////////////////////////////////////////////////////
void Opendp::fixed_cell_assign() {
for(Cell &cell : cells_) {
if(isFixed(&cell)) {
int y_start = gridY(&cell);
int y_end = gridEndY(&cell);
int x_start = gridPaddedX(&cell);
int x_end = gridPaddedEndX(&cell);
int y_start_rf = 0;
int y_end_rf = gridEndY();
int x_start_rf = 0;
int x_end_rf = gridEndX();
y_start = max(y_start, y_start_rf);
y_end = min(y_end, y_end_rf);
x_start = max(x_start, x_start_rf);
x_end = min(x_end, x_end_rf);
#ifdef ODP_DEBUG
cout << "FixedCellAssign: cell_name : "
<< cell.name() << endl;
cout << "FixedCellAssign: y_start : " << y_start << endl;
cout << "FixedCellAssign: y_end : " << y_end << endl;
cout << "FixedCellAssign: x_start : " << x_start << endl;
cout << "FixedCellAssign: x_end : " << x_end << endl;
#endif
for(int j = y_start; j < y_end; j++) {
for(int k = x_start; k < x_end; k++) {
Pixel &pixel = grid_[j][k];
pixel.cell = &cell;
pixel.util = 1.0;
}
}
}
}
}
void Opendp::group_cell_region_assign() {
for(Group& group : groups_) {
int64_t site_count = 0;
for(int j = 0; j < row_count_; j++) {
for(int k = 0; k < row_site_count_; k++) {
Pixel &pixel = grid_[j][k];
if(pixel.is_valid
&& pixel.group_ == &group)
site_count++;
}
}
int64_t area = site_count * site_width_ * row_height_;
int64_t cell_area = 0;
for(Cell* cell : group.cells_) {
cell_area += cell->area();
for(Rect &rect : group.regions) {
if (check_inside(cell, &rect))
cell->region_ = ▭
}
if(cell->region_ == nullptr)
cell->region_ = &group.regions[0];
}
group.util = static_cast<double>(cell_area) / area;
}
}
void Opendp::group_pixel_assign2() {
for(int i = 0; i < row_count_; i++) {
for(int j = 0; j < row_site_count_; j++) {
Rect sub;
sub.init(j * site_width_, i * row_height_,
(j + 1) * site_width_, (i + 1) * row_height_);
for(Group& group : groups_) {
for(Rect &rect : group.regions) {
if(!check_inside(sub, rect) &&
check_overlap(sub, rect)) {
Pixel &pixel = grid_[i][j];
pixel.util = 0.0;
pixel.cell = &dummy_cell_;
pixel.is_valid = false;
}
}
}
}
}
}
void Opendp::group_pixel_assign() {
for(int i = 0; i < row_count_; i++) {
for(int j = 0; j < row_site_count_; j++) {
grid_[i][j].util = 0.0;
}
}
for(Group& group : groups_) {
for(Rect &rect : group.regions) {
int row_start = divCeil(rect.yMin(), row_height_);
int row_end = divFloor(rect.yMax(), row_height_);
for(int k = row_start; k < row_end; k++) {
int col_start = divCeil(rect.xMin(), site_width_);
int col_end = divFloor(rect.xMax(), site_width_);
for(int l = col_start; l < col_end; l++) {
grid_[k][l].util += 1.0;
}
if(rect.xMin() % site_width_ != 0) {
grid_[k][col_start].util -=
(rect.xMin() % site_width_) / static_cast<double>(site_width_);
}
if(rect.xMax() % site_width_ != 0) {
grid_[k][col_end - 1].util -=
((site_width_ - rect.xMax()) % site_width_) / static_cast<double>(site_width_);
}
}
}
for(Rect& rect : group.regions) {
int row_start = divCeil(rect.yMin(), row_height_);
int row_end = divFloor(rect.yMax(), row_height_);
for(int k = row_start; k < row_end; k++) {
int col_start = divCeil(rect.xMin(), site_width_);
int col_end = divFloor(rect.xMax(), site_width_);
// Assign group to each pixel.
for(int l = col_start; l < col_end; l++) {
Pixel &pixel = grid_[k][l];
if(pixel.util == 1.0) {
pixel.group_ = &group;
pixel.is_valid = true;
pixel.util = 1.0;
}
else if(pixel.util > 0.0 && pixel.util < 1.0) {
pixel.cell = &dummy_cell_;
pixel.util = 0.0;
pixel.is_valid = false;
}
}
}
}
}
}
void Opendp::erase_pixel(Cell* cell) {
if(!(isFixed(cell) || !cell->is_placed_)) {
int x_step = gridPaddedWidth(cell);
int y_step = gridHeight(cell);
for(int i = gridY(cell); i < gridY(cell) + y_step; i++) {
for(int j = gridPaddedX(cell); j < gridPaddedX(cell) + x_step; j++) {
Pixel &pixel = grid_[i][j];
pixel.cell = nullptr;
pixel.util = 0;
}
}
cell->is_placed_ = false;
cell->hold_ = false;
}
}
void Opendp::paint_pixel(Cell* cell, int grid_x, int grid_y) {
assert(!cell->is_placed_);
int x_step = gridPaddedWidth(cell);
int y_step = gridHeight(cell);
setGridPaddedLoc(cell, grid_x, grid_y);
cell->is_placed_ = true;
#ifdef ODP_DEBUG
cout << "paint cell : " << cell->name() << endl;
cout << "x_ - y_ : " << cell->x_ << " - "
<< cell->y_ << endl;
cout << "x_step - y_step : " << x_step << " - " << y_step << endl;
cout << "grid_x - grid_y : " << grid_x << " - " << grid_y << endl;
#endif
for(int i = grid_y; i < grid_y + y_step; i++) {
for(int j = grid_x; j < grid_x + x_step; j++) {
Pixel &pixel = grid_[i][j];
if(pixel.cell != nullptr) {
error("Cannot paint grid because it is already occupied.");
}
else {
pixel.cell = cell;
pixel.util = 1.0;
}
}
}
if(max_cell_height_ > 1) {
if(y_step % 2 == 1) {
if(rowTopPower(grid_y) != topPower(cell))
cell->orient_ = dbOrientType::MX;
else
cell->orient_ = dbOrientType::R0;
}
}
else {
cell->orient_ = rowOrient(grid_y);
}
}
} // namespace opendp
<|endoftext|>
|
<commit_before>#include <stdio.h>
#include <memory.h>
#include <assert.h>
#include <stdlib.h>
#include "halide_benchmark.h"
#include "process.h"
void usage(char *prg_name) {
const char usage_string[] = " Run a bunch of small filters\n\n"
"\t -m -> hvx_mode - options are hvx64, hvx128. Default is to run hvx64, hvx128 and cpu\n"
"\t -n -> number of iterations\n"
"\t -h -> print this help message\n";
printf ("%s - %s", prg_name, usage_string);
}
const char *to_string(bmark_run_mode_t mode) {
if (mode == bmark_run_mode_t::hvx64) {
return "(64 byte mode)";
} else if (mode == bmark_run_mode_t::hvx128) {
return "(128 byte mode)";
} else {
return "(cpu)";
}
}
int main(int argc, char **argv) {
// Set some defaults first.
const int W = 1024;
const int H = 1024;
std::vector<bmark_run_mode_t> modes;
int iterations = 10;
// Process command line args.
for (int i = 1; i < argc; ++i) {
if (argv[i][0] == '-') {
switch (argv[i][1]) {
case 'm':
{
std::string mode_to_run = argv[i+1];
if (mode_to_run == "hvx64") {
modes.push_back(bmark_run_mode_t::hvx64);
} else if (mode_to_run == "hvx128") {
modes.push_back(bmark_run_mode_t::hvx128);
} else if (mode_to_run == "cpu") {
modes.push_back(bmark_run_mode_t::cpu);
} else {
usage(argv[0]);
abort();
}
i++;
}
break;
case 'h':
usage(argv[0]);
return 0;
break;
case 'n':
iterations = atoi(argv[i+1]);
i++;
break;
}
}
}
if (modes.empty()) {
modes.push_back(bmark_run_mode_t::hvx64);
modes.push_back(bmark_run_mode_t::hvx128);
modes.push_back(bmark_run_mode_t::cpu);
}
Conv3x3a16Descriptor conv3x3a16_pipeline(W, H);
Dilate3x3Descriptor dilate3x3_pipeine(W, H);
Median3x3Descriptor median3x3_pipeline(W, H);
Gaussian5x5Descriptor gaussian5x5_pipeline(W, H);
SobelDescriptor sobel_pipeline(W, H);
Conv3x3a32Descriptor conv3x3a32_pipeline(W, H);
std::vector<PipelineDescriptorBase *> pipelines = {&conv3x3a16_pipeline, &dilate3x3_pipeine, &median3x3_pipeline,
&gaussian5x5_pipeline, &sobel_pipeline, &conv3x3a32_pipeline};
for (bmark_run_mode_t m : modes) {
for (PipelineDescriptorBase *p : pipelines) {
if (!p->defined()) {
continue;
}
p->init();
printf ("Running %s...\n", p->name());
// To avoid the cost of powering HVX on in each call of the
// pipeline, power it on once now. Also, set Hexagon performance to turbo.
halide_hexagon_set_performance_mode(NULL, halide_hexagon_power_turbo);
halide_hexagon_power_hvx_on(NULL);
double time = benchmark(iterations, 10, [&]() {
int result = p->run(m);
if (result != 0) {
printf("pipeline failed! %d\n", result);
}
});
printf("Done, time (%s): %g s %s\n", p->name(), time, to_string(m));
// We're done with HVX, power it off, and reset the performance mode
// to default to save power.
halide_hexagon_power_hvx_off(NULL);
halide_hexagon_set_performance_mode(NULL, halide_hexagon_power_default);
if (!p->verify(W, H)) {
abort();
}
p->finalize();
}
}
printf("Success!\n");
return 0;
}
<commit_msg>Fix process.cpp in new hexagon_benchmark<commit_after>#include <stdio.h>
#include <memory.h>
#include <assert.h>
#include <stdlib.h>
#include "halide_benchmark.h"
#include "process.h"
void usage(char *prg_name) {
const char usage_string[] = " Run a bunch of small filters\n\n"
"\t -m -> hvx_mode - options are hvx64, hvx128. Default is to run hvx64, hvx128 and cpu\n"
"\t -n -> number of iterations\n"
"\t -h -> print this help message\n";
printf ("%s - %s", prg_name, usage_string);
}
const char *to_string(bmark_run_mode_t mode) {
if (mode == bmark_run_mode_t::hvx64) {
return "(64 byte mode)";
} else if (mode == bmark_run_mode_t::hvx128) {
return "(128 byte mode)";
} else {
return "(cpu)";
}
}
int main(int argc, char **argv) {
// Set some defaults first.
const int W = 1024;
const int H = 1024;
std::vector<bmark_run_mode_t> modes;
int iterations = 10;
// Process command line args.
for (int i = 1; i < argc; ++i) {
if (argv[i][0] == '-') {
switch (argv[i][1]) {
case 'm':
{
std::string mode_to_run = argv[i+1];
if (mode_to_run == "hvx64") {
modes.push_back(bmark_run_mode_t::hvx64);
} else if (mode_to_run == "hvx128") {
modes.push_back(bmark_run_mode_t::hvx128);
} else if (mode_to_run == "cpu") {
modes.push_back(bmark_run_mode_t::cpu);
} else {
usage(argv[0]);
abort();
}
i++;
}
break;
case 'h':
usage(argv[0]);
return 0;
break;
case 'n':
iterations = atoi(argv[i+1]);
i++;
break;
}
}
}
if (modes.empty()) {
modes.push_back(bmark_run_mode_t::hvx64);
modes.push_back(bmark_run_mode_t::hvx128);
modes.push_back(bmark_run_mode_t::cpu);
}
Conv3x3a16Descriptor conv3x3a16_pipeline(W, H);
Dilate3x3Descriptor dilate3x3_pipeine(W, H);
Median3x3Descriptor median3x3_pipeline(W, H);
Gaussian5x5Descriptor gaussian5x5_pipeline(W, H);
SobelDescriptor sobel_pipeline(W, H);
Conv3x3a32Descriptor conv3x3a32_pipeline(W, H);
std::vector<PipelineDescriptorBase *> pipelines = {&conv3x3a16_pipeline, &dilate3x3_pipeine, &median3x3_pipeline,
&gaussian5x5_pipeline, &sobel_pipeline, &conv3x3a32_pipeline};
for (bmark_run_mode_t m : modes) {
for (PipelineDescriptorBase *p : pipelines) {
if (!p->defined()) {
continue;
}
p->init();
printf ("Running %s...\n", p->name());
// To avoid the cost of powering HVX on in each call of the
// pipeline, power it on once now. Also, set Hexagon performance to turbo.
halide_hexagon_set_performance_mode(NULL, halide_hexagon_power_turbo);
halide_hexagon_power_hvx_on(NULL);
double time = Halide::Tools::benchmark(iterations, 10, [&]() {
int result = p->run(m);
if (result != 0) {
printf("pipeline failed! %d\n", result);
}
});
printf("Done, time (%s): %g s %s\n", p->name(), time, to_string(m));
// We're done with HVX, power it off, and reset the performance mode
// to default to save power.
halide_hexagon_power_hvx_off(NULL);
halide_hexagon_set_performance_mode(NULL, halide_hexagon_power_default);
if (!p->verify(W, H)) {
abort();
}
p->finalize();
}
}
printf("Success!\n");
return 0;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2013-2015 Daniel Nicoletti <dantti12@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.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "dispatcher_p.h"
#include "common.h"
#include "application.h"
#include "engine.h"
#include "context.h"
#include "controller.h"
#include "controller_p.h"
#include "action.h"
#include "request_p.h"
#include "dispatchtypepath.h"
#include "dispatchtypechained.h"
#include "utils.h"
#include <QUrl>
#include <QMetaMethod>
using namespace Cutelyst;
Dispatcher::Dispatcher(QObject *parent) : QObject(parent)
, d_ptr(new DispatcherPrivate(this))
{
new DispatchTypePath(parent);
new DispatchTypeChained(parent);
}
Dispatcher::~Dispatcher()
{
delete d_ptr;
}
void Dispatcher::setupActions(const QVector<Controller*> &controllers, const QVector<Cutelyst::DispatchType *> &dispatchers, bool printActions)
{
Q_D(Dispatcher);
d->dispatchers = dispatchers;
ActionList registeredActions;
for (Controller *controller : controllers) {
bool instanceUsed = false;
const auto actions = controller->actions();
for (Action *action : actions) {
bool registered = false;
if (!d->actions.contains(action->reverse())) {
if (!action->attributes().contains(QLatin1String("Private"))) {
// Register the action with each dispatcher
for (DispatchType *dispatch : dispatchers) {
if (dispatch->registerAction(action)) {
registered = true;
}
}
} else {
// We register private actions
registered = true;
}
}
// The Begin, Auto, End actions are not
// registered by Dispatchers but we need them
// as private actions anyway
if (registered) {
d->actions.insert(action->ns() + QLatin1Char('/') + action->name(), action);
d->actionContainer[action->ns()] << action;
registeredActions.append(action);
instanceUsed = true;
} else {
qCDebug(CUTELYST_DISPATCHER) << "The action" << action->name() << "of"
<< action->controller()->objectName()
<< "controller was not registered in any dispatcher."
" If you still want to access it internally (via actionFor())"
" you may make it's method private.";
}
}
if (instanceUsed) {
d->controllers.insert(controller->objectName(), controller);
}
}
if (printActions) {
d->printActions();
}
// Cache root actions, BEFORE the controllers set them
d->rootActions = d->actionContainer.value(QLatin1String(""));
for (Controller *controller : controllers) {
controller->d_ptr->setupFinished();
}
// Unregister any dispatcher that is not in use
int i = 0;
while (i < d->dispatchers.size()) {
DispatchType *type = d->dispatchers.at(i);
if (!type->inUse()) {
d->dispatchers.removeAt(i);
continue;
}
++i;
}
if (printActions) {
// List all public actions
for (DispatchType *dispatch : dispatchers) {
qCDebug(CUTELYST_DISPATCHER) << dispatch->list().constData();
}
}
}
bool Dispatcher::dispatch(Context *c)
{
Action *action = c->action();
if (action) {
return action->controller()->_DISPATCH(c);
} else {
const QString path = c->req()->path();
if (path.isEmpty()) {
c->error(c->translate("Cutelyst::Dispatcher", "No default action defined"));
} else {
c->error(c->translate("Cutelyst::Dispatcher", "Unknown resource '%1'.").arg(path));
}
}
return false;
}
bool Dispatcher::forward(Context *c, Component *component)
{
Q_ASSERT(component);
// If the component was an Action
// the dispatch() would call c->execute
return c->execute(component);
}
bool Dispatcher::forward(Context *c, const QString &opname)
{
Q_D(const Dispatcher);
Action *action = d->command2Action(c, opname, c->request()->args());
if (action) {
return action->dispatch(c);
}
qCCritical(CUTELYST_DISPATCHER) << "Action not found" << opname << c->request()->args();
return false;
}
void Dispatcher::prepareAction(Context *c)
{
Q_D(Dispatcher);
Request *request = c->request();
d->prepareAction(c, request->path());
static const auto &log = CUTELYST_DISPATCHER();
if (log.isDebugEnabled()) {
if (!request->match().isEmpty()) {
qCDebug(log) << "Path is" << request->match();
}
if (!request->args().isEmpty()) {
qCDebug(log) << "Arguments are" << request->args().join(QLatin1Char('/'));
}
}
}
void DispatcherPrivate::prepareAction(Context *c, const QString &requestPath) const
{
QString path = normalizePath(requestPath);
QStringList args;
// "foo/bar"
// "foo/" skip
// "foo"
// ""
Q_FOREVER {
// Check out the dispatch types to see if any
// will handle the path at this level
for (DispatchType *type : dispatchers) {
if (type->match(c, path, args) == DispatchType::ExactMatch) {
return;
}
}
// leave the loop if we are at the root "/"
if (path.isEmpty()) {
break;
}
int pos = path.lastIndexOf(QLatin1Char('/'));
QString arg = path.mid(pos + 1);
args.prepend(Utils::decodePercentEncoding(&arg));
path.resize(pos);
}
}
Action *Dispatcher::getAction(const QString &name, const QString &nameSpace) const
{
Q_D(const Dispatcher);
if (name.isEmpty()) {
return 0;
}
if (nameSpace.isEmpty()) {
return d->actions.value(QLatin1Char('/') + name);
}
const QString ns = DispatcherPrivate::cleanNamespace(nameSpace);
return d->actions.value(ns + QLatin1Char('/') + name);
}
Action *Dispatcher::getActionByPath(const QString &path) const
{
Q_D(const Dispatcher);
QString _path = path;
if (_path.startsWith(QLatin1Char('/'))) {
_path.remove(0, 1);
}
if (!_path.contains(QLatin1Char('/'))) {
_path.prepend(QLatin1Char('/'));
}
return d->actions.value(_path);
}
ActionList Dispatcher::getActions(const QString &name, const QString &nameSpace) const
{
Q_D(const Dispatcher);
ActionList ret;
if (name.isEmpty()) {
return ret;
}
const QString ns = DispatcherPrivate::cleanNamespace(nameSpace);
const ActionList containers = d->getContainers(ns);
for (Action *action : containers) {
if (action->name() == name) {
ret.prepend(action);
}
}
return ret;
}
QMap<QString, Controller *> Dispatcher::controllers() const
{
Q_D(const Dispatcher);
return d->controllers;
}
QString Dispatcher::uriForAction(Action *action, const QStringList &captures) const
{
Q_D(const Dispatcher);
QString ret;
for (DispatchType *dispatch : d->dispatchers) {
ret = dispatch->uriForAction(action, captures);
if (!ret.isNull()) {
if (ret.isEmpty()) {
ret = QStringLiteral("/");
}
break;
}
}
return ret;
}
Action *Dispatcher::expandAction(Context *c, Action *action) const
{
Q_D(const Dispatcher);
for (DispatchType *dispatch : d->dispatchers) {
Action *expandedAction = dispatch->expandAction(c, action);
if (expandedAction) {
return expandedAction;
}
}
return action;
}
QVector<DispatchType *> Dispatcher::dispatchers() const
{
Q_D(const Dispatcher);
return d->dispatchers;
}
QString DispatcherPrivate::cleanNamespace(const QString &ns)
{
QString ret = ns;
bool lastWasSlash = true; // remove initial slash
int nsSize = ns.size();
for (int i = 0; i < nsSize; ++i) {
// Mark if the last char was a slash
// so that two or more consecutive slashes
// could be converted to just one
// "a///b" -> "a/b"
if (ret.at(i) == QLatin1Char('/')) {
if (lastWasSlash) {
ret.remove(i, 1);
--nsSize;
} else {
lastWasSlash = true;
}
} else {
lastWasSlash = false;
}
}
return ret;
}
QString DispatcherPrivate::normalizePath(const QString &path)
{
QString ret = path;
bool lastSlash = true;
int i = 0;
while (i < ret.size()) {
if (ret.at(i) == QLatin1Char('/')) {
if (lastSlash) {
ret.remove(i, 1);
continue;
}
lastSlash = true;
} else {
lastSlash = false;
}
++i;
}
if (ret.endsWith(QLatin1Char('/'))) {
ret.resize(ret.size() - 1);
}
return ret;
}
void DispatcherPrivate::printActions() const
{
QVector<QStringList> table;
QStringList keys = actions.keys();
keys.sort(Qt::CaseInsensitive);
for (const QString &key : keys) {
Action *action = actions.value(key);
QString path = key;
if (!path.startsWith(QLatin1Char('/'))) {
path.prepend(QLatin1Char('/'));
}
QStringList row;
row.append(path);
row.append(action->className());
row.append(action->name());
table.append(row);
}
qCDebug(CUTELYST_DISPATCHER) << Utils::buildTable(table, {
QLatin1String("Private"),
QLatin1String("Class"),
QLatin1String("Method")
},
QLatin1String("Loaded Private actions:")).constData();
}
ActionList DispatcherPrivate::getContainers(const QString &ns) const
{
ActionList ret;
if (ns != QLatin1String("/")) {
int pos = ns.size();
// qDebug() << pos << ns.mid(0, pos);
while (pos > 0) {
// qDebug() << pos << ns.mid(0, pos);
ret.append(actionContainer.value(ns.mid(0, pos)));
pos = ns.lastIndexOf(QLatin1Char('/'), pos - 1);
}
}
// qDebug() << actionContainer.size() << rootActions;
ret.append(rootActions);
return ret;
}
Action *DispatcherPrivate::command2Action(Context *c, const QString &command, const QStringList &args) const
{
auto it = actions.constFind(command);
if (it != actions.constEnd()) {
return it.value();
}
return invokeAsPath(c, command, args);
}
Action *DispatcherPrivate::invokeAsPath(Context *c, const QString &relativePath, const QStringList &args) const
{
Q_Q(const Dispatcher);
Action *ret;
QString path = DispatcherPrivate::actionRel2Abs(c, relativePath);
int pos = path.lastIndexOf(QLatin1Char('/'));
int lastPos = path.size();
do {
if (pos == -1) {
ret = q->getAction(path, QString());
if (ret) {
return ret;
}
} else {
const QString name = path.mid(pos + 1, lastPos);
path = path.mid(0, pos);
ret = q->getAction(name, path);
if (ret) {
return ret;
}
}
lastPos = pos;
pos = path.indexOf(QLatin1Char('/'), pos - 1);
} while (pos != -1);
return 0;
}
QString DispatcherPrivate::actionRel2Abs(Context *c, const QString &path)
{
QString ret;
if (path.startsWith(QLatin1Char('/'))) {
ret = path.mid(1);
return ret;
}
const QString ns = qobject_cast<Action *>(c->stack().constLast())->ns();
if (ns.isEmpty()) {
ret = path;
} else {
ret = ns + QLatin1Char('/') + path;
}
return ret;
}
#include "moc_dispatcher.cpp"
<commit_msg>Core: Use getActionsByPath in getActions<commit_after>/*
* Copyright (C) 2013-2015 Daniel Nicoletti <dantti12@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.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "dispatcher_p.h"
#include "common.h"
#include "application.h"
#include "engine.h"
#include "context.h"
#include "controller.h"
#include "controller_p.h"
#include "action.h"
#include "request_p.h"
#include "dispatchtypepath.h"
#include "dispatchtypechained.h"
#include "utils.h"
#include <QUrl>
#include <QMetaMethod>
using namespace Cutelyst;
Dispatcher::Dispatcher(QObject *parent) : QObject(parent)
, d_ptr(new DispatcherPrivate(this))
{
new DispatchTypePath(parent);
new DispatchTypeChained(parent);
}
Dispatcher::~Dispatcher()
{
delete d_ptr;
}
void Dispatcher::setupActions(const QVector<Controller*> &controllers, const QVector<Cutelyst::DispatchType *> &dispatchers, bool printActions)
{
Q_D(Dispatcher);
d->dispatchers = dispatchers;
ActionList registeredActions;
for (Controller *controller : controllers) {
bool instanceUsed = false;
const auto actions = controller->actions();
for (Action *action : actions) {
bool registered = false;
if (!d->actions.contains(action->reverse())) {
if (!action->attributes().contains(QLatin1String("Private"))) {
// Register the action with each dispatcher
for (DispatchType *dispatch : dispatchers) {
if (dispatch->registerAction(action)) {
registered = true;
}
}
} else {
// We register private actions
registered = true;
}
}
// The Begin, Auto, End actions are not
// registered by Dispatchers but we need them
// as private actions anyway
if (registered) {
d->actions.insert(action->ns() + QLatin1Char('/') + action->name(), action);
d->actionContainer[action->ns()] << action;
registeredActions.append(action);
instanceUsed = true;
} else {
qCDebug(CUTELYST_DISPATCHER) << "The action" << action->name() << "of"
<< action->controller()->objectName()
<< "controller was not registered in any dispatcher."
" If you still want to access it internally (via actionFor())"
" you may make it's method private.";
}
}
if (instanceUsed) {
d->controllers.insert(controller->objectName(), controller);
}
}
if (printActions) {
d->printActions();
}
// Cache root actions, BEFORE the controllers set them
d->rootActions = d->actionContainer.value(QLatin1String(""));
for (Controller *controller : controllers) {
controller->d_ptr->setupFinished();
}
// Unregister any dispatcher that is not in use
int i = 0;
while (i < d->dispatchers.size()) {
DispatchType *type = d->dispatchers.at(i);
if (!type->inUse()) {
d->dispatchers.removeAt(i);
continue;
}
++i;
}
if (printActions) {
// List all public actions
for (DispatchType *dispatch : dispatchers) {
qCDebug(CUTELYST_DISPATCHER) << dispatch->list().constData();
}
}
}
bool Dispatcher::dispatch(Context *c)
{
Action *action = c->action();
if (action) {
return action->controller()->_DISPATCH(c);
} else {
const QString path = c->req()->path();
if (path.isEmpty()) {
c->error(c->translate("Cutelyst::Dispatcher", "No default action defined"));
} else {
c->error(c->translate("Cutelyst::Dispatcher", "Unknown resource '%1'.").arg(path));
}
}
return false;
}
bool Dispatcher::forward(Context *c, Component *component)
{
Q_ASSERT(component);
// If the component was an Action
// the dispatch() would call c->execute
return c->execute(component);
}
bool Dispatcher::forward(Context *c, const QString &opname)
{
Q_D(const Dispatcher);
Action *action = d->command2Action(c, opname, c->request()->args());
if (action) {
return action->dispatch(c);
}
qCCritical(CUTELYST_DISPATCHER) << "Action not found" << opname << c->request()->args();
return false;
}
void Dispatcher::prepareAction(Context *c)
{
Q_D(Dispatcher);
Request *request = c->request();
d->prepareAction(c, request->path());
static const auto &log = CUTELYST_DISPATCHER();
if (log.isDebugEnabled()) {
if (!request->match().isEmpty()) {
qCDebug(log) << "Path is" << request->match();
}
if (!request->args().isEmpty()) {
qCDebug(log) << "Arguments are" << request->args().join(QLatin1Char('/'));
}
}
}
void DispatcherPrivate::prepareAction(Context *c, const QString &requestPath) const
{
QString path = normalizePath(requestPath);
QStringList args;
// "foo/bar"
// "foo/" skip
// "foo"
// ""
Q_FOREVER {
// Check out the dispatch types to see if any
// will handle the path at this level
for (DispatchType *type : dispatchers) {
if (type->match(c, path, args) == DispatchType::ExactMatch) {
return;
}
}
// leave the loop if we are at the root "/"
if (path.isEmpty()) {
break;
}
int pos = path.lastIndexOf(QLatin1Char('/'));
QString arg = path.mid(pos + 1);
args.prepend(Utils::decodePercentEncoding(&arg));
path.resize(pos);
}
}
Action *Dispatcher::getAction(const QString &name, const QString &nameSpace) const
{
Q_D(const Dispatcher);
if (name.isEmpty()) {
return nullptr;
}
if (nameSpace.isEmpty()) {
return d->actions.value(QLatin1Char('/') + name);
}
const QString ns = DispatcherPrivate::cleanNamespace(nameSpace);
return getActionByPath(ns + QLatin1Char('/') + name);
}
Action *Dispatcher::getActionByPath(const QString &path) const
{
Q_D(const Dispatcher);
QString _path = path;
if (_path.startsWith(QLatin1Char('/'))) {
_path.remove(0, 1);
}
if (!_path.contains(QLatin1Char('/'))) {
_path.prepend(QLatin1Char('/'));
}
return d->actions.value(_path);
}
ActionList Dispatcher::getActions(const QString &name, const QString &nameSpace) const
{
Q_D(const Dispatcher);
ActionList ret;
if (name.isEmpty()) {
return ret;
}
const QString ns = DispatcherPrivate::cleanNamespace(nameSpace);
const ActionList containers = d->getContainers(ns);
for (Action *action : containers) {
if (action->name() == name) {
ret.prepend(action);
}
}
return ret;
}
QMap<QString, Controller *> Dispatcher::controllers() const
{
Q_D(const Dispatcher);
return d->controllers;
}
QString Dispatcher::uriForAction(Action *action, const QStringList &captures) const
{
Q_D(const Dispatcher);
QString ret;
for (DispatchType *dispatch : d->dispatchers) {
ret = dispatch->uriForAction(action, captures);
if (!ret.isNull()) {
if (ret.isEmpty()) {
ret = QStringLiteral("/");
}
break;
}
}
return ret;
}
Action *Dispatcher::expandAction(Context *c, Action *action) const
{
Q_D(const Dispatcher);
for (DispatchType *dispatch : d->dispatchers) {
Action *expandedAction = dispatch->expandAction(c, action);
if (expandedAction) {
return expandedAction;
}
}
return action;
}
QVector<DispatchType *> Dispatcher::dispatchers() const
{
Q_D(const Dispatcher);
return d->dispatchers;
}
QString DispatcherPrivate::cleanNamespace(const QString &ns)
{
QString ret = ns;
bool lastWasSlash = true; // remove initial slash
int nsSize = ns.size();
for (int i = 0; i < nsSize; ++i) {
// Mark if the last char was a slash
// so that two or more consecutive slashes
// could be converted to just one
// "a///b" -> "a/b"
if (ret.at(i) == QLatin1Char('/')) {
if (lastWasSlash) {
ret.remove(i, 1);
--nsSize;
} else {
lastWasSlash = true;
}
} else {
lastWasSlash = false;
}
}
return ret;
}
QString DispatcherPrivate::normalizePath(const QString &path)
{
QString ret = path;
bool lastSlash = true;
int i = 0;
while (i < ret.size()) {
if (ret.at(i) == QLatin1Char('/')) {
if (lastSlash) {
ret.remove(i, 1);
continue;
}
lastSlash = true;
} else {
lastSlash = false;
}
++i;
}
if (ret.endsWith(QLatin1Char('/'))) {
ret.resize(ret.size() - 1);
}
return ret;
}
void DispatcherPrivate::printActions() const
{
QVector<QStringList> table;
QStringList keys = actions.keys();
keys.sort(Qt::CaseInsensitive);
for (const QString &key : keys) {
Action *action = actions.value(key);
QString path = key;
if (!path.startsWith(QLatin1Char('/'))) {
path.prepend(QLatin1Char('/'));
}
QStringList row;
row.append(path);
row.append(action->className());
row.append(action->name());
table.append(row);
}
qCDebug(CUTELYST_DISPATCHER) << Utils::buildTable(table, {
QLatin1String("Private"),
QLatin1String("Class"),
QLatin1String("Method")
},
QLatin1String("Loaded Private actions:")).constData();
}
ActionList DispatcherPrivate::getContainers(const QString &ns) const
{
ActionList ret;
if (ns != QLatin1String("/")) {
int pos = ns.size();
// qDebug() << pos << ns.mid(0, pos);
while (pos > 0) {
// qDebug() << pos << ns.mid(0, pos);
ret.append(actionContainer.value(ns.mid(0, pos)));
pos = ns.lastIndexOf(QLatin1Char('/'), pos - 1);
}
}
// qDebug() << actionContainer.size() << rootActions;
ret.append(rootActions);
return ret;
}
Action *DispatcherPrivate::command2Action(Context *c, const QString &command, const QStringList &args) const
{
auto it = actions.constFind(command);
if (it != actions.constEnd()) {
return it.value();
}
return invokeAsPath(c, command, args);
}
Action *DispatcherPrivate::invokeAsPath(Context *c, const QString &relativePath, const QStringList &args) const
{
Q_Q(const Dispatcher);
Action *ret;
QString path = DispatcherPrivate::actionRel2Abs(c, relativePath);
int pos = path.lastIndexOf(QLatin1Char('/'));
int lastPos = path.size();
do {
if (pos == -1) {
ret = q->getAction(path, QString());
if (ret) {
return ret;
}
} else {
const QString name = path.mid(pos + 1, lastPos);
path = path.mid(0, pos);
ret = q->getAction(name, path);
if (ret) {
return ret;
}
}
lastPos = pos;
pos = path.indexOf(QLatin1Char('/'), pos - 1);
} while (pos != -1);
return 0;
}
QString DispatcherPrivate::actionRel2Abs(Context *c, const QString &path)
{
QString ret;
if (path.startsWith(QLatin1Char('/'))) {
ret = path.mid(1);
return ret;
}
const QString ns = qobject_cast<Action *>(c->stack().constLast())->ns();
if (ns.isEmpty()) {
ret = path;
} else {
ret = ns + QLatin1Char('/') + path;
}
return ret;
}
#include "moc_dispatcher.cpp"
<|endoftext|>
|
<commit_before>#include "catch.hpp"
#include <shadow.hpp>
#include <vector>
#include <iostream>
struct tca1
{
int i;
char c;
};
class tca2
{
public:
tca2() : c_('a')
{
}
tca2(char c) : c_(std::move(c))
{
}
char
get_c() const
{
return c_;
}
private:
char c_;
};
class tca3
{
public:
tca3(const int& i) : i_(i)
{
}
int
get_i() const
{
return i_;
}
private:
int i_;
};
namespace tca_space
{
REGISTER_TYPE_BEGIN()
REGISTER_TYPE(tca1)
REGISTER_TYPE(tca2)
REGISTER_TYPE(tca3)
REGISTER_TYPE_END()
REGISTER_CONSTRUCTOR(tca1, int, char)
REGISTER_CONSTRUCTOR(tca2)
REGISTER_CONSTRUCTOR(tca2, char)
REGISTER_CONSTRUCTOR(tca3, const int&)
SHADOW_INIT()
}
TEST_CASE("get all types", "[reflection_manager]")
{
auto types_pair = tca_space::manager.types();
SECTION("find double type")
{
auto found = std::find_if(
types_pair.first, types_pair.second, [](const auto& tp) {
return tp.name() == std::string("double");
});
REQUIRE(found != types_pair.second);
SECTION("get all constructors for double")
{
auto constr_pair = tca_space::manager.constructors_by_type(*found);
REQUIRE(std::distance(constr_pair.first, constr_pair.second) == 2);
SECTION("find constructor taking 0 arguments")
{
auto found_constr = std::find_if(
constr_pair.first, constr_pair.second, [](const auto& ctr) {
return ctr.num_parameters() == 0;
});
REQUIRE(found_constr != constr_pair.second);
SECTION("constructor double with 0 args")
{
// construct with no arg overload
auto obj = tca_space::manager.construct(*found_constr);
// construct with overload taking iterators to args
std::vector<shadow::variable> args;
auto obj2 = tca_space::manager.construct(
*found_constr, args.begin(), args.end());
REQUIRE(obj.type().name() == std::string("double"));
REQUIRE(obj2.type().name() == std::string("double"));
REQUIRE(tca_space::static_value_cast<double>(obj) ==
Approx(0.0));
REQUIRE(tca_space::static_value_cast<double>(obj2) ==
Approx(0.0));
}
}
SECTION("find constructor taking 1 argument")
{
auto found_constr = std::find_if(
constr_pair.first, constr_pair.second, [](const auto& ctr) {
return ctr.num_parameters() == 1;
});
REQUIRE(found_constr != constr_pair.second);
SECTION("constructor double with 1 arg")
{
// construct with overload taking iterators to args
std::vector<shadow::variable> args{
tca_space::static_create<double>(20.0)};
auto obj = tca_space::manager.construct(
*found_constr, args.begin(), args.end());
REQUIRE(obj.type().name() == std::string("double"));
REQUIRE(tca_space::static_value_cast<double>(obj) ==
Approx(20.0));
}
}
}
}
SECTION("find tca1 type")
{
auto found = std::find_if(
types_pair.first, types_pair.second, [](const auto& tp) {
return tp.name() == std::string("tca1");
});
REQUIRE(found != types_pair.second);
SECTION("get all constructors for tca1")
{
auto constr_pair = tca_space::manager.constructors_by_type(*found);
REQUIRE(std::distance(constr_pair.first, constr_pair.second) == 1);
SECTION("find constructor taking two args")
{
auto found_constr = std::find_if(
constr_pair.first, constr_pair.second, [](const auto& ctr) {
return ctr.num_parameters() == 2;
});
REQUIRE(found_constr != constr_pair.second);
SECTION("construct a tca1 with two arguments")
{
std::vector<shadow::variable> args{
tca_space::static_create<int>(10),
tca_space::static_create<char>('c')};
auto obj = tca_space::manager.construct(
*found_constr, args.begin(), args.end());
REQUIRE(obj.type().name() == std::string("tca1"));
REQUIRE(tca_space::static_value_cast<tca1>(obj).i == 10);
REQUIRE(tca_space::static_value_cast<tca1>(obj).c == 'c');
}
}
}
}
SECTION("find tca2 type")
{
auto found = std::find_if(
types_pair.first, types_pair.second, [](const auto& tp) {
return tp.name() == std::string("tca2");
});
REQUIRE(found != types_pair.second);
SECTION("get all constructors for tca2")
{
auto constr_pair = tca_space::manager.constructors_by_type(*found);
REQUIRE(std::distance(constr_pair.first, constr_pair.second) == 2);
SECTION("find default constructor for tca2")
{
auto found_constr = std::find_if(
constr_pair.first, constr_pair.second, [](const auto& ctr) {
return ctr.num_parameters() == 0;
});
REQUIRE(found_constr != constr_pair.second);
SECTION("construct tca2 with default constructor")
{
auto obj = tca_space::manager.construct(*found_constr);
REQUIRE(obj.type().name() == std::string("tca2"));
REQUIRE(tca_space::static_value_cast<tca2>(obj).get_c() ==
'a');
}
}
SECTION("find constructor for tca2 taking one argument")
{
auto found_constr = std::find_if(
constr_pair.first, constr_pair.second, [](const auto& ctr) {
return ctr.num_parameters() == 1;
});
REQUIRE(found_constr != constr_pair.second);
SECTION("construct tca2 with one arg constructor")
{
std::vector<shadow::variable> args{
tca_space::static_create<char>('w')};
auto obj = tca_space::manager.construct(
*found_constr, args.begin(), args.end());
REQUIRE(obj.type().name() == std::string("tca2"));
REQUIRE(tca_space::static_value_cast<tca2>(obj).get_c() ==
'w');
}
}
}
}
SECTION("find tca3 type")
{
auto found = std::find_if(
types_pair.first, types_pair.second, [](const auto& tp) {
return tp.name() == std::string("tca3");
});
REQUIRE(found != types_pair.second);
SECTION("get all constructors for tca3")
{
auto constr_pair = tca_space::manager.constructors_by_type(*found);
REQUIRE(std::distance(constr_pair.first, constr_pair.second) == 1);
}
}
}
<commit_msg>Add unit test causing segfault. modified: tests/test_constructor_api.cpp<commit_after>#include "catch.hpp"
#include <shadow.hpp>
#include <vector>
#include <iostream>
struct tca1
{
int i;
char c;
};
class tca2
{
public:
tca2() : c_('a')
{
}
tca2(char c) : c_(std::move(c))
{
}
char
get_c() const
{
return c_;
}
private:
char c_;
};
class tca3
{
public:
tca3(const int& i) : i_(i)
{
}
int
get_i() const
{
return i_;
}
private:
int i_;
};
namespace tca_space
{
REGISTER_TYPE_BEGIN()
REGISTER_TYPE(tca1)
REGISTER_TYPE(tca2)
REGISTER_TYPE(tca3)
REGISTER_TYPE_END()
REGISTER_CONSTRUCTOR(tca1, int, char)
REGISTER_CONSTRUCTOR(tca2)
REGISTER_CONSTRUCTOR(tca2, char)
REGISTER_CONSTRUCTOR(tca3, const int&)
SHADOW_INIT()
}
TEST_CASE("get all types", "[reflection_manager]")
{
auto types_pair = tca_space::manager.types();
SECTION("find double type")
{
auto found = std::find_if(
types_pair.first, types_pair.second, [](const auto& tp) {
return tp.name() == std::string("double");
});
REQUIRE(found != types_pair.second);
SECTION("get all constructors for double")
{
auto constr_pair = tca_space::manager.constructors_by_type(*found);
REQUIRE(std::distance(constr_pair.first, constr_pair.second) == 2);
SECTION("find constructor taking 0 arguments")
{
auto found_constr = std::find_if(
constr_pair.first, constr_pair.second, [](const auto& ctr) {
return ctr.num_parameters() == 0;
});
REQUIRE(found_constr != constr_pair.second);
SECTION("constructor double with 0 args")
{
// construct with no arg overload
auto obj = tca_space::manager.construct(*found_constr);
// construct with overload taking iterators to args
std::vector<shadow::variable> args;
auto obj2 = tca_space::manager.construct(
*found_constr, args.begin(), args.end());
REQUIRE(obj.type().name() == std::string("double"));
REQUIRE(obj2.type().name() == std::string("double"));
REQUIRE(tca_space::static_value_cast<double>(obj) ==
Approx(0.0));
REQUIRE(tca_space::static_value_cast<double>(obj2) ==
Approx(0.0));
}
}
SECTION("find constructor taking 1 argument")
{
auto found_constr = std::find_if(
constr_pair.first, constr_pair.second, [](const auto& ctr) {
return ctr.num_parameters() == 1;
});
REQUIRE(found_constr != constr_pair.second);
SECTION("constructor double with 1 arg")
{
// construct with overload taking iterators to args
std::vector<shadow::variable> args{
tca_space::static_create<double>(20.0)};
auto obj = tca_space::manager.construct(
*found_constr, args.begin(), args.end());
REQUIRE(obj.type().name() == std::string("double"));
REQUIRE(tca_space::static_value_cast<double>(obj) ==
Approx(20.0));
}
}
}
}
SECTION("find tca1 type")
{
auto found = std::find_if(
types_pair.first, types_pair.second, [](const auto& tp) {
return tp.name() == std::string("tca1");
});
REQUIRE(found != types_pair.second);
SECTION("get all constructors for tca1")
{
auto constr_pair = tca_space::manager.constructors_by_type(*found);
REQUIRE(std::distance(constr_pair.first, constr_pair.second) == 1);
SECTION("find constructor taking two args")
{
auto found_constr = std::find_if(
constr_pair.first, constr_pair.second, [](const auto& ctr) {
return ctr.num_parameters() == 2;
});
REQUIRE(found_constr != constr_pair.second);
SECTION("construct a tca1 with two arguments")
{
std::vector<shadow::variable> args{
tca_space::static_create<int>(10),
tca_space::static_create<char>('c')};
auto obj = tca_space::manager.construct(
*found_constr, args.begin(), args.end());
REQUIRE(obj.type().name() == std::string("tca1"));
REQUIRE(tca_space::static_value_cast<tca1>(obj).i == 10);
REQUIRE(tca_space::static_value_cast<tca1>(obj).c == 'c');
}
}
}
}
SECTION("find tca2 type")
{
auto found = std::find_if(
types_pair.first, types_pair.second, [](const auto& tp) {
return tp.name() == std::string("tca2");
});
REQUIRE(found != types_pair.second);
SECTION("get all constructors for tca2")
{
auto constr_pair = tca_space::manager.constructors_by_type(*found);
REQUIRE(std::distance(constr_pair.first, constr_pair.second) == 2);
SECTION("find default constructor for tca2")
{
auto found_constr = std::find_if(
constr_pair.first, constr_pair.second, [](const auto& ctr) {
return ctr.num_parameters() == 0;
});
REQUIRE(found_constr != constr_pair.second);
SECTION("construct tca2 with default constructor")
{
auto obj = tca_space::manager.construct(*found_constr);
REQUIRE(obj.type().name() == std::string("tca2"));
REQUIRE(tca_space::static_value_cast<tca2>(obj).get_c() ==
'a');
}
}
SECTION("find constructor for tca2 taking one argument")
{
auto found_constr = std::find_if(
constr_pair.first, constr_pair.second, [](const auto& ctr) {
return ctr.num_parameters() == 1;
});
REQUIRE(found_constr != constr_pair.second);
SECTION("construct tca2 with one arg constructor")
{
std::vector<shadow::variable> args{
tca_space::static_create<char>('w')};
auto obj = tca_space::manager.construct(
*found_constr, args.begin(), args.end());
REQUIRE(obj.type().name() == std::string("tca2"));
REQUIRE(tca_space::static_value_cast<tca2>(obj).get_c() ==
'w');
}
}
}
}
SECTION("find tca3 type")
{
auto found = std::find_if(
types_pair.first, types_pair.second, [](const auto& tp) {
return tp.name() == std::string("tca3");
});
REQUIRE(found != types_pair.second);
SECTION("get all constructors for tca3")
{
auto constr_pair = tca_space::manager.constructors_by_type(*found);
REQUIRE(std::distance(constr_pair.first, constr_pair.second) == 1);
SECTION("find constructor taking one arg")
{
auto found_constr = std::find_if(
constr_pair.first, constr_pair.second, [](const auto& ctr) {
return ctr.num_parameters() == 1;
});
REQUIRE(found_constr != constr_pair.second);
SECTION("construct tca3 with one argument")
{
std::vector<shadow::variable> args{
tca_space::static_create<int>(100)};
auto obj = tca_space::manager.construct(
*found_constr, args.begin(), args.end());
REQUIRE(obj.type().name() == std::string("tca3"));
}
}
}
}
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: aquavclevents.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: kz $ $Date: 2007-10-09 15:07:55 $
*
* 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 INCLUDED_AQUAVCLEVENTS_HXX
#define INCLUDED_AQUAVCLEVENTS_HXX
#include <premac.h>
#include <Carbon/Carbon.h>
#include <postmac.h>
/* Definition of custom OpenOffice.org events.
Avoid conflict with Apple defined event class and type
definitions by using uppercase letters. Lowercase
letter definitions are reserved for Apple!
*/
enum {
cOOoSalUserEventClass = 'OOUE'
};
enum {
cOOoSalEventUser = 'UEVT',
cOOoSalEventTimer = 'EVTT',
cOOoSalEventData = 'EVTD',
cOOoSalEventParamTypePtr = 'EPPT'
};
/* Definition of all necessary EventTypeSpec's */
const EventTypeSpec cWindowBoundsChangedEvent = { kEventClassWindow, kEventWindowBoundsChanged };
const EventTypeSpec cWindowCloseEvent = { kEventClassWindow, kEventWindowClose };
const EventTypeSpec cOOoSalUserEvent = { cOOoSalUserEventClass, cOOoSalEventUser };
const EventTypeSpec cOOoSalTimerEvent = { cOOoSalUserEventClass, cOOoSalEventTimer };
const EventTypeSpec cWindowActivatedEvent[] = { { kEventClassWindow, kEventWindowActivated },
{ kEventClassWindow, kEventWindowDeactivated } };
const EventTypeSpec cWindowPaintEvent = { kEventClassWindow, kEventWindowPaint };
const EventTypeSpec cWindowDrawContentEvent = { kEventClassWindow, kEventWindowDrawContent };
const EventTypeSpec cWindowFocusEvent[] = { { kEventClassWindow, kEventWindowFocusAcquired },
{ kEventClassWindow, kEventWindowFocusRelinquish } };
const EventTypeSpec cMouseEnterExitEvent[] = { { kEventClassControl, kEventControlTrackingAreaEntered },
{ kEventClassControl, kEventControlTrackingAreaExited } };
const EventTypeSpec cMouseEvent[] = { { kEventClassMouse, kEventMouseDown },
{ kEventClassMouse, kEventMouseUp },
{ kEventClassMouse, kEventMouseMoved },
{ kEventClassMouse, kEventMouseDragged } };
const EventTypeSpec cMouseWheelMovedEvent = { kEventClassMouse, kEventMouseWheelMoved };
const EventTypeSpec cWindowResizeStarted = { kEventClassWindow, kEventWindowResizeStarted };
const EventTypeSpec cWindowResizeCompleted = { kEventClassWindow, kEventWindowResizeCompleted };
/* Events for native menus */
const EventTypeSpec cCommandProcessEvent = { kEventClassCommand, kEventCommandProcess };
const EventTypeSpec cMenuPopulateEvent = { kEventClassMenu, kEventMenuPopulate };
const EventTypeSpec cMenuClosedEvent = { kEventClassMenu, kEventMenuClosed };
const EventTypeSpec cMenuTargetItemEvent = { kEventClassMenu, kEventMenuTargetItem };
/* Events for keyboard */
const EventTypeSpec cKeyboardRawKeyEvents[] = { { kEventClassKeyboard, kEventRawKeyDown},
{ kEventClassKeyboard, kEventRawKeyUp},
{ kEventClassKeyboard, kEventRawKeyRepeat},
{ kEventClassKeyboard, kEventRawKeyModifiersChanged} };
const EventTypeSpec cTextInputEvents[] = { { kEventClassTextInput, kEventTextInputUpdateActiveInputArea},
{ kEventClassTextInput, kEventTextInputUnicodeForKeyEvent},
{ kEventClassTextInput, kEventTextInputOffsetToPos} };
/* Events for scrollbar */
const EventTypeSpec cAppearanceScrollbarVariantChangedEvent = { kEventClassAppearance, kEventAppearanceScrollBarVariantChanged };
#endif // INCLUDED_AQUAVCLEVENTS_HXX
<commit_msg>INTEGRATION: CWS changefileheader (1.4.168); FILE MERGED 2008/03/28 15:44:01 rt 1.4.168.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: aquavclevents.hxx,v $
* $Revision: 1.5 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef INCLUDED_AQUAVCLEVENTS_HXX
#define INCLUDED_AQUAVCLEVENTS_HXX
#include <premac.h>
#include <Carbon/Carbon.h>
#include <postmac.h>
/* Definition of custom OpenOffice.org events.
Avoid conflict with Apple defined event class and type
definitions by using uppercase letters. Lowercase
letter definitions are reserved for Apple!
*/
enum {
cOOoSalUserEventClass = 'OOUE'
};
enum {
cOOoSalEventUser = 'UEVT',
cOOoSalEventTimer = 'EVTT',
cOOoSalEventData = 'EVTD',
cOOoSalEventParamTypePtr = 'EPPT'
};
/* Definition of all necessary EventTypeSpec's */
const EventTypeSpec cWindowBoundsChangedEvent = { kEventClassWindow, kEventWindowBoundsChanged };
const EventTypeSpec cWindowCloseEvent = { kEventClassWindow, kEventWindowClose };
const EventTypeSpec cOOoSalUserEvent = { cOOoSalUserEventClass, cOOoSalEventUser };
const EventTypeSpec cOOoSalTimerEvent = { cOOoSalUserEventClass, cOOoSalEventTimer };
const EventTypeSpec cWindowActivatedEvent[] = { { kEventClassWindow, kEventWindowActivated },
{ kEventClassWindow, kEventWindowDeactivated } };
const EventTypeSpec cWindowPaintEvent = { kEventClassWindow, kEventWindowPaint };
const EventTypeSpec cWindowDrawContentEvent = { kEventClassWindow, kEventWindowDrawContent };
const EventTypeSpec cWindowFocusEvent[] = { { kEventClassWindow, kEventWindowFocusAcquired },
{ kEventClassWindow, kEventWindowFocusRelinquish } };
const EventTypeSpec cMouseEnterExitEvent[] = { { kEventClassControl, kEventControlTrackingAreaEntered },
{ kEventClassControl, kEventControlTrackingAreaExited } };
const EventTypeSpec cMouseEvent[] = { { kEventClassMouse, kEventMouseDown },
{ kEventClassMouse, kEventMouseUp },
{ kEventClassMouse, kEventMouseMoved },
{ kEventClassMouse, kEventMouseDragged } };
const EventTypeSpec cMouseWheelMovedEvent = { kEventClassMouse, kEventMouseWheelMoved };
const EventTypeSpec cWindowResizeStarted = { kEventClassWindow, kEventWindowResizeStarted };
const EventTypeSpec cWindowResizeCompleted = { kEventClassWindow, kEventWindowResizeCompleted };
/* Events for native menus */
const EventTypeSpec cCommandProcessEvent = { kEventClassCommand, kEventCommandProcess };
const EventTypeSpec cMenuPopulateEvent = { kEventClassMenu, kEventMenuPopulate };
const EventTypeSpec cMenuClosedEvent = { kEventClassMenu, kEventMenuClosed };
const EventTypeSpec cMenuTargetItemEvent = { kEventClassMenu, kEventMenuTargetItem };
/* Events for keyboard */
const EventTypeSpec cKeyboardRawKeyEvents[] = { { kEventClassKeyboard, kEventRawKeyDown},
{ kEventClassKeyboard, kEventRawKeyUp},
{ kEventClassKeyboard, kEventRawKeyRepeat},
{ kEventClassKeyboard, kEventRawKeyModifiersChanged} };
const EventTypeSpec cTextInputEvents[] = { { kEventClassTextInput, kEventTextInputUpdateActiveInputArea},
{ kEventClassTextInput, kEventTextInputUnicodeForKeyEvent},
{ kEventClassTextInput, kEventTextInputOffsetToPos} };
/* Events for scrollbar */
const EventTypeSpec cAppearanceScrollbarVariantChangedEvent = { kEventClassAppearance, kEventAppearanceScrollBarVariantChanged };
#endif // INCLUDED_AQUAVCLEVENTS_HXX
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: salcolorutils.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: pluby $ $Date: 2001-03-13 09:44:40 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _SV_SALCOLORUTILS_HXX
#define _SV_SALCOLORUTILS_HXX
#ifndef _LIMITS_H
#include <limits.h>
#endif
#include <premac.h>
#include <ApplicationServices/ApplicationServices.h>
#include <postmac.h>
#ifndef _SV_SALBTYPE_HXX
#include <salbtype.hxx>
#endif
#ifndef _SV_SALGTYPE_HXX
#include <salgtype.hxx>
#endif
#ifndef _SV_SALCONST_H
#include <salconst.h>
#endif
#ifndef _SV_SALMATHUTILS_HXX
#include <salmathutils.hxx>
#endif
// ------------------------------------------------------------------
SalColor RGBColor2SALColor ( const RGBColor *pRGBColor );
SalColor RGB8BitColor2SALColor ( const RGBColor *pRGBColor );
SalColor RGB16BitColor2SALColor ( const RGBColor *pRGBColor );
SalColor RGB32BitColor2SALColor ( const RGBColor *pRGBColor );
// ------------------------------------------------------------------
RGBColor SALColor2RGBColor ( const SalColor nSalColor );
RGBColor SALColor2RGB32bitColor ( const SalColor nSalColor );
RGBColor SALColor2RGB18bitColor ( const SalColor nSalColor );
RGBColor SALColor2RGB8bitColor ( const SalColor nSalColor );
// ------------------------------------------------------------------
SalColor GetROPSalColor ( SalROPColor nROPColor );
// ------------------------------------------------------------------
RGBColor BitmapColor2RGBColor ( const BitmapColor &rBitmapColor );
void RGBColor2BitmapColor ( const RGBColor *rRGBColor,
BitmapColor &rBitmapColor
);
// ------------------------------------------------------------------
short GetMinColorCount ( const short nPixMapColorDepth,
const BitmapPalette &rBitmapPalette
);
// ------------------------------------------------------------------
void SetBlackForeColor ( );
void SetWhiteBackColor ( );
RGBColor GetBlackColor ( );
RGBColor GetWhiteColor ( );
// ------------------------------------------------------------------
CTabHandle CopyGDeviceCTab ( );
CTabHandle GetCTabFromStdCLUT ( const short nBitDepth );
CTabHandle CopyCTabIndexed ( CTabHandle hCTab );
CTabHandle CopyCTabRGBDirect ( CTabHandle hCTab );
// ------------------------------------------------------------------
CTabHandle CopyPixMapCTab ( PixMapHandle hPixMap );
// ------------------------------------------------------------------
void SetBitmapBufferColorFormat ( const PixMapHandle mhPixMap,
BitmapBuffer *rBuffer
);
// ------------------------------------------------------------------
#endif // _SV_SALCOLORUTILS_HXX
<commit_msg>INTEGRATION: CWS ooo19126 (1.4.984); FILE MERGED 2005/09/05 14:43:33 rt 1.4.984.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: salcolorutils.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2005-09-09 10:32:59 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _SV_SALCOLORUTILS_HXX
#define _SV_SALCOLORUTILS_HXX
#ifndef _LIMITS_H
#include <limits.h>
#endif
#include <premac.h>
#include <ApplicationServices/ApplicationServices.h>
#include <postmac.h>
#ifndef _SV_SALBTYPE_HXX
#include <salbtype.hxx>
#endif
#ifndef _SV_SALGTYPE_HXX
#include <salgtype.hxx>
#endif
#ifndef _SV_SALCONST_H
#include <salconst.h>
#endif
#ifndef _SV_SALMATHUTILS_HXX
#include <salmathutils.hxx>
#endif
// ------------------------------------------------------------------
SalColor RGBColor2SALColor ( const RGBColor *pRGBColor );
SalColor RGB8BitColor2SALColor ( const RGBColor *pRGBColor );
SalColor RGB16BitColor2SALColor ( const RGBColor *pRGBColor );
SalColor RGB32BitColor2SALColor ( const RGBColor *pRGBColor );
// ------------------------------------------------------------------
RGBColor SALColor2RGBColor ( const SalColor nSalColor );
RGBColor SALColor2RGB32bitColor ( const SalColor nSalColor );
RGBColor SALColor2RGB18bitColor ( const SalColor nSalColor );
RGBColor SALColor2RGB8bitColor ( const SalColor nSalColor );
// ------------------------------------------------------------------
SalColor GetROPSalColor ( SalROPColor nROPColor );
// ------------------------------------------------------------------
RGBColor BitmapColor2RGBColor ( const BitmapColor &rBitmapColor );
void RGBColor2BitmapColor ( const RGBColor *rRGBColor,
BitmapColor &rBitmapColor
);
// ------------------------------------------------------------------
short GetMinColorCount ( const short nPixMapColorDepth,
const BitmapPalette &rBitmapPalette
);
// ------------------------------------------------------------------
void SetBlackForeColor ( );
void SetWhiteBackColor ( );
RGBColor GetBlackColor ( );
RGBColor GetWhiteColor ( );
// ------------------------------------------------------------------
CTabHandle CopyGDeviceCTab ( );
CTabHandle GetCTabFromStdCLUT ( const short nBitDepth );
CTabHandle CopyCTabIndexed ( CTabHandle hCTab );
CTabHandle CopyCTabRGBDirect ( CTabHandle hCTab );
// ------------------------------------------------------------------
CTabHandle CopyPixMapCTab ( PixMapHandle hPixMap );
// ------------------------------------------------------------------
void SetBitmapBufferColorFormat ( const PixMapHandle mhPixMap,
BitmapBuffer *rBuffer
);
// ------------------------------------------------------------------
#endif // _SV_SALCOLORUTILS_HXX
<|endoftext|>
|
<commit_before><commit_msg>Remove unused #define<commit_after><|endoftext|>
|
<commit_before>#include "Halide.h"
namespace {
// Compile a simple pipeline to an object and to C code.
HalideExtern_2(int, an_extern_func, int, int);
class Pipeline : public Halide::Generator<Pipeline> {
public:
ImageParam input{UInt(16), 2, "input"};
Func build() {
Var x, y;
Func f, g, h;
f(x, y) = (input(clamp(x+2, 0, input.width()-1), clamp(y-2, 0, input.height()-1)) * 17)/13;
h.define_extern("an_extern_stage", {f}, Int(16), 0);
g(x, y) = f(y, x) + f(x, y) + cast<uint16_t>(an_extern_func(x, y)) + h();
f.compute_root();
h.compute_root();
return g;
}
};
Halide::RegisterGenerator<Pipeline> register_me{"pipeline"};
} // namespace
<commit_msg>Type fix.<commit_after>#include "Halide.h"
namespace {
// Compile a simple pipeline to an object and to C code.
HalideExtern_2(int, an_extern_func, int, int);
class Pipeline : public Halide::Generator<Pipeline> {
public:
ImageParam input{UInt(16), 2, "input"};
Func build() {
Var x, y;
Func f, g, h;
f(x, y) = (input(clamp(x+2, 0, input.width()-1), clamp(y-2, 0, input.height()-1)) * 17)/13;
h.define_extern("an_extern_stage", {f}, Int(16), 0);
g(x, y) = cast<uint16_t>(f(y, x) + f(x, y) + an_extern_func(x, y) + h());
f.compute_root();
h.compute_root();
return g;
}
};
Halide::RegisterGenerator<Pipeline> register_me{"pipeline"};
} // namespace
<|endoftext|>
|
<commit_before>#include "LargeRAWFile.h"
using namespace std;
#define BLOCK_COPY_SIZE (UINT64(128*1024*1024))
LargeRAWFile::LargeRAWFile(const std::string& strFilename, UINT64 iHeaderSize) :
m_strFilename(strFilename),
m_bIsOpen(false),
m_bWritable(false),
m_iHeaderSize(iHeaderSize)
{
}
LargeRAWFile::LargeRAWFile(const std::wstring& wstrFilename, UINT64 iHeaderSize) :
m_bIsOpen(false),
m_bWritable(false),
m_iHeaderSize(iHeaderSize)
{
string strFilename(wstrFilename.begin(), wstrFilename.end());
m_strFilename = strFilename;
}
LargeRAWFile::LargeRAWFile(LargeRAWFile &other) :
m_strFilename(other.m_strFilename+"~"),
m_bIsOpen(other.m_bIsOpen),
m_iHeaderSize(other.m_iHeaderSize),
m_bWritable(other.m_bWritable)
{
if (m_bIsOpen) {
UINT64 iDataSize = other.GetCurrentSize();
Create(iDataSize);
other.SeekStart();
unsigned char* pData = new unsigned char[size_t(min(iDataSize, BLOCK_COPY_SIZE))];
for (UINT64 i = 0;i<iDataSize;i+=BLOCK_COPY_SIZE) {
UINT64 iCopySize = min(BLOCK_COPY_SIZE, iDataSize-i);
other.ReadRAW(pData, iCopySize);
WriteRAW(pData, iCopySize);
}
delete [] pData;
}
}
bool LargeRAWFile::Open(bool bReadWrite) {
#ifdef _WIN32
m_StreamFile = CreateFileA(m_strFilename.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
m_bIsOpen = m_StreamFile != INVALID_HANDLE_VALUE;
#else
m_StreamFile = fopen(m_strFilename.c_str(), (bReadWrite) ? "w+b" : "rb");
m_bIsOpen = m_StreamFile != NULL;
#endif
if (m_bIsOpen && m_iHeaderSize != 0) SeekStart();
m_bWritable = (m_bIsOpen) ? bReadWrite : false;
return m_bIsOpen;
}
bool LargeRAWFile::Create(UINT64 iInitialSize) {
#ifdef _WIN32
m_StreamFile = CreateFileA(m_strFilename.c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
m_bIsOpen = m_StreamFile != INVALID_HANDLE_VALUE;
#else
m_StreamFile = fopen(m_strFilename.c_str(), "w+b");
m_bIsOpen = m_StreamFile != NULL;
#endif
if (m_bIsOpen) {
SeekPos(iInitialSize);
SeekStart();
}
return m_bIsOpen;
}
void LargeRAWFile::Close() {
if (m_bIsOpen) {
#ifdef _WIN32
CloseHandle(m_StreamFile);
#else
fclose(m_StreamFile);
#endif
m_bIsOpen =false;
}
}
UINT64 LargeRAWFile::GetCurrentSize() {
UINT64 iPrevPos = GetPos();
SeekStart();
UINT64 ulStart = GetPos();
UINT64 ulEnd = SeekEnd();
UINT64 ulFileLength = ulEnd - ulStart;
SeekPos(iPrevPos);
return ulFileLength;
}
void LargeRAWFile::SeekStart(){
SeekPos(0);
}
UINT64 LargeRAWFile::SeekEnd(){
#ifdef _WIN32
LARGE_INTEGER liTarget, liRealTarget; liTarget.QuadPart = 0;
SetFilePointerEx(m_StreamFile, liTarget, &liRealTarget, FILE_END);
return UINT64(liRealTarget.QuadPart)-m_iHeaderSize;
#else
if(fseeko(m_StreamFile, 0, SEEK_END)==0)
return ftello(m_StreamFile)-m_iHeaderSize;//get current position=file size!
else
return 0;
#endif
}
UINT64 LargeRAWFile::GetPos(){
#ifdef _WIN32
LARGE_INTEGER liTarget, liRealTarget; liTarget.QuadPart = 0;
SetFilePointerEx(m_StreamFile, liTarget, &liRealTarget, FILE_CURRENT);
return UINT64(liRealTarget.QuadPart)-m_iHeaderSize;
#else
return ftello(m_StreamFile)-m_iHeaderSize;//get current position=file size!
#endif
}
void LargeRAWFile::SeekPos(UINT64 iPos){
#ifdef _WIN32
LARGE_INTEGER liTarget; liTarget.QuadPart = LONGLONG(iPos+m_iHeaderSize);
SetFilePointerEx(m_StreamFile, liTarget, NULL, FILE_BEGIN);
#else
fseeko(m_StreamFile, off_t(iPos+m_iHeaderSize), SEEK_SET);
#endif
}
size_t LargeRAWFile::ReadRAW(unsigned char* pData, UINT64 iCount){
#ifdef _WIN32
DWORD dwReadBytes;
ReadFile(m_StreamFile, pData, DWORD(iCount), &dwReadBytes, NULL);
return dwReadBytes;
#else
return fread(pData,1,iCount,m_StreamFile);
#endif
}
size_t LargeRAWFile::WriteRAW(const unsigned char* pData, UINT64 iCount){
#ifdef _WIN32
DWORD dwWrittenBytes;
WriteFile(m_StreamFile, pData, DWORD(iCount), &dwWrittenBytes, NULL);
return dwWrittenBytes;
#else
return fwrite(pData,1,iCount,m_StreamFile);
#endif
}
void LargeRAWFile::Delete() {
if (m_bIsOpen) Close();
remove(m_strFilename.c_str());
}
<commit_msg>Fix completely ridiculous compiler warning.<commit_after>#include "LargeRAWFile.h"
using namespace std;
#define BLOCK_COPY_SIZE (UINT64(128*1024*1024))
LargeRAWFile::LargeRAWFile(const std::string& strFilename, UINT64 iHeaderSize) :
m_strFilename(strFilename),
m_bIsOpen(false),
m_bWritable(false),
m_iHeaderSize(iHeaderSize)
{
}
LargeRAWFile::LargeRAWFile(const std::wstring& wstrFilename, UINT64 iHeaderSize) :
m_bIsOpen(false),
m_bWritable(false),
m_iHeaderSize(iHeaderSize)
{
string strFilename(wstrFilename.begin(), wstrFilename.end());
m_strFilename = strFilename;
}
LargeRAWFile::LargeRAWFile(LargeRAWFile &other) :
m_strFilename(other.m_strFilename+"~"),
m_bIsOpen(other.m_bIsOpen),
m_bWritable(other.m_bWritable),
m_iHeaderSize(other.m_iHeaderSize)
{
if (m_bIsOpen) {
UINT64 iDataSize = other.GetCurrentSize();
Create(iDataSize);
other.SeekStart();
unsigned char* pData = new unsigned char[size_t(min(iDataSize, BLOCK_COPY_SIZE))];
for (UINT64 i = 0;i<iDataSize;i+=BLOCK_COPY_SIZE) {
UINT64 iCopySize = min(BLOCK_COPY_SIZE, iDataSize-i);
other.ReadRAW(pData, iCopySize);
WriteRAW(pData, iCopySize);
}
delete [] pData;
}
}
bool LargeRAWFile::Open(bool bReadWrite) {
#ifdef _WIN32
m_StreamFile = CreateFileA(m_strFilename.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
m_bIsOpen = m_StreamFile != INVALID_HANDLE_VALUE;
#else
m_StreamFile = fopen(m_strFilename.c_str(), (bReadWrite) ? "w+b" : "rb");
m_bIsOpen = m_StreamFile != NULL;
#endif
if (m_bIsOpen && m_iHeaderSize != 0) SeekStart();
m_bWritable = (m_bIsOpen) ? bReadWrite : false;
return m_bIsOpen;
}
bool LargeRAWFile::Create(UINT64 iInitialSize) {
#ifdef _WIN32
m_StreamFile = CreateFileA(m_strFilename.c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
m_bIsOpen = m_StreamFile != INVALID_HANDLE_VALUE;
#else
m_StreamFile = fopen(m_strFilename.c_str(), "w+b");
m_bIsOpen = m_StreamFile != NULL;
#endif
if (m_bIsOpen) {
SeekPos(iInitialSize);
SeekStart();
}
return m_bIsOpen;
}
void LargeRAWFile::Close() {
if (m_bIsOpen) {
#ifdef _WIN32
CloseHandle(m_StreamFile);
#else
fclose(m_StreamFile);
#endif
m_bIsOpen =false;
}
}
UINT64 LargeRAWFile::GetCurrentSize() {
UINT64 iPrevPos = GetPos();
SeekStart();
UINT64 ulStart = GetPos();
UINT64 ulEnd = SeekEnd();
UINT64 ulFileLength = ulEnd - ulStart;
SeekPos(iPrevPos);
return ulFileLength;
}
void LargeRAWFile::SeekStart(){
SeekPos(0);
}
UINT64 LargeRAWFile::SeekEnd(){
#ifdef _WIN32
LARGE_INTEGER liTarget, liRealTarget; liTarget.QuadPart = 0;
SetFilePointerEx(m_StreamFile, liTarget, &liRealTarget, FILE_END);
return UINT64(liRealTarget.QuadPart)-m_iHeaderSize;
#else
if(fseeko(m_StreamFile, 0, SEEK_END)==0)
return ftello(m_StreamFile)-m_iHeaderSize;//get current position=file size!
else
return 0;
#endif
}
UINT64 LargeRAWFile::GetPos(){
#ifdef _WIN32
LARGE_INTEGER liTarget, liRealTarget; liTarget.QuadPart = 0;
SetFilePointerEx(m_StreamFile, liTarget, &liRealTarget, FILE_CURRENT);
return UINT64(liRealTarget.QuadPart)-m_iHeaderSize;
#else
return ftello(m_StreamFile)-m_iHeaderSize;//get current position=file size!
#endif
}
void LargeRAWFile::SeekPos(UINT64 iPos){
#ifdef _WIN32
LARGE_INTEGER liTarget; liTarget.QuadPart = LONGLONG(iPos+m_iHeaderSize);
SetFilePointerEx(m_StreamFile, liTarget, NULL, FILE_BEGIN);
#else
fseeko(m_StreamFile, off_t(iPos+m_iHeaderSize), SEEK_SET);
#endif
}
size_t LargeRAWFile::ReadRAW(unsigned char* pData, UINT64 iCount){
#ifdef _WIN32
DWORD dwReadBytes;
ReadFile(m_StreamFile, pData, DWORD(iCount), &dwReadBytes, NULL);
return dwReadBytes;
#else
return fread(pData,1,iCount,m_StreamFile);
#endif
}
size_t LargeRAWFile::WriteRAW(const unsigned char* pData, UINT64 iCount){
#ifdef _WIN32
DWORD dwWrittenBytes;
WriteFile(m_StreamFile, pData, DWORD(iCount), &dwWrittenBytes, NULL);
return dwWrittenBytes;
#else
return fwrite(pData,1,iCount,m_StreamFile);
#endif
}
void LargeRAWFile::Delete() {
if (m_bIsOpen) Close();
remove(m_strFilename.c_str());
}
<|endoftext|>
|
<commit_before>// RUN: %check_clang_tidy %s cppcoreguidelines-pro-type-member-init %t -- -config="{CheckOptions: [{key: "cppcoreguidelines-pro-type-member-init.UseAssignment", value: 1}]}"
struct T {
int i;
};
struct S {
bool b;
// CHECK-FIXES: bool b = false;
char c;
// CHECK-FIXES: char c = 0;
signed char sc;
// CHECK-FIXES: signed char sc = 0;
unsigned char uc;
// CHECK-FIXES: unsigned char uc = 0U;
int i;
// CHECK-FIXES: int i = 0;
unsigned u;
// CHECK-FIXES: unsigned u = 0U;
long l;
// CHECK-FIXES: long l = 0L;
unsigned long ul;
// CHECK-FIXES: unsigned long ul = 0UL;
long long ll;
// CHECK-FIXES: long long ll = 0LL;
unsigned long long ull;
// CHECK-FIXES: unsigned long long ull = 0ULL;
float f;
// CHECK-FIXES: float f = 0.0F;
double d;
// CHECK-FIXES: double d = 0.0;
long double ld;
// CHECK-FIXES: double ld = 0.0L;
int *ptr;
// CHECK-FIXES: int *ptr = nullptr;
T t;
// CHECK-FIXES: T t{};
S() {}
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: constructor does not initialize these fields:
};
<commit_msg>Make cppcoreguidelines-pro-type-member-init-use-assignment.cpp pass on platforms where char is unsigned<commit_after>// RUN: %check_clang_tidy %s cppcoreguidelines-pro-type-member-init %t -- -config="{CheckOptions: [{key: "cppcoreguidelines-pro-type-member-init.UseAssignment", value: 1}]}" -- -fsigned-char
struct T {
int i;
};
struct S {
bool b;
// CHECK-FIXES: bool b = false;
char c;
// CHECK-FIXES: char c = 0;
signed char sc;
// CHECK-FIXES: signed char sc = 0;
unsigned char uc;
// CHECK-FIXES: unsigned char uc = 0U;
int i;
// CHECK-FIXES: int i = 0;
unsigned u;
// CHECK-FIXES: unsigned u = 0U;
long l;
// CHECK-FIXES: long l = 0L;
unsigned long ul;
// CHECK-FIXES: unsigned long ul = 0UL;
long long ll;
// CHECK-FIXES: long long ll = 0LL;
unsigned long long ull;
// CHECK-FIXES: unsigned long long ull = 0ULL;
float f;
// CHECK-FIXES: float f = 0.0F;
double d;
// CHECK-FIXES: double d = 0.0;
long double ld;
// CHECK-FIXES: double ld = 0.0L;
int *ptr;
// CHECK-FIXES: int *ptr = nullptr;
T t;
// CHECK-FIXES: T t{};
S() {}
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: constructor does not initialize these fields:
};
<|endoftext|>
|
<commit_before>/*
* Copyright 2015 - 2016 gtalent2@gmail.com
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#pragma once
#include <ox/std/std.hpp>
namespace ox {
namespace fs {
using namespace ox::std;
template<typename FsT>
class FileStore {
public:
typedef uint16_t InodeId_t;
typedef FsT FsSize_t;
struct StatInfo {
InodeId_t inodeId;
FsSize_t size;
};
private:
struct Inode {
// the next Inode in memory
FsSize_t prev, next;
// The following variables should not be assumed to exist
FsSize_t dataLen;
InodeId_t m_id;
uint8_t refs;
FsSize_t left, right;
FsSize_t size();
void setId(InodeId_t);
void setData(void *data, int size);
void *data();
private:
Inode() = default;
};
uint32_t m_version;
FsSize_t m_size;
FsSize_t m_firstInode;
FsSize_t m_rootInode;
public:
/**
* Initializes the memory chunk of this FileStore was given.
* This clears the previous contents.
*/
void init();
/**
* Writes the given data to a "file" with the given id.
* @param id the id of the file
* @param data the contents of the file
* @param dataLen the number of bytes data points to
*/
int write(void *data, FsSize_t dataLen);
/**
* Writes the given data to a "file" with the given id.
* @param id the id of the file
* @param data the contents of the file
* @param dataLen the number of bytes data points to
*/
int write(InodeId_t id, void *data, FsSize_t dataLen);
/**
* Reads the "file" at the given id. You are responsible for freeing
* the data when done with it.
* @param id id of the "file"
* @param data pointer to the pointer where the data is stored
* @param size pointer to a value that will be assigned the size of data
* @return 0 if read is a success
*/
int read(InodeId_t id, void *data, FsSize_t *size);
/**
* Reads the stat information of the inode of the given inode id.
* If the returned inode id is 0, then the requested inode was not found.
* @param id id of the inode to stat
* @return the stat information of the inode of the given inode id
*/
StatInfo stat(InodeId_t id);
static uint8_t version();
static uint8_t *format(uint8_t *buffer, FsSize_t size);
private:
/**
* Gets the inode at the given id.
* @param root the root node to start comparing on
* @param id id of the "file"
* @param pathLen number of characters in pathLen
* @return the requested Inode, if available
*/
Inode *getInode(Inode *root, InodeId_t id);
/**
* Gets an address for a new Inode.
* @param size the size of the Inode
*/
void *alloc(FsSize_t size);
/**
* Compresses all of the inode into a contiguous space, starting at m_firstInode.
*/
void compress();
/**
* Inserts the given insertValue into the tree of the given root.
* If the inode already exists, it replaces the old on deletes it.
* @return true if the inode was inserted
*/
bool insert(Inode *root, Inode *insertValue);
/**
* Gets the FsSize_t associated with the next Inode to be allocated.
* @retrun the FsSize_t associated with the next Inode to be allocated
*/
FsSize_t iterator();
Inode *firstInode();
Inode *lastInode();
uint8_t *begin() {
return (uint8_t*) this;
}
uint8_t *end() {
return begin() + this->m_size;
}
/**
* Converts an actual pointer to a FsSize_t.
*/
FsSize_t ptr(void *ptr);
/**
* Converts a FsSize_t to an actual pointer.
*/
template<typename T>
T ptr(FsSize_t ptr) {
return (T) (begin() + ptr);
};
};
template<typename FsSize_t>
FsSize_t FileStore<FsSize_t>::Inode::size() {
return sizeof(Inode) + dataLen;
}
template<typename FsSize_t>
void FileStore<FsSize_t>::Inode::setId(InodeId_t id) {
this->m_id = id;
}
template<typename FsSize_t>
void FileStore<FsSize_t>::Inode::setData(void *data, int size) {
memcpy(this->data(), data, size);
dataLen = size;
}
template<typename FsSize_t>
void *FileStore<FsSize_t>::Inode::data() {
return this + 1;
}
// FileStore
template<typename FsSize_t>
int FileStore<FsSize_t>::write(void *data, FsSize_t dataLen) {
return 1;
}
template<typename FsSize_t>
int FileStore<FsSize_t>::write(InodeId_t id, void *data, FsSize_t dataLen) {
auto retval = 1;
const FsSize_t size = sizeof(Inode) + dataLen;
auto inode = (Inode*) alloc(size);
if (inode) {
auto root = ptr<Inode*>(m_rootInode);
inode->m_id = id;
inode->setData(data, dataLen);
if (insert(root, inode) || root == inode) {
retval = 0;
}
}
return retval;
}
template<typename FsSize_t>
int FileStore<FsSize_t>::read(InodeId_t id, void *data, FsSize_t *size) {
auto inode = getInode(ptr<Inode*>(m_rootInode), id);
int retval = 1;
if (inode) {
if (size) {
*size = inode->dataLen;
}
memcpy(data, inode->data(), inode->dataLen);
retval = 0;
}
return retval;
}
template<typename FsSize_t>
typename FileStore<FsSize_t>::StatInfo FileStore<FsSize_t>::stat(InodeId_t id) {
auto inode = getInode(ptr<Inode*>(m_rootInode), id);
StatInfo stat;
if (inode) {
stat.size = inode->dataLen;
stat.inodeId = id;
} else {
stat.inodeId = 0;
}
return stat;
}
template<typename FsSize_t>
typename FileStore<FsSize_t>::Inode *FileStore<FsSize_t>::getInode(Inode *root, InodeId_t id) {
Inode *retval = nullptr;
if (root->m_id > id) {
if (root->left) {
retval = getInode(ptr<Inode*>(root->left), id);
}
} else if (root->m_id < id) {
if (root->right) {
retval = getInode(ptr<Inode*>(root->right), id);
}
} else if (root->m_id == id) {
retval = root;
}
return retval;
}
template<typename FsSize_t>
void *FileStore<FsSize_t>::alloc(FsSize_t size) {
if ((lastInode()->next + size) > (uint64_t) end()) {
compress();
if ((lastInode()->next + size) > (uint64_t) end()) {
return nullptr;
}
}
const auto retval = lastInode()->next;
const auto inode = ptr<Inode*>(retval);
memset(inode, 0, size);
inode->next = retval + size;
ptr<Inode*>(m_firstInode)->prev = retval;
return inode;
}
template<typename FsSize_t>
void FileStore<FsSize_t>::compress() {
auto current = ptr<Inode*>(m_firstInode);
while (current->next) {
auto prevEnd = current + current->size();
current = ptr<Inode*>(current->next);
if (prevEnd != current) {
memcpy(prevEnd, current, current->size());
current = prevEnd;
}
}
}
template<typename FsSize_t>
bool FileStore<FsSize_t>::insert(Inode *root, Inode *insertValue) {
auto retval = false;
if (root->m_id > insertValue->m_id) {
if (root->left) {
retval = insert(ptr<Inode*>(root->left), insertValue);
} else {
root->left = ptr(insertValue);
retval = true;
}
} else if (root->m_id < insertValue->m_id) {
if (root->right) {
retval = insert(ptr<Inode*>(root->right), insertValue);
} else {
root->right = ptr(insertValue);
retval = true;
}
}
return retval;
}
template<typename FsSize_t>
FsSize_t FileStore<FsSize_t>::iterator() {
return ptr(lastInode()) + lastInode()->size();
}
template<typename FsSize_t>
FsSize_t FileStore<FsSize_t>::ptr(void *ptr) {
return ((uint8_t*) ptr) - begin();
}
template<typename FsSize_t>
typename FileStore<FsSize_t>::Inode *FileStore<FsSize_t>::firstInode() {
return ptr<Inode*>(sizeof(FileStore<FsSize_t>));
}
template<typename FsSize_t>
typename FileStore<FsSize_t>::Inode *FileStore<FsSize_t>::lastInode() {
return ptr<Inode*>(ptr<Inode*>(m_firstInode)->prev);
}
template<typename FsSize_t>
uint8_t FileStore<FsSize_t>::version() {
return 0;
};
template<typename FsSize_t>
uint8_t *FileStore<FsSize_t>::format(uint8_t *buffer, FsSize_t size) {
memset(buffer, 0, size);
auto *fs = (FileStore*) buffer;
fs->m_version = FileStore<FsSize_t>::version();
fs->m_size = size;
fs->m_rootInode = sizeof(FileStore<FsSize_t>);
fs->m_firstInode = sizeof(FileStore<FsSize_t>);
fs->lastInode()->m_id = 0;
fs->lastInode()->next = sizeof(FileStore<FsSize_t>);
return (uint8_t*) buffer;
}
typedef FileStore<uint16_t> FileStore16;
typedef FileStore<uint32_t> FileStore32;
typedef FileStore<uint64_t> FileStore64;
}
}
<commit_msg>Fixed tracking last inode.<commit_after>/*
* Copyright 2015 - 2016 gtalent2@gmail.com
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#pragma once
#include <ox/std/std.hpp>
namespace ox {
namespace fs {
using namespace ox::std;
template<typename FsT>
class FileStore {
public:
typedef uint16_t InodeId_t;
typedef FsT FsSize_t;
struct StatInfo {
InodeId_t inodeId;
FsSize_t size;
};
private:
struct Inode {
// the next Inode in memory
FsSize_t prev, next;
// The following variables should not be assumed to exist
FsSize_t dataLen;
InodeId_t m_id;
uint8_t refs;
FsSize_t left, right;
FsSize_t size();
void setId(InodeId_t);
void setData(void *data, int size);
void *data();
private:
Inode() = default;
};
uint32_t m_version;
FsSize_t m_size;
FsSize_t m_firstInode;
FsSize_t m_rootInode;
public:
/**
* Initializes the memory chunk of this FileStore was given.
* This clears the previous contents.
*/
void init();
/**
* Writes the given data to a "file" with the given id.
* @param id the id of the file
* @param data the contents of the file
* @param dataLen the number of bytes data points to
*/
int write(void *data, FsSize_t dataLen);
/**
* Writes the given data to a "file" with the given id.
* @param id the id of the file
* @param data the contents of the file
* @param dataLen the number of bytes data points to
*/
int write(InodeId_t id, void *data, FsSize_t dataLen);
/**
* Reads the "file" at the given id. You are responsible for freeing
* the data when done with it.
* @param id id of the "file"
* @param data pointer to the pointer where the data is stored
* @param size pointer to a value that will be assigned the size of data
* @return 0 if read is a success
*/
int read(InodeId_t id, void *data, FsSize_t *size);
/**
* Reads the stat information of the inode of the given inode id.
* If the returned inode id is 0, then the requested inode was not found.
* @param id id of the inode to stat
* @return the stat information of the inode of the given inode id
*/
StatInfo stat(InodeId_t id);
static uint8_t version();
static uint8_t *format(uint8_t *buffer, FsSize_t size);
private:
/**
* Gets the inode at the given id.
* @param root the root node to start comparing on
* @param id id of the "file"
* @param pathLen number of characters in pathLen
* @return the requested Inode, if available
*/
Inode *getInode(Inode *root, InodeId_t id);
/**
* Gets an address for a new Inode.
* @param size the size of the Inode
*/
void *alloc(FsSize_t size);
/**
* Compresses all of the inode into a contiguous space, starting at m_firstInode.
*/
void compress();
/**
* Inserts the given insertValue into the tree of the given root.
* If the inode already exists, it replaces the old on deletes it.
* @return true if the inode was inserted
*/
bool insert(Inode *root, Inode *insertValue);
/**
* Gets the FsSize_t associated with the next Inode to be allocated.
* @retrun the FsSize_t associated with the next Inode to be allocated
*/
FsSize_t iterator();
Inode *firstInode();
Inode *lastInode();
uint8_t *begin() {
return (uint8_t*) this;
}
uint8_t *end() {
return begin() + this->m_size;
}
/**
* Converts an actual pointer to a FsSize_t.
*/
FsSize_t ptr(void *ptr);
/**
* Converts a FsSize_t to an actual pointer.
*/
template<typename T>
T ptr(FsSize_t ptr) {
return (T) (begin() + ptr);
};
};
template<typename FsSize_t>
FsSize_t FileStore<FsSize_t>::Inode::size() {
return sizeof(Inode) + dataLen;
}
template<typename FsSize_t>
void FileStore<FsSize_t>::Inode::setId(InodeId_t id) {
this->m_id = id;
}
template<typename FsSize_t>
void FileStore<FsSize_t>::Inode::setData(void *data, int size) {
memcpy(this->data(), data, size);
dataLen = size;
}
template<typename FsSize_t>
void *FileStore<FsSize_t>::Inode::data() {
return this + 1;
}
// FileStore
template<typename FsSize_t>
int FileStore<FsSize_t>::write(void *data, FsSize_t dataLen) {
return 1;
}
template<typename FsSize_t>
int FileStore<FsSize_t>::write(InodeId_t id, void *data, FsSize_t dataLen) {
auto retval = 1;
const FsSize_t size = sizeof(Inode) + dataLen;
//printf("%d\n", m_rootInode);
auto inode = (Inode*) alloc(size);
if (inode) {
auto root = ptr<Inode*>(m_rootInode);
inode->m_id = id;
inode->setData(data, dataLen);
if (insert(root, inode) || root == inode) {
retval = 0;
}
}
return retval;
}
template<typename FsSize_t>
int FileStore<FsSize_t>::read(InodeId_t id, void *data, FsSize_t *size) {
auto inode = getInode(ptr<Inode*>(m_rootInode), id);
int retval = 1;
if (inode) {
if (size) {
*size = inode->dataLen;
}
memcpy(data, inode->data(), inode->dataLen);
retval = 0;
}
return retval;
}
template<typename FsSize_t>
typename FileStore<FsSize_t>::StatInfo FileStore<FsSize_t>::stat(InodeId_t id) {
auto inode = getInode(ptr<Inode*>(m_rootInode), id);
StatInfo stat;
if (inode) {
stat.size = inode->dataLen;
stat.inodeId = id;
} else {
stat.inodeId = 0;
}
return stat;
}
template<typename FsSize_t>
typename FileStore<FsSize_t>::Inode *FileStore<FsSize_t>::getInode(Inode *root, InodeId_t id) {
Inode *retval = nullptr;
if (root->m_id > id) {
if (root->left) {
retval = getInode(ptr<Inode*>(root->left), id);
}
} else if (root->m_id < id) {
if (root->right) {
retval = getInode(ptr<Inode*>(root->right), id);
}
} else if (root->m_id == id) {
retval = root;
}
return retval;
}
template<typename FsSize_t>
void *FileStore<FsSize_t>::alloc(FsSize_t size) {
if ((lastInode()->next + size) > (uint64_t) end()) {
compress();
if ((lastInode()->next + size) > (uint64_t) end()) {
return nullptr;
}
}
const auto retval = lastInode()->next;
const auto inode = ptr<Inode*>(retval);
memset(inode, 0, size);
inode->next = retval + size;
ptr<Inode*>(m_firstInode)->prev = retval;
return inode;
}
template<typename FsSize_t>
void FileStore<FsSize_t>::compress() {
auto current = ptr<Inode*>(m_firstInode);
while (current->next) {
auto prevEnd = current + current->size();
current = ptr<Inode*>(current->next);
if (prevEnd != current) {
memcpy(prevEnd, current, current->size());
current = prevEnd;
}
}
}
template<typename FsSize_t>
bool FileStore<FsSize_t>::insert(Inode *root, Inode *insertValue) {
auto retval = false;
if (root->m_id > insertValue->m_id) {
if (root->left) {
retval = insert(ptr<Inode*>(root->left), insertValue);
} else {
root->left = ptr(insertValue);
retval = true;
}
} else if (root->m_id < insertValue->m_id) {
if (root->right) {
retval = insert(ptr<Inode*>(root->right), insertValue);
} else {
root->right = ptr(insertValue);
retval = true;
}
}
return retval;
}
template<typename FsSize_t>
FsSize_t FileStore<FsSize_t>::iterator() {
return ptr(lastInode()) + lastInode()->size();
}
template<typename FsSize_t>
FsSize_t FileStore<FsSize_t>::ptr(void *ptr) {
return ((uint8_t*) ptr) - begin();
}
template<typename FsSize_t>
typename FileStore<FsSize_t>::Inode *FileStore<FsSize_t>::firstInode() {
return ptr<Inode*>(sizeof(FileStore<FsSize_t>));
}
template<typename FsSize_t>
typename FileStore<FsSize_t>::Inode *FileStore<FsSize_t>::lastInode() {
return ptr<Inode*>(ptr<Inode*>(m_firstInode)->prev);
}
template<typename FsSize_t>
uint8_t FileStore<FsSize_t>::version() {
return 0;
};
template<typename FsSize_t>
uint8_t *FileStore<FsSize_t>::format(uint8_t *buffer, FsSize_t size) {
memset(buffer, 0, size);
auto *fs = (FileStore*) buffer;
fs->m_version = FileStore<FsSize_t>::version();
fs->m_size = size;
fs->m_rootInode = sizeof(FileStore<FsSize_t>);
fs->m_firstInode = sizeof(FileStore<FsSize_t>);
fs->firstInode()->prev = fs->m_firstInode;
fs->lastInode()->next = sizeof(FileStore<FsSize_t>);
return (uint8_t*) buffer;
}
typedef FileStore<uint16_t> FileStore16;
typedef FileStore<uint32_t> FileStore32;
typedef FileStore<uint64_t> FileStore64;
}
}
<|endoftext|>
|
<commit_before>/*
* Use and distribution licensed under the Apache license version 2.
*
* See the COPYING file in the root project directory for full text.
*/
#include <iostream>
#include <cctype>
#include <sstream>
#include "parser/error.h"
#include "parser/parse.h"
#include "parser/symbol.h"
#include "parser/token.h"
namespace sqltoast {
static const size_t NUM_CREATE_STATEMENT_PARSERS = 2;
static const parse_func_t create_statement_parsers[2] = {
&parse_create_table,
&parse_create_schema
};
static const size_t NUM_DROP_STATEMENT_PARSERS = 2;
static const parse_func_t drop_statement_parsers[2] = {
&parse_drop_table,
&parse_drop_schema
};
static const size_t NUM_DELETE_STATEMENT_PARSERS = 1;
static const parse_func_t delete_statement_parsers[1] = {
&parse_delete
};
static const size_t NUM_SELECT_STATEMENT_PARSERS = 1;
static const parse_func_t select_statement_parsers[1] = {
&parse_select
};
static const size_t NUM_INSERT_STATEMENT_PARSERS = 1;
static const parse_func_t insert_statement_parsers[1] = {
&parse_insert
};
static const size_t NUM_UPDATE_STATEMENT_PARSERS = 1;
static const parse_func_t update_statement_parsers[1] = {
&parse_update
};
void parse_statement(parse_context_t& ctx) {
// Assumption: the current token will be a keyword
lexer_t& lex = ctx.lexer;
token_t& cur_tok = lex.current_token;
symbol_t cur_sym = cur_tok.symbol;
std::unique_ptr<statement_t> stmt_p;
size_t num_parsers = 0;
const parse_func_t* parsers;
switch (cur_sym) {
case SYMBOL_CREATE:
{
num_parsers = NUM_CREATE_STATEMENT_PARSERS;
parsers = create_statement_parsers;
break;
}
case SYMBOL_DELETE:
{
num_parsers = NUM_DELETE_STATEMENT_PARSERS;
parsers = delete_statement_parsers;
break;
}
case SYMBOL_DROP:
{
num_parsers = NUM_DROP_STATEMENT_PARSERS;
parsers = drop_statement_parsers;
break;
}
case SYMBOL_SELECT:
{
num_parsers = NUM_SELECT_STATEMENT_PARSERS;
parsers = select_statement_parsers;
break;
}
case SYMBOL_INSERT:
{
num_parsers = NUM_INSERT_STATEMENT_PARSERS;
parsers = insert_statement_parsers;
break;
}
case SYMBOL_UPDATE:
{
num_parsers = NUM_UPDATE_STATEMENT_PARSERS;
parsers = update_statement_parsers;
break;
}
default:
return;
}
size_t x = 0;
while (ctx.result.code == PARSE_OK && x < num_parsers) {
if (parsers[x++](ctx, cur_tok, stmt_p))
goto push_statement;
}
if (ctx.result.code == PARSE_SYNTAX_ERROR) {
// Already have a nicely-formatted error, so just return
return;
} else {
std::stringstream estr;
estr << "Failed to recognize any valid SQL statement." << std::endl;
create_syntax_error_marker(ctx, estr);
}
push_statement:
if (ctx.opts.disable_statement_construction)
return;
ctx.result.statements.emplace_back(std::move(stmt_p));
}
} // namespace sqltoast
<commit_msg>link in alter table parser into parse_statement()<commit_after>/*
* Use and distribution licensed under the Apache license version 2.
*
* See the COPYING file in the root project directory for full text.
*/
#include <iostream>
#include <cctype>
#include <sstream>
#include "parser/error.h"
#include "parser/parse.h"
#include "parser/symbol.h"
#include "parser/token.h"
namespace sqltoast {
static const size_t NUM_ALTER_STATEMENT_PARSERS = 1;
static const parse_func_t alter_statement_parsers[1] = {
&parse_alter_table
};
static const size_t NUM_CREATE_STATEMENT_PARSERS = 2;
static const parse_func_t create_statement_parsers[2] = {
&parse_create_table,
&parse_create_schema
};
static const size_t NUM_DROP_STATEMENT_PARSERS = 2;
static const parse_func_t drop_statement_parsers[2] = {
&parse_drop_table,
&parse_drop_schema
};
static const size_t NUM_DELETE_STATEMENT_PARSERS = 1;
static const parse_func_t delete_statement_parsers[1] = {
&parse_delete
};
static const size_t NUM_SELECT_STATEMENT_PARSERS = 1;
static const parse_func_t select_statement_parsers[1] = {
&parse_select
};
static const size_t NUM_INSERT_STATEMENT_PARSERS = 1;
static const parse_func_t insert_statement_parsers[1] = {
&parse_insert
};
static const size_t NUM_UPDATE_STATEMENT_PARSERS = 1;
static const parse_func_t update_statement_parsers[1] = {
&parse_update
};
void parse_statement(parse_context_t& ctx) {
// Assumption: the current token will be a keyword
lexer_t& lex = ctx.lexer;
token_t& cur_tok = lex.current_token;
symbol_t cur_sym = cur_tok.symbol;
std::unique_ptr<statement_t> stmt_p;
size_t num_parsers = 0;
const parse_func_t* parsers;
switch (cur_sym) {
case SYMBOL_ALTER:
{
num_parsers = NUM_ALTER_STATEMENT_PARSERS;
parsers = alter_statement_parsers;
break;
}
case SYMBOL_CREATE:
{
num_parsers = NUM_CREATE_STATEMENT_PARSERS;
parsers = create_statement_parsers;
break;
}
case SYMBOL_DELETE:
{
num_parsers = NUM_DELETE_STATEMENT_PARSERS;
parsers = delete_statement_parsers;
break;
}
case SYMBOL_DROP:
{
num_parsers = NUM_DROP_STATEMENT_PARSERS;
parsers = drop_statement_parsers;
break;
}
case SYMBOL_SELECT:
{
num_parsers = NUM_SELECT_STATEMENT_PARSERS;
parsers = select_statement_parsers;
break;
}
case SYMBOL_INSERT:
{
num_parsers = NUM_INSERT_STATEMENT_PARSERS;
parsers = insert_statement_parsers;
break;
}
case SYMBOL_UPDATE:
{
num_parsers = NUM_UPDATE_STATEMENT_PARSERS;
parsers = update_statement_parsers;
break;
}
default:
{
std::stringstream estr;
estr << "Failed to recognize any valid SQL statement." << std::endl;
create_syntax_error_marker(ctx, estr);
return;
}
}
size_t x = 0;
while (ctx.result.code == PARSE_OK && x < num_parsers) {
if (parsers[x++](ctx, cur_tok, stmt_p))
goto push_statement;
}
if (ctx.result.code == PARSE_SYNTAX_ERROR) {
// Already have a nicely-formatted error, so just return
return;
} else {
std::stringstream estr;
estr << "Failed to recognize any valid SQL statement." << std::endl;
create_syntax_error_marker(ctx, estr);
}
push_statement:
if (ctx.opts.disable_statement_construction)
return;
ctx.result.statements.emplace_back(std::move(stmt_p));
}
} // namespace sqltoast
<|endoftext|>
|
<commit_before>///
/// @file pi_deleglise_rivat_parallel1.cpp
/// @brief Parallel implementation of the Lagarias-Miller-Odlyzko
/// prime counting algorithm with the improvements of Deleglise
/// and Rivat. This implementation is based on
/// pi_deleglise_rivat1.cpp and the paper: Tomás Oliveira e
/// Silva, Computing pi(x): the combinatorial method, Revista
/// do DETUA, vol. 4, no. 6, March 2006, pp. 759-768.
///
/// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <primecount-internal.hpp>
#include <primesieve.hpp>
#include <pmath.hpp>
#include <pi_bsearch.hpp>
#include <PhiTiny.hpp>
#include <tos_counters.hpp>
#include <utils.hpp>
#include <stdint.h>
#include <algorithm>
#include <vector>
#ifdef _OPENMP
#include <omp.h>
#endif
using namespace std;
namespace {
/// For each prime calculate its first multiple >= low.
template <typename T1, typename T2>
void initialize_next_multiples(T1* next, T2& primes, int64_t size, int64_t low)
{
next->reserve(size);
next->push_back(0);
for (int64_t b = 1; b < size; b++)
{
int64_t prime = primes[b];
int64_t next_multiple = ((low + prime - 1) / prime) * prime;
next->push_back(next_multiple);
}
}
template <typename T1, typename T2>
void cross_off(int64_t prime, int64_t low, int64_t high, int64_t& next_multiple, T1& sieve, T2& counters)
{
int64_t segment_size = sieve.size();
int64_t k = next_multiple + prime * (~next_multiple & 1);
for (; k < high; k += prime * 2)
{
if (sieve[k - low])
{
sieve[k - low] = 0;
cnt_update(counters, k - low, segment_size);
}
}
next_multiple = k;
}
/// Compute the S2 contribution for the interval
/// [low_process, low_process + segments * segment_size[.
/// The missing special leaf contributions for the interval
/// [1, low_process[ are later reconstructed and added in
/// the calling (parent) S2 function.
///
int64_t S2_thread(int64_t x,
int64_t y,
int64_t c,
int64_t pi_sqrty,
int64_t pi_y,
int64_t segment_size,
int64_t segments_per_thread,
int64_t thread_num,
int64_t low,
int64_t limit,
vector<int32_t>& pi,
vector<int32_t>& primes,
vector<int32_t>& lpf,
vector<int32_t>& mu,
vector<int64_t>& mu_sum,
vector<int64_t>& phi,
vector<int32_t>& min_trivial_leaves,
vector<int32_t>& min_easy_leaves)
{
low += segment_size * segments_per_thread * thread_num;
limit = min(low + segment_size * segments_per_thread, limit);
int64_t size = pi[min(isqrt(x / low), y)] + 1;
int64_t S2_thread = 0;
if (c >= size - 1)
return 0;
vector<char> sieve(segment_size);
vector<int32_t> counters(segment_size);
vector<int64_t> next;
initialize_next_multiples(&next, primes, size, low);
phi.resize(size, 0);
mu_sum.resize(size, 0);
// Process the segments corresponding to the current thread
for (; low < limit; low += segment_size)
{
fill(sieve.begin(), sieve.end(), 1);
// Current segment = interval [low, high[
int64_t high = min(low + segment_size, limit);
int64_t b = 1;
for (; b <= c; b++)
{
int64_t k = next[b];
for (int64_t prime = primes[b]; k < high; k += prime)
sieve[k - low] = 0;
next[b] = k;
}
// Initialize special tree data structure from sieve
cnt_finit(sieve, counters, segment_size);
// For c + 1 <= b < pi_sqrty
// Find all special leaves: n = primes[b] * m, with mu[m] != 0 and primes[b] < lpf[m]
// which satisfy: low <= (x / n) < high
for (; b < min(pi_sqrty, size); b++)
{
int64_t prime = primes[b];
int64_t min_m = max(x / (prime * high), y / prime);
int64_t max_m = min(x / (prime * low), y);
if (prime >= max_m)
goto next_segment;
for (int64_t m = max_m; m > min_m; m--)
{
if (mu[m] != 0 && prime < lpf[m])
{
int64_t n = prime * m;
int64_t count = cnt_query(counters, (x / n) - low);
int64_t phi_xn = phi[b] + count;
S2_thread -= mu[m] * phi_xn;
mu_sum[b] -= mu[m];
}
}
phi[b] += cnt_query(counters, (high - 1) - low);
cross_off(prime, low, high, next[b], sieve, counters);
}
// For pi_sqrty <= b < pi_y
// Find all special leaves: n = primes[b] * primes[l]
// which satisfy: low <= (x / n) < high
for (; b < pi_y; b++)
{
int64_t prime = primes[b];
int64_t l = pi[min(x / (prime * low), y)];
int64_t min_m = min(y, max(x / (prime * high), y / prime));
int64_t min_hard_leaf = pi[max(min_m, prime)];
int64_t min_trivial_leaf = max<int64_t>(min_hard_leaf, min_trivial_leaves[b]);
int64_t min_easy_leaf = max<int64_t>(min_hard_leaf, min_easy_leaves[b]);
if (prime >= primes[l])
goto next_segment;
// For max(x / primes[b]^2, primes[b]) < primes[l] <= y
// Find all trivial leaves which satisfy:
// phi(x / (primes[b] * primes[l]), b - 1) = 1
if (l > min_trivial_leaf)
{
S2_thread += l - min_trivial_leaf;
l = min_trivial_leaf;
}
// For max(z / primes[b], primes[b]) < primes[l] <= max(x / primes[b]^2, y)
// Find all easy leaves: n = primes[b] * primes[l]
// which satisfy x / n <= y such that:
// phi(x / n, b - 1) = pi[x / n] - b + 2
for (; l > min_easy_leaf; l--)
{
int64_t n = prime * primes[l];
int64_t xn = x / n;
S2_thread += pi[xn] - b + 2;
}
// For max(x / (prime * high), prime) < primes[l] <= max(z / primes[b], primes[b])
// Find all hard leaves: n = primes[b] * primes[l]
// which satisfy: low <= (x / n) < high
for (; l > min_hard_leaf; l--)
{
int64_t n = prime * primes[l];
int64_t xn = x / n;
int64_t count = cnt_query(counters, xn - low);
int64_t phi_xn = phi[b] + count;
S2_thread += phi_xn;
mu_sum[b]++;
}
phi[b] += cnt_query(counters, (high - 1) - low);
cross_off(prime, low, high, next[b], sieve, counters);
}
next_segment:;
}
return S2_thread;
}
/// Calculate the contribution of the special leaves.
/// This is a parallel implementation with advanced load balancing.
/// As most special leaves tend to be in the first segments we
/// start off with a small segment size and few segments
/// per thread, after each iteration we dynamically increase
/// the segment size and the segments per thread.
/// @pre y > 0 && c > 1
///
int64_t S2(int64_t x,
int64_t y,
int64_t z,
int64_t pi_y,
int64_t c,
vector<int32_t>& primes,
vector<int32_t>& lpf,
vector<int32_t>& mu,
int threads)
{
threads = validate_threads(threads);
int64_t S2_total = 0;
int64_t low = 1;
int64_t limit = x / y + 1;
int64_t sqrt_limit = isqrt(limit);
int64_t logx = max(1, ilog(x));
int64_t min_segment_size = 1 << 6;
int64_t segment_size = next_power_of_2(sqrt_limit / (logx * threads));
int64_t segments_per_thread = 1;
int64_t pi_sqrty = pi_bsearch(primes, isqrt(y));
vector<int32_t> pi = make_pi(y);
vector<int32_t> min_trivial_leaves(primes.size());
vector<int32_t> min_easy_leaves(primes.size());
vector<int64_t> phi_total(primes.size(), 0);
segment_size = max(segment_size, min_segment_size);
for (size_t i = 1; i < primes.size(); i++)
{
int64_t prime = primes[i];
min_trivial_leaves[i] = pi[min(y, max(x / (prime * prime), prime))];
min_easy_leaves[i] = pi[min(y, max(z / prime, prime))];
}
while (low < limit)
{
int64_t segments = (limit - low + segment_size - 1) / segment_size;
threads = in_between(1, threads, segments);
segments_per_thread = in_between(1, segments_per_thread, (segments + threads - 1) / threads);
double seconds = get_wtime();
vector<vector<int64_t> > phi(threads);
vector<vector<int64_t> > mu_sum(threads);
#pragma omp parallel for num_threads(threads) reduction(+: S2_total)
for (int i = 0; i < threads; i++)
S2_total += S2_thread(x, y, c, pi_sqrty, pi_y, segment_size, segments_per_thread,
i, low, limit, pi, primes, lpf, mu, mu_sum[i], phi[i], min_trivial_leaves, min_easy_leaves);
seconds = get_wtime() - seconds;
low += segments_per_thread * threads * segment_size;
// Dynamically increase segment_size or segments_per_thread
// if the running time is less than a certain threshold.
// We start off with a small segment size and few segments
// per thread as most special leaves are in the first segments
// whereas later on there are very few special leaves.
//
if (low > sqrt_limit && seconds < 10)
{
if (segment_size < sqrt_limit)
segment_size <<= 1;
else
segments_per_thread *= 2;
}
// Once all threads have finished reconstruct and add the
// missing contribution of all special leaves. This must
// be done in order as each thread (i) requires the sum of
// the phi values from the previous threads.
//
for (int i = 0; i < threads; i++)
{
for (size_t j = 1; j < phi[i].size(); j++)
{
S2_total += phi_total[j] * mu_sum[i][j];
phi_total[j] += phi[i][j];
}
}
}
return S2_total;
}
} // namespace
namespace primecount {
/// Calculate the number of primes below x using the
/// Lagarias-Miller-Odlyzko algorithm.
/// Run time: O(x^(2/3)) operations, O(x^(1/3) * log log x) space.
///
int64_t pi_deleglise_rivat_parallel1(int64_t x, int threads)
{
if (x < 2)
return 0;
double beta = 3.0;
double alpha = max(1.0, log(log((double) x)) * beta);
int64_t x13 = iroot<3>(x);
int64_t y = (int64_t)(x13 * alpha);
int64_t z = x / (int64_t) (x13 * sqrt(alpha));
vector<int32_t> mu = make_moebius(y);
vector<int32_t> lpf = make_least_prime_factor(y);
vector<int32_t> primes;
primes.push_back(0);
primesieve::generate_primes(y, &primes);
int64_t pi_y = primes.size() - 1;
int64_t c = min<int64_t>(PhiTiny::MAX_A, pi_y);
int64_t s1 = S1(x, y, c, primes, lpf , mu);
int64_t s2 = S2(x, y, z, pi_y, c, primes, lpf , mu, threads);
int64_t p2 = P2(x, y, threads);
int64_t phi = s1 + s2;
int64_t sum = phi + pi_y - 1 - p2;
return sum;
}
} // namespace primecount
<commit_msg>Update pi_deleglise_rivat_parallel1.cpp<commit_after>///
/// @file pi_deleglise_rivat_parallel1.cpp
/// @brief Parallel implementation of the Lagarias-Miller-Odlyzko
/// prime counting algorithm with the improvements of Deleglise
/// and Rivat. This implementation is based on
/// pi_deleglise_rivat1.cpp and the paper: Tomás Oliveira e
/// Silva, Computing pi(x): the combinatorial method, Revista
/// do DETUA, vol. 4, no. 6, March 2006, pp. 759-768.
///
/// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <primecount-internal.hpp>
#include <primesieve.hpp>
#include <pmath.hpp>
#include <pi_bsearch.hpp>
#include <PhiTiny.hpp>
#include <tos_counters.hpp>
#include <utils.hpp>
#include <stdint.h>
#include <algorithm>
#include <vector>
#ifdef _OPENMP
#include <omp.h>
#endif
using namespace std;
namespace {
/// For each prime calculate its first multiple >= low.
template <typename T1, typename T2>
void initialize_next_multiples(T1* next, T2& primes, int64_t size, int64_t low)
{
next->reserve(size);
next->push_back(0);
for (int64_t b = 1; b < size; b++)
{
int64_t prime = primes[b];
int64_t next_multiple = ((low + prime - 1) / prime) * prime;
next->push_back(next_multiple);
}
}
template <typename T1, typename T2>
void cross_off(int64_t prime, int64_t low, int64_t high, int64_t& next_multiple, T1& sieve, T2& counters)
{
int64_t segment_size = sieve.size();
int64_t k = next_multiple + prime * (~next_multiple & 1);
for (; k < high; k += prime * 2)
{
if (sieve[k - low])
{
sieve[k - low] = 0;
cnt_update(counters, k - low, segment_size);
}
}
next_multiple = k;
}
/// Compute the S2 contribution for the interval
/// [low_process, low_process + segments * segment_size[.
/// The missing special leaf contributions for the interval
/// [1, low_process[ are later reconstructed and added in
/// the calling (parent) S2 function.
///
int64_t S2_thread(int64_t x,
int64_t y,
int64_t c,
int64_t pi_sqrty,
int64_t pi_y,
int64_t segment_size,
int64_t segments_per_thread,
int64_t thread_num,
int64_t low,
int64_t limit,
vector<int32_t>& pi,
vector<int32_t>& primes,
vector<int32_t>& lpf,
vector<int32_t>& mu,
vector<int64_t>& mu_sum,
vector<int64_t>& phi,
vector<int32_t>& min_trivial_leaves,
vector<int32_t>& min_easy_leaves)
{
low += segment_size * segments_per_thread * thread_num;
limit = min(low + segment_size * segments_per_thread, limit);
int64_t size = pi[min(isqrt(x / low), y)] + 1;
int64_t S2_thread = 0;
if (c >= size - 1)
return 0;
vector<char> sieve(segment_size);
vector<int32_t> counters(segment_size);
vector<int64_t> next;
initialize_next_multiples(&next, primes, size, low);
phi.resize(size, 0);
mu_sum.resize(size, 0);
// Process the segments corresponding to the current thread
for (; low < limit; low += segment_size)
{
fill(sieve.begin(), sieve.end(), 1);
// Current segment = interval [low, high[
int64_t high = min(low + segment_size, limit);
int64_t b = 1;
for (; b <= c; b++)
{
int64_t k = next[b];
for (int64_t prime = primes[b]; k < high; k += prime)
sieve[k - low] = 0;
next[b] = k;
}
// Initialize special tree data structure from sieve
cnt_finit(sieve, counters, segment_size);
// For c + 1 <= b < pi_sqrty
// Find all special leaves: n = primes[b] * m, with mu[m] != 0 and primes[b] < lpf[m]
// which satisfy: low <= (x / n) < high
for (; b < min(pi_sqrty, size); b++)
{
int64_t prime = primes[b];
int64_t min_m = max(x / (prime * high), y / prime);
int64_t max_m = min(x / (prime * low), y);
if (prime >= max_m)
goto next_segment;
for (int64_t m = max_m; m > min_m; m--)
{
if (mu[m] != 0 && prime < lpf[m])
{
int64_t n = prime * m;
int64_t count = cnt_query(counters, (x / n) - low);
int64_t phi_xn = phi[b] + count;
S2_thread -= mu[m] * phi_xn;
mu_sum[b] -= mu[m];
}
}
phi[b] += cnt_query(counters, (high - 1) - low);
cross_off(prime, low, high, next[b], sieve, counters);
}
// For pi_sqrty <= b < pi_y
// Find all special leaves: n = primes[b] * primes[l]
// which satisfy: low <= (x / n) < high
for (; b < pi_y; b++)
{
int64_t prime = primes[b];
int64_t l = pi[min(x / (prime * low), y)];
int64_t min_m = min(y, max(x / (prime * high), y / prime));
int64_t min_hard_leaf = pi[max(min_m, prime)];
int64_t min_trivial_leaf = max<int64_t>(min_hard_leaf, min_trivial_leaves[b]);
int64_t min_easy_leaf = max<int64_t>(min_hard_leaf, min_easy_leaves[b]);
if (prime >= primes[l])
goto next_segment;
// For max(x / primes[b]^2, primes[b]) < primes[l] <= y
// Find all trivial leaves which satisfy:
// phi(x / (primes[b] * primes[l]), b - 1) = 1
if (l > min_trivial_leaf)
{
S2_thread += l - min_trivial_leaf;
l = min_trivial_leaf;
}
// For max(z / primes[b], primes[b]) < primes[l] <= max(x / primes[b]^2, y)
// Find all easy leaves: n = primes[b] * primes[l]
// which satisfy x / n <= y such that:
// phi(x / n, b - 1) = pi[x / n] - b + 2
for (; l > min_easy_leaf; l--)
{
int64_t n = prime * primes[l];
int64_t xn = x / n;
S2_thread += pi[xn] - b + 2;
}
// For max(x / (prime * high), prime) < primes[l] <= max(z / primes[b], primes[b])
// Find all hard leaves: n = primes[b] * primes[l]
// which satisfy: low <= (x / n) < high
for (; l > min_hard_leaf; l--)
{
int64_t n = prime * primes[l];
int64_t xn = x / n;
int64_t count = cnt_query(counters, xn - low);
int64_t phi_xn = phi[b] + count;
S2_thread += phi_xn;
mu_sum[b]++;
}
phi[b] += cnt_query(counters, (high - 1) - low);
cross_off(prime, low, high, next[b], sieve, counters);
}
next_segment:;
}
return S2_thread;
}
/// Calculate the contribution of the special leaves.
/// This is a parallel implementation with advanced load balancing.
/// As most special leaves tend to be in the first segments we
/// start off with a small segment size and few segments
/// per thread, after each iteration we dynamically increase
/// the segment size and the segments per thread.
/// @pre y > 0 && c > 1
///
int64_t S2(int64_t x,
int64_t y,
int64_t z,
int64_t pi_y,
int64_t c,
vector<int32_t>& primes,
vector<int32_t>& lpf,
vector<int32_t>& mu,
int threads)
{
threads = validate_threads(threads);
int64_t S2_total = 0;
int64_t low = 1;
int64_t limit = x / y + 1;
int64_t sqrt_limit = isqrt(limit);
int64_t logx = max(1, ilog(x));
int64_t min_segment_size = 1 << 6;
int64_t segment_size = next_power_of_2(sqrt_limit / (logx * threads));
int64_t segments_per_thread = 1;
int64_t pi_sqrty = pi_bsearch(primes, isqrt(y));
vector<int32_t> pi = make_pi(y);
vector<int32_t> min_trivial_leaves(primes.size());
vector<int32_t> min_easy_leaves(primes.size());
vector<int64_t> phi_total(primes.size(), 0);
segment_size = max(segment_size, min_segment_size);
for (size_t i = 1; i < primes.size(); i++)
{
int64_t prime = primes[i];
min_trivial_leaves[i] = pi[min(y, max(x / (prime * prime), prime))];
min_easy_leaves[i] = pi[min(y, max(z / prime, prime))];
}
while (low < limit)
{
int64_t segments = (limit - low + segment_size - 1) / segment_size;
threads = in_between(1, threads, segments);
segments_per_thread = in_between(1, segments_per_thread, (segments + threads - 1) / threads);
double seconds = get_wtime();
vector<vector<int64_t> > phi(threads);
vector<vector<int64_t> > mu_sum(threads);
#pragma omp parallel for num_threads(threads) reduction(+: S2_total)
for (int i = 0; i < threads; i++)
S2_total += S2_thread(x, y, c, pi_sqrty, pi_y, segment_size, segments_per_thread,
i, low, limit, pi, primes, lpf, mu, mu_sum[i], phi[i], min_trivial_leaves, min_easy_leaves);
seconds = get_wtime() - seconds;
low += segments_per_thread * threads * segment_size;
// Dynamically increase segment_size or segments_per_thread
// if the running time is less than a certain threshold.
// We start off with a small segment size and few segments
// per thread as most special leaves are in the first segments
// whereas later on there are very few special leaves.
//
if (low > sqrt_limit && seconds < 10)
{
if (segment_size < sqrt_limit)
segment_size <<= 1;
else
segments_per_thread *= 2;
}
// Once all threads have finished reconstruct and add the
// missing contribution of all special leaves. This must
// be done in order as each thread (i) requires the sum of
// the phi values from the previous threads.
//
for (int i = 0; i < threads; i++)
{
for (size_t j = 1; j < phi[i].size(); j++)
{
S2_total += phi_total[j] * mu_sum[i][j];
phi_total[j] += phi[i][j];
}
}
}
return S2_total;
}
} // namespace
namespace primecount {
/// Calculate the number of primes below x using the
/// Deleglise-Rivat algorithm.
/// Run time: O(x^(2/3) / log x) operations, O(x^(1/3) * log log x) space.
///
int64_t pi_deleglise_rivat_parallel1(int64_t x, int threads)
{
if (x < 2)
return 0;
double beta = 3.0;
double alpha = max(1.0, log(log((double) x)) * beta);
int64_t x13 = iroot<3>(x);
int64_t y = (int64_t)(x13 * alpha);
int64_t z = x / (int64_t) (x13 * sqrt(alpha));
vector<int32_t> mu = make_moebius(y);
vector<int32_t> lpf = make_least_prime_factor(y);
vector<int32_t> primes;
primes.push_back(0);
primesieve::generate_primes(y, &primes);
int64_t pi_y = primes.size() - 1;
int64_t c = min<int64_t>(PhiTiny::MAX_A, pi_y);
int64_t s1 = S1(x, y, c, primes, lpf , mu);
int64_t s2 = S2(x, y, z, pi_y, c, primes, lpf , mu, threads);
int64_t p2 = P2(x, y, threads);
int64_t phi = s1 + s2;
int64_t sum = phi + pi_y - 1 - p2;
return sum;
}
} // namespace primecount
<|endoftext|>
|
<commit_before>// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/renderer/atom_renderer_client.h"
#include <string>
#include <vector>
#include "atom/common/api/api_messages.h"
#include "atom/common/api/atom_bindings.h"
#include "atom/common/api/event_emitter_caller.h"
#include "atom/common/color_util.h"
#include "atom/common/native_mate_converters/value_converter.h"
#include "atom/common/node_bindings.h"
#include "atom/common/options_switches.h"
#include "atom/renderer/atom_render_view_observer.h"
#include "atom/renderer/content_settings_observer.h"
#include "atom/renderer/guest_view_container.h"
#include "atom/renderer/node_array_buffer_bridge.h"
#include "atom/renderer/preferences_manager.h"
#include "base/command_line.h"
#include "chrome/renderer/media/chrome_key_systems.h"
#include "chrome/renderer/pepper/pepper_helper.h"
#include "chrome/renderer/printing/print_web_view_helper.h"
#include "chrome/renderer/tts_dispatcher.h"
#include "content/public/common/content_constants.h"
#include "content/public/renderer/render_frame.h"
#include "content/public/renderer/render_frame_observer.h"
#include "content/public/renderer/render_thread.h"
#include "content/public/renderer/render_view.h"
#include "ipc/ipc_message_macros.h"
#include "native_mate/dictionary.h"
#include "third_party/WebKit/public/web/WebCustomElement.h"
#include "third_party/WebKit/public/web/WebDocument.h"
#include "third_party/WebKit/public/web/WebFrameWidget.h"
#include "third_party/WebKit/public/web/WebKit.h"
#include "third_party/WebKit/public/web/WebLocalFrame.h"
#include "third_party/WebKit/public/web/WebPluginParams.h"
#include "third_party/WebKit/public/web/WebRuntimeFeatures.h"
#include "third_party/WebKit/public/web/WebScriptSource.h"
#include "third_party/WebKit/public/web/WebSecurityPolicy.h"
#include "third_party/WebKit/public/web/WebView.h"
#if defined(OS_MACOSX)
#include "base/mac/mac_util.h"
#include "base/strings/sys_string_conversions.h"
#endif
#if defined(OS_WIN)
#include <shlobj.h>
#endif
#include "atom/common/node_includes.h"
namespace atom {
namespace {
// Helper class to forward the messages to the client.
class AtomRenderFrameObserver : public content::RenderFrameObserver {
public:
AtomRenderFrameObserver(content::RenderFrame* frame,
AtomRendererClient* renderer_client,
bool isolated_world)
: content::RenderFrameObserver(frame),
render_frame_(frame),
isolated_world_(isolated_world),
main_context_created_(false),
isolated_context_created_(false),
renderer_client_(renderer_client) {}
// content::RenderFrameObserver:
void DidClearWindowObject() override {
renderer_client_->DidClearWindowObject(render_frame_);
}
void CreateIsolatedWorldContext() {
blink::WebScriptSource source("void 0");
render_frame_->GetWebFrame()->executeScriptInIsolatedWorld(
1,
&source,
1,
1,
nullptr);
}
bool IsMainWorld(int world_id) {
return world_id == 0;
}
bool IsIsolatedWorld(int world_id) {
return world_id == 1;
}
void DidCreateScriptContext(v8::Handle<v8::Context> context,
int extension_group,
int world_id) override {
if (!main_context_created_ && IsMainWorld(world_id)) {
main_context_created_ = true;
if (isolated_world_) {
CreateIsolatedWorldContext();
} else {
renderer_client_->DidCreateScriptContext(context, render_frame_);
}
}
if (isolated_world_ && !isolated_context_created_
&& IsIsolatedWorld(world_id)) {
isolated_context_created_ = true;
renderer_client_->DidCreateScriptContext(context, render_frame_);
}
}
void WillReleaseScriptContext(v8::Local<v8::Context> context,
int world_id) override {
if (isolated_world_) {
if (IsIsolatedWorld(world_id))
renderer_client_->WillReleaseScriptContext(context, render_frame_);
} else if (IsMainWorld(world_id)) {
renderer_client_->WillReleaseScriptContext(context, render_frame_);
}
}
void OnDestruct() override {
delete this;
}
private:
content::RenderFrame* render_frame_;
bool isolated_world_;
bool main_context_created_;
bool isolated_context_created_;
AtomRendererClient* renderer_client_;
DISALLOW_COPY_AND_ASSIGN(AtomRenderFrameObserver);
};
v8::Local<v8::Value> GetRenderProcessPreferences(
const PreferencesManager* preferences_manager, v8::Isolate* isolate) {
if (preferences_manager->preferences())
return mate::ConvertToV8(isolate, *preferences_manager->preferences());
else
return v8::Null(isolate);
}
void AddRenderBindings(v8::Isolate* isolate,
v8::Local<v8::Object> process,
const PreferencesManager* preferences_manager) {
mate::Dictionary dict(isolate, process);
dict.SetMethod(
"getRenderProcessPreferences",
base::Bind(GetRenderProcessPreferences, preferences_manager));
}
bool IsDevToolsExtension(content::RenderFrame* render_frame) {
return static_cast<GURL>(render_frame->GetWebFrame()->document().url())
.SchemeIs("chrome-extension");
}
std::vector<std::string> ParseSchemesCLISwitch(const char* switch_name) {
base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
std::string custom_schemes = command_line->GetSwitchValueASCII(switch_name);
return base::SplitString(
custom_schemes, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY);
}
} // namespace
AtomRendererClient::AtomRendererClient()
: node_bindings_(NodeBindings::Create(false)),
atom_bindings_(new AtomBindings) {
// Parse --standard-schemes=scheme1,scheme2
std::vector<std::string> standard_schemes_list =
ParseSchemesCLISwitch(switches::kStandardSchemes);
for (const std::string& scheme : standard_schemes_list)
url::AddStandardScheme(scheme.c_str(), url::SCHEME_WITHOUT_PORT);
}
AtomRendererClient::~AtomRendererClient() {
}
void AtomRendererClient::RenderThreadStarted() {
blink::WebCustomElement::addEmbedderCustomElementName("webview");
blink::WebCustomElement::addEmbedderCustomElementName("browserplugin");
OverrideNodeArrayBuffer();
preferences_manager_.reset(new PreferencesManager);
#if defined(OS_WIN)
// Set ApplicationUserModelID in renderer process.
base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
base::string16 app_id =
command_line->GetSwitchValueNative(switches::kAppUserModelId);
if (!app_id.empty()) {
SetCurrentProcessExplicitAppUserModelID(app_id.c_str());
}
#endif
#if defined(OS_MACOSX)
// Disable rubber banding by default.
base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
if (!command_line->HasSwitch(switches::kScrollBounce)) {
base::ScopedCFTypeRef<CFStringRef> key(
base::SysUTF8ToCFStringRef("NSScrollViewRubberbanding"));
base::ScopedCFTypeRef<CFStringRef> value(
base::SysUTF8ToCFStringRef("false"));
CFPreferencesSetAppValue(key, value, kCFPreferencesCurrentApplication);
CFPreferencesAppSynchronize(kCFPreferencesCurrentApplication);
}
#endif
}
void AtomRendererClient::RenderFrameCreated(
content::RenderFrame* render_frame) {
new PepperHelper(render_frame);
bool isolated_world = base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kIsolatedWorld);
new AtomRenderFrameObserver(render_frame, this, isolated_world);
new ContentSettingsObserver(render_frame);
// Allow file scheme to handle service worker by default.
// FIXME(zcbenz): Can this be moved elsewhere?
blink::WebSecurityPolicy::registerURLSchemeAsAllowingServiceWorkers("file");
// Parse --secure-schemes=scheme1,scheme2
std::vector<std::string> secure_schemes_list =
ParseSchemesCLISwitch(switches::kSecureSchemes);
for (const std::string& secure_scheme : secure_schemes_list)
blink::WebSecurityPolicy::registerURLSchemeAsSecure(
blink::WebString::fromUTF8(secure_scheme));
}
void AtomRendererClient::RenderViewCreated(content::RenderView* render_view) {
new printing::PrintWebViewHelper(render_view);
new AtomRenderViewObserver(render_view, this);
blink::WebFrameWidget* web_frame_widget = render_view->GetWebFrameWidget();
if (!web_frame_widget)
return;
base::CommandLine* cmd = base::CommandLine::ForCurrentProcess();
if (cmd->HasSwitch(switches::kGuestInstanceID)) { // webview.
web_frame_widget->setBaseBackgroundColor(SK_ColorTRANSPARENT);
} else { // normal window.
// If backgroundColor is specified then use it.
std::string name = cmd->GetSwitchValueASCII(switches::kBackgroundColor);
// Otherwise use white background.
SkColor color = name.empty() ? SK_ColorWHITE : ParseHexColor(name);
web_frame_widget->setBaseBackgroundColor(color);
}
}
void AtomRendererClient::DidClearWindowObject(
content::RenderFrame* render_frame) {
// Make sure every page will get a script context created.
render_frame->GetWebFrame()->executeScript(blink::WebScriptSource("void 0"));
}
void AtomRendererClient::RunScriptsAtDocumentStart(
content::RenderFrame* render_frame) {
// Inform the document start pharse.
node::Environment* env = node_bindings_->uv_env();
if (env) {
v8::HandleScope handle_scope(env->isolate());
mate::EmitEvent(env->isolate(), env->process_object(), "document-start");
}
}
void AtomRendererClient::RunScriptsAtDocumentEnd(
content::RenderFrame* render_frame) {
// Inform the document end pharse.
node::Environment* env = node_bindings_->uv_env();
if (env) {
v8::HandleScope handle_scope(env->isolate());
mate::EmitEvent(env->isolate(), env->process_object(), "document-end");
}
}
blink::WebSpeechSynthesizer* AtomRendererClient::OverrideSpeechSynthesizer(
blink::WebSpeechSynthesizerClient* client) {
return new TtsDispatcher(client);
}
bool AtomRendererClient::OverrideCreatePlugin(
content::RenderFrame* render_frame,
blink::WebLocalFrame* frame,
const blink::WebPluginParams& params,
blink::WebPlugin** plugin) {
base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
if (params.mimeType.utf8() == content::kBrowserPluginMimeType ||
command_line->HasSwitch(switches::kEnablePlugins))
return false;
*plugin = nullptr;
return true;
}
void AtomRendererClient::DidCreateScriptContext(
v8::Handle<v8::Context> context, content::RenderFrame* render_frame) {
// Only allow node integration for the main frame, unless it is a devtools
// extension page.
if (!render_frame->IsMainFrame() && !IsDevToolsExtension(render_frame))
return;
// Whether the node binding has been initialized.
bool first_time = node_bindings_->uv_env() == nullptr;
// Prepare the node bindings.
if (first_time) {
node_bindings_->Initialize();
node_bindings_->PrepareMessageLoop();
}
// Setup node environment for each window.
node::Environment* env = node_bindings_->CreateEnvironment(context);
// Add Electron extended APIs.
atom_bindings_->BindTo(env->isolate(), env->process_object());
AddRenderBindings(env->isolate(), env->process_object(),
preferences_manager_.get());
// Load everything.
node_bindings_->LoadEnvironment(env);
if (first_time) {
// Make uv loop being wrapped by window context.
node_bindings_->set_uv_env(env);
// Give the node loop a run to make sure everything is ready.
node_bindings_->RunMessageLoop();
}
}
void AtomRendererClient::WillReleaseScriptContext(
v8::Handle<v8::Context> context, content::RenderFrame* render_frame) {
// Only allow node integration for the main frame, unless it is a devtools
// extension page.
if (!render_frame->IsMainFrame() && !IsDevToolsExtension(render_frame))
return;
node::Environment* env = node::Environment::GetCurrent(context);
if (env)
mate::EmitEvent(env->isolate(), env->process_object(), "exit");
}
bool AtomRendererClient::ShouldFork(blink::WebLocalFrame* frame,
const GURL& url,
const std::string& http_method,
bool is_initial_navigation,
bool is_server_redirect,
bool* send_referrer) {
// Handle all the navigations and reloads in browser.
// FIXME We only support GET here because http method will be ignored when
// the OpenURLFromTab is triggered, which means form posting would not work,
// we should solve this by patching Chromium in future.
*send_referrer = true;
return http_method == "GET";
}
content::BrowserPluginDelegate* AtomRendererClient::CreateBrowserPluginDelegate(
content::RenderFrame* render_frame,
const std::string& mime_type,
const GURL& original_url) {
if (mime_type == content::kBrowserPluginMimeType) {
return new GuestViewContainer(render_frame);
} else {
return nullptr;
}
}
void AtomRendererClient::AddSupportedKeySystems(
std::vector<std::unique_ptr<::media::KeySystemProperties>>* key_systems) {
AddChromeKeySystems(key_systems);
}
} // namespace atom
<commit_msg>Add world id constants<commit_after>// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/renderer/atom_renderer_client.h"
#include <string>
#include <vector>
#include "atom/common/api/api_messages.h"
#include "atom/common/api/atom_bindings.h"
#include "atom/common/api/event_emitter_caller.h"
#include "atom/common/color_util.h"
#include "atom/common/native_mate_converters/value_converter.h"
#include "atom/common/node_bindings.h"
#include "atom/common/options_switches.h"
#include "atom/renderer/atom_render_view_observer.h"
#include "atom/renderer/content_settings_observer.h"
#include "atom/renderer/guest_view_container.h"
#include "atom/renderer/node_array_buffer_bridge.h"
#include "atom/renderer/preferences_manager.h"
#include "base/command_line.h"
#include "chrome/renderer/media/chrome_key_systems.h"
#include "chrome/renderer/pepper/pepper_helper.h"
#include "chrome/renderer/printing/print_web_view_helper.h"
#include "chrome/renderer/tts_dispatcher.h"
#include "content/public/common/content_constants.h"
#include "content/public/renderer/render_frame.h"
#include "content/public/renderer/render_frame_observer.h"
#include "content/public/renderer/render_thread.h"
#include "content/public/renderer/render_view.h"
#include "ipc/ipc_message_macros.h"
#include "native_mate/dictionary.h"
#include "third_party/WebKit/public/web/WebCustomElement.h"
#include "third_party/WebKit/public/web/WebDocument.h"
#include "third_party/WebKit/public/web/WebFrameWidget.h"
#include "third_party/WebKit/public/web/WebKit.h"
#include "third_party/WebKit/public/web/WebLocalFrame.h"
#include "third_party/WebKit/public/web/WebPluginParams.h"
#include "third_party/WebKit/public/web/WebRuntimeFeatures.h"
#include "third_party/WebKit/public/web/WebScriptSource.h"
#include "third_party/WebKit/public/web/WebSecurityPolicy.h"
#include "third_party/WebKit/public/web/WebView.h"
#if defined(OS_MACOSX)
#include "base/mac/mac_util.h"
#include "base/strings/sys_string_conversions.h"
#endif
#if defined(OS_WIN)
#include <shlobj.h>
#endif
#include "atom/common/node_includes.h"
namespace atom {
namespace {
// Helper class to forward the messages to the client.
class AtomRenderFrameObserver : public content::RenderFrameObserver {
public:
AtomRenderFrameObserver(content::RenderFrame* frame,
AtomRendererClient* renderer_client,
bool isolated_world)
: content::RenderFrameObserver(frame),
render_frame_(frame),
isolated_world_(isolated_world),
main_context_created_(false),
isolated_context_created_(false),
renderer_client_(renderer_client) {}
// content::RenderFrameObserver:
void DidClearWindowObject() override {
renderer_client_->DidClearWindowObject(render_frame_);
}
void CreateIsolatedWorldContext() {
blink::WebScriptSource source("void 0");
render_frame_->GetWebFrame()->executeScriptInIsolatedWorld(
kIsolatedWorldId, &source, 1, 1);
}
bool IsMainWorld(int world_id) {
return world_id == kMainWorldId;
}
bool IsIsolatedWorld(int world_id) {
return world_id == kIsolatedWorldId;
}
void DidCreateScriptContext(v8::Handle<v8::Context> context,
int extension_group,
int world_id) override {
if (!main_context_created_ && IsMainWorld(world_id)) {
main_context_created_ = true;
if (isolated_world_) {
CreateIsolatedWorldContext();
} else {
renderer_client_->DidCreateScriptContext(context, render_frame_);
}
}
if (isolated_world_ && !isolated_context_created_
&& IsIsolatedWorld(world_id)) {
isolated_context_created_ = true;
renderer_client_->DidCreateScriptContext(context, render_frame_);
}
}
void WillReleaseScriptContext(v8::Local<v8::Context> context,
int world_id) override {
if (isolated_world_) {
if (IsIsolatedWorld(world_id))
renderer_client_->WillReleaseScriptContext(context, render_frame_);
} else if (IsMainWorld(world_id)) {
renderer_client_->WillReleaseScriptContext(context, render_frame_);
}
}
void OnDestruct() override {
delete this;
}
private:
content::RenderFrame* render_frame_;
bool isolated_world_;
bool main_context_created_;
bool isolated_context_created_;
AtomRendererClient* renderer_client_;
const int kMainWorldId = 0;
const int kIsolatedWorldId = 999;
DISALLOW_COPY_AND_ASSIGN(AtomRenderFrameObserver);
};
v8::Local<v8::Value> GetRenderProcessPreferences(
const PreferencesManager* preferences_manager, v8::Isolate* isolate) {
if (preferences_manager->preferences())
return mate::ConvertToV8(isolate, *preferences_manager->preferences());
else
return v8::Null(isolate);
}
void AddRenderBindings(v8::Isolate* isolate,
v8::Local<v8::Object> process,
const PreferencesManager* preferences_manager) {
mate::Dictionary dict(isolate, process);
dict.SetMethod(
"getRenderProcessPreferences",
base::Bind(GetRenderProcessPreferences, preferences_manager));
}
bool IsDevToolsExtension(content::RenderFrame* render_frame) {
return static_cast<GURL>(render_frame->GetWebFrame()->document().url())
.SchemeIs("chrome-extension");
}
std::vector<std::string> ParseSchemesCLISwitch(const char* switch_name) {
base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
std::string custom_schemes = command_line->GetSwitchValueASCII(switch_name);
return base::SplitString(
custom_schemes, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY);
}
} // namespace
AtomRendererClient::AtomRendererClient()
: node_bindings_(NodeBindings::Create(false)),
atom_bindings_(new AtomBindings) {
// Parse --standard-schemes=scheme1,scheme2
std::vector<std::string> standard_schemes_list =
ParseSchemesCLISwitch(switches::kStandardSchemes);
for (const std::string& scheme : standard_schemes_list)
url::AddStandardScheme(scheme.c_str(), url::SCHEME_WITHOUT_PORT);
}
AtomRendererClient::~AtomRendererClient() {
}
void AtomRendererClient::RenderThreadStarted() {
blink::WebCustomElement::addEmbedderCustomElementName("webview");
blink::WebCustomElement::addEmbedderCustomElementName("browserplugin");
OverrideNodeArrayBuffer();
preferences_manager_.reset(new PreferencesManager);
#if defined(OS_WIN)
// Set ApplicationUserModelID in renderer process.
base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
base::string16 app_id =
command_line->GetSwitchValueNative(switches::kAppUserModelId);
if (!app_id.empty()) {
SetCurrentProcessExplicitAppUserModelID(app_id.c_str());
}
#endif
#if defined(OS_MACOSX)
// Disable rubber banding by default.
base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
if (!command_line->HasSwitch(switches::kScrollBounce)) {
base::ScopedCFTypeRef<CFStringRef> key(
base::SysUTF8ToCFStringRef("NSScrollViewRubberbanding"));
base::ScopedCFTypeRef<CFStringRef> value(
base::SysUTF8ToCFStringRef("false"));
CFPreferencesSetAppValue(key, value, kCFPreferencesCurrentApplication);
CFPreferencesAppSynchronize(kCFPreferencesCurrentApplication);
}
#endif
}
void AtomRendererClient::RenderFrameCreated(
content::RenderFrame* render_frame) {
new PepperHelper(render_frame);
bool isolated_world = base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kIsolatedWorld);
new AtomRenderFrameObserver(render_frame, this, isolated_world);
new ContentSettingsObserver(render_frame);
// Allow file scheme to handle service worker by default.
// FIXME(zcbenz): Can this be moved elsewhere?
blink::WebSecurityPolicy::registerURLSchemeAsAllowingServiceWorkers("file");
// Parse --secure-schemes=scheme1,scheme2
std::vector<std::string> secure_schemes_list =
ParseSchemesCLISwitch(switches::kSecureSchemes);
for (const std::string& secure_scheme : secure_schemes_list)
blink::WebSecurityPolicy::registerURLSchemeAsSecure(
blink::WebString::fromUTF8(secure_scheme));
}
void AtomRendererClient::RenderViewCreated(content::RenderView* render_view) {
new printing::PrintWebViewHelper(render_view);
new AtomRenderViewObserver(render_view, this);
blink::WebFrameWidget* web_frame_widget = render_view->GetWebFrameWidget();
if (!web_frame_widget)
return;
base::CommandLine* cmd = base::CommandLine::ForCurrentProcess();
if (cmd->HasSwitch(switches::kGuestInstanceID)) { // webview.
web_frame_widget->setBaseBackgroundColor(SK_ColorTRANSPARENT);
} else { // normal window.
// If backgroundColor is specified then use it.
std::string name = cmd->GetSwitchValueASCII(switches::kBackgroundColor);
// Otherwise use white background.
SkColor color = name.empty() ? SK_ColorWHITE : ParseHexColor(name);
web_frame_widget->setBaseBackgroundColor(color);
}
}
void AtomRendererClient::DidClearWindowObject(
content::RenderFrame* render_frame) {
// Make sure every page will get a script context created.
render_frame->GetWebFrame()->executeScript(blink::WebScriptSource("void 0"));
}
void AtomRendererClient::RunScriptsAtDocumentStart(
content::RenderFrame* render_frame) {
// Inform the document start pharse.
node::Environment* env = node_bindings_->uv_env();
if (env) {
v8::HandleScope handle_scope(env->isolate());
mate::EmitEvent(env->isolate(), env->process_object(), "document-start");
}
}
void AtomRendererClient::RunScriptsAtDocumentEnd(
content::RenderFrame* render_frame) {
// Inform the document end pharse.
node::Environment* env = node_bindings_->uv_env();
if (env) {
v8::HandleScope handle_scope(env->isolate());
mate::EmitEvent(env->isolate(), env->process_object(), "document-end");
}
}
blink::WebSpeechSynthesizer* AtomRendererClient::OverrideSpeechSynthesizer(
blink::WebSpeechSynthesizerClient* client) {
return new TtsDispatcher(client);
}
bool AtomRendererClient::OverrideCreatePlugin(
content::RenderFrame* render_frame,
blink::WebLocalFrame* frame,
const blink::WebPluginParams& params,
blink::WebPlugin** plugin) {
base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
if (params.mimeType.utf8() == content::kBrowserPluginMimeType ||
command_line->HasSwitch(switches::kEnablePlugins))
return false;
*plugin = nullptr;
return true;
}
void AtomRendererClient::DidCreateScriptContext(
v8::Handle<v8::Context> context, content::RenderFrame* render_frame) {
// Only allow node integration for the main frame, unless it is a devtools
// extension page.
if (!render_frame->IsMainFrame() && !IsDevToolsExtension(render_frame))
return;
// Whether the node binding has been initialized.
bool first_time = node_bindings_->uv_env() == nullptr;
// Prepare the node bindings.
if (first_time) {
node_bindings_->Initialize();
node_bindings_->PrepareMessageLoop();
}
// Setup node environment for each window.
node::Environment* env = node_bindings_->CreateEnvironment(context);
// Add Electron extended APIs.
atom_bindings_->BindTo(env->isolate(), env->process_object());
AddRenderBindings(env->isolate(), env->process_object(),
preferences_manager_.get());
// Load everything.
node_bindings_->LoadEnvironment(env);
if (first_time) {
// Make uv loop being wrapped by window context.
node_bindings_->set_uv_env(env);
// Give the node loop a run to make sure everything is ready.
node_bindings_->RunMessageLoop();
}
}
void AtomRendererClient::WillReleaseScriptContext(
v8::Handle<v8::Context> context, content::RenderFrame* render_frame) {
// Only allow node integration for the main frame, unless it is a devtools
// extension page.
if (!render_frame->IsMainFrame() && !IsDevToolsExtension(render_frame))
return;
node::Environment* env = node::Environment::GetCurrent(context);
if (env)
mate::EmitEvent(env->isolate(), env->process_object(), "exit");
}
bool AtomRendererClient::ShouldFork(blink::WebLocalFrame* frame,
const GURL& url,
const std::string& http_method,
bool is_initial_navigation,
bool is_server_redirect,
bool* send_referrer) {
// Handle all the navigations and reloads in browser.
// FIXME We only support GET here because http method will be ignored when
// the OpenURLFromTab is triggered, which means form posting would not work,
// we should solve this by patching Chromium in future.
*send_referrer = true;
return http_method == "GET";
}
content::BrowserPluginDelegate* AtomRendererClient::CreateBrowserPluginDelegate(
content::RenderFrame* render_frame,
const std::string& mime_type,
const GURL& original_url) {
if (mime_type == content::kBrowserPluginMimeType) {
return new GuestViewContainer(render_frame);
} else {
return nullptr;
}
}
void AtomRendererClient::AddSupportedKeySystems(
std::vector<std::unique_ptr<::media::KeySystemProperties>>* key_systems) {
AddChromeKeySystems(key_systems);
}
} // namespace atom
<|endoftext|>
|
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#include <stdio.h>
#include <avmedia/mediawindow.hxx>
#include "mediawindow_impl.hxx"
#include "mediamisc.hxx"
#include "mediawindow.hrc"
#include <tools/urlobj.hxx>
#include <vcl/msgbox.hxx>
#include <unotools/pathoptions.hxx>
#include <sfx2/filedlghelper.hxx>
#include <comphelper/processfactory.hxx>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/media/XManager.hpp>
#include "com/sun/star/ui/dialogs/TemplateDescription.hpp"
#define AVMEDIA_FRAMEGRABBER_DEFAULTFRAME_MEDIATIME 3.0
using namespace ::com::sun::star;
namespace avmedia {
// ---------------
// - MediaWindow -
// ---------------
MediaWindow::MediaWindow( Window* parent, bool bInternalMediaControl ) :
mpImpl( new priv::MediaWindowImpl( parent, this, bInternalMediaControl ) )
{
mpImpl->Show();
}
// -------------------------------------------------------------------------
MediaWindow::~MediaWindow()
{
mpImpl->cleanUp();
delete mpImpl;
mpImpl = NULL;
}
// -------------------------------------------------------------------------
void MediaWindow::setURL( const ::rtl::OUString& rURL )
{
if( mpImpl )
mpImpl->setURL( rURL );
}
// -------------------------------------------------------------------------
const ::rtl::OUString& MediaWindow::getURL() const
{
return mpImpl->getURL();
}
// -------------------------------------------------------------------------
bool MediaWindow::isValid() const
{
return( mpImpl != NULL && mpImpl->isValid() );
}
// -------------------------------------------------------------------------
void MediaWindow::MouseMove( const MouseEvent& /* rMEvt */ )
{
}
// ---------------------------------------------------------------------
void MediaWindow::MouseButtonDown( const MouseEvent& /* rMEvt */ )
{
}
// ---------------------------------------------------------------------
void MediaWindow::MouseButtonUp( const MouseEvent& /* rMEvt */ )
{
}
// -------------------------------------------------------------------------
void MediaWindow::KeyInput( const KeyEvent& /* rKEvt */ )
{
}
// -------------------------------------------------------------------------
void MediaWindow::KeyUp( const KeyEvent& /* rKEvt */ )
{
}
// -------------------------------------------------------------------------
void MediaWindow::Command( const CommandEvent& /* rCEvt */ )
{
}
// -------------------------------------------------------------------------
sal_Int8 MediaWindow::AcceptDrop( const AcceptDropEvent& /* rEvt */ )
{
return 0;
}
// -------------------------------------------------------------------------
sal_Int8 MediaWindow::ExecuteDrop( const ExecuteDropEvent& /* rEvt */ )
{
return 0;
}
// -------------------------------------------------------------------------
void MediaWindow::StartDrag( sal_Int8 /* nAction */, const Point& /* rPosPixel */ )
{
}
// -------------------------------------------------------------------------
bool MediaWindow::hasPreferredSize() const
{
return( mpImpl != NULL && mpImpl->hasPreferredSize() );
}
// -------------------------------------------------------------------------
Size MediaWindow::getPreferredSize() const
{
return mpImpl->getPreferredSize();
}
// -------------------------------------------------------------------------
void MediaWindow::setPosSize( const Rectangle& rNewRect )
{
if( mpImpl )
{
mpImpl->setPosSize( rNewRect );
}
}
// -------------------------------------------------------------------------
Rectangle MediaWindow::getPosSize() const
{
return Rectangle( mpImpl->GetPosPixel(), mpImpl->GetSizePixel() );
}
// -------------------------------------------------------------------------
void MediaWindow::setPointer( const Pointer& rPointer )
{
if( mpImpl )
mpImpl->setPointer( rPointer );
}
// -------------------------------------------------------------------------
const Pointer& MediaWindow::getPointer() const
{
return mpImpl->getPointer();
}
// -------------------------------------------------------------------------
bool MediaWindow::setZoom( ::com::sun::star::media::ZoomLevel eLevel )
{
return( mpImpl != NULL && mpImpl->setZoom( eLevel ) );
}
// -------------------------------------------------------------------------
::com::sun::star::media::ZoomLevel MediaWindow::getZoom() const
{
return mpImpl->getZoom();
}
// -------------------------------------------------------------------------
bool MediaWindow::start()
{
return( mpImpl != NULL && mpImpl->start() );
}
// -------------------------------------------------------------------------
void MediaWindow::stop()
{
if( mpImpl )
mpImpl->stop();
}
// -------------------------------------------------------------------------
bool MediaWindow::isPlaying() const
{
return( mpImpl != NULL && mpImpl->isPlaying() );
}
// -------------------------------------------------------------------------
double MediaWindow::getDuration() const
{
return mpImpl->getDuration();
}
// -------------------------------------------------------------------------
void MediaWindow::setMediaTime( double fTime )
{
if( mpImpl )
mpImpl->setMediaTime( fTime );
}
// -------------------------------------------------------------------------
double MediaWindow::getMediaTime() const
{
return mpImpl->getMediaTime();
}
// -------------------------------------------------------------------------
void MediaWindow::setStopTime( double fTime )
{
if( mpImpl )
mpImpl->setStopTime( fTime );
}
// -------------------------------------------------------------------------
double MediaWindow::getStopTime() const
{
return mpImpl->getStopTime();
}
// -------------------------------------------------------------------------
void MediaWindow::setRate( double fRate )
{
if( mpImpl )
mpImpl->setRate( fRate );
}
// -------------------------------------------------------------------------
double MediaWindow::getRate() const
{
return mpImpl->getRate();
}
// -------------------------------------------------------------------------
void MediaWindow::setPlaybackLoop( bool bSet )
{
if( mpImpl )
mpImpl->setPlaybackLoop( bSet );
}
// -------------------------------------------------------------------------
bool MediaWindow::isPlaybackLoop() const
{
return mpImpl->isPlaybackLoop();
}
// -------------------------------------------------------------------------
void MediaWindow::setMute( bool bSet )
{
if( mpImpl )
mpImpl->setMute( bSet );
}
// -------------------------------------------------------------------------
bool MediaWindow::isMute() const
{
return mpImpl->isMute();
}
// -------------------------------------------------------------------------
void MediaWindow::updateMediaItem( MediaItem& rItem ) const
{
if( mpImpl )
mpImpl->updateMediaItem( rItem );
}
// -------------------------------------------------------------------------
void MediaWindow::executeMediaItem( const MediaItem& rItem )
{
if( mpImpl )
mpImpl->executeMediaItem( rItem );
}
// -------------------------------------------------------------------------
void MediaWindow::show()
{
if( mpImpl )
mpImpl->Show();
}
// -------------------------------------------------------------------------
void MediaWindow::hide()
{
if( mpImpl )
mpImpl->Hide();
}
// -------------------------------------------------------------------------
void MediaWindow::enable()
{
if( mpImpl )
mpImpl->Enable();
}
// -------------------------------------------------------------------------
void MediaWindow::disable()
{
if( mpImpl )
mpImpl->Disable();
}
// -------------------------------------------------------------------------
Window* MediaWindow::getWindow() const
{
return mpImpl;
}
// -------------------------------------------------------------------------
void MediaWindow::getMediaFilters( FilterNameVector& rFilterNameVector )
{
static const char* pFilters[] = { "AIF Audio", "aif;aiff",
"AU Audio", "au",
"AVI", "avi",
"CD Audio", "cda",
"FLAC Audio", "flac",
"Matroska Media", "mkv",
"MIDI Audio", "mid;midi",
"MPEG Audio", "mp2;mp3;mpa",
"MPEG Video", "mpg;mpeg;mpv;mp4",
"Ogg bitstream", "ogg",
"Quicktime Video", "mov",
"Vivo Video", "viv",
"WAVE Audio", "wav",
"WebM Video", "webm" };
for( size_t i = 0; i < SAL_N_ELEMENT(pFIlters); i += 2 )
{
rFilterNameVector.push_back( ::std::make_pair< ::rtl::OUString, ::rtl::OUString >(
::rtl::OUString::createFromAscii(pFilters[i]),
::rtl::OUString::createFromAscii(pFilters[i+1]) ) );
}
}
// -------------------------------------------------------------------------
bool MediaWindow::executeMediaURLDialog( Window* /* pParent */, ::rtl::OUString& rURL, bool bInsertDialog )
{
::sfx2::FileDialogHelper aDlg( com::sun::star::ui::dialogs::TemplateDescription::FILEOPEN_SIMPLE, 0 );
static const ::rtl::OUString aWildcard( RTL_CONSTASCII_USTRINGPARAM( "*." ) );
FilterNameVector aFilters;
const ::rtl::OUString aSeparator( RTL_CONSTASCII_USTRINGPARAM( ";" ) );
::rtl::OUString aAllTypes;
aDlg.SetTitle( AVMEDIA_RESID( bInsertDialog ? AVMEDIA_STR_INSERTMEDIA_DLG : AVMEDIA_STR_OPENMEDIA_DLG ) );
getMediaFilters( aFilters );
unsigned int i;
for( i = 0; i < aFilters.size(); ++i )
{
for( sal_Int32 nIndex = 0; nIndex >= 0; )
{
if( aAllTypes.getLength() )
aAllTypes += aSeparator;
( aAllTypes += aWildcard ) += aFilters[ i ].second.getToken( 0, ';', nIndex );
}
}
// add filter for all media types
aDlg.AddFilter( AVMEDIA_RESID( AVMEDIA_STR_ALL_MEDIAFILES ), aAllTypes );
for( i = 0; i < aFilters.size(); ++i )
{
::rtl::OUString aTypes;
for( sal_Int32 nIndex = 0; nIndex >= 0; )
{
if( aTypes.getLength() )
aTypes += aSeparator;
( aTypes += aWildcard ) += aFilters[ i ].second.getToken( 0, ';', nIndex );
}
// add single filters
aDlg.AddFilter( aFilters[ i ].first, aTypes );
}
// add filter for all types
aDlg.AddFilter( AVMEDIA_RESID( AVMEDIA_STR_ALL_FILES ), String( RTL_CONSTASCII_USTRINGPARAM( "*.*" ) ) );
if( aDlg.Execute() == ERRCODE_NONE )
{
const INetURLObject aURL( aDlg.GetPath() );
rURL = aURL.GetMainURL( INetURLObject::DECODE_UNAMBIGUOUS );
}
else if( rURL.getLength() )
rURL = ::rtl::OUString();
return( rURL.getLength() > 0 );
}
// -------------------------------------------------------------------------
void MediaWindow::executeFormatErrorBox( Window* pParent )
{
ErrorBox aErrBox( pParent, AVMEDIA_RESID( AVMEDIA_ERR_URL ) );
aErrBox.Execute();
}
// -------------------------------------------------------------------------
bool MediaWindow::isMediaURL( const ::rtl::OUString& rURL, bool bDeep, Size* pPreferredSizePixel )
{
const INetURLObject aURL( rURL );
bool bRet = false;
if( aURL.GetProtocol() != INET_PROT_NOT_VALID )
{
if( bDeep || pPreferredSizePixel )
{
try
{
uno::Reference< media::XPlayer > xPlayer( priv::MediaWindowImpl::createPlayer(
aURL.GetMainURL( INetURLObject::DECODE_UNAMBIGUOUS ) ) );
if( xPlayer.is() )
{
bRet = true;
if( pPreferredSizePixel )
{
const awt::Size aAwtSize( xPlayer->getPreferredPlayerWindowSize() );
pPreferredSizePixel->Width() = aAwtSize.Width;
pPreferredSizePixel->Height() = aAwtSize.Height;
}
}
}
catch( ... )
{
}
}
else
{
FilterNameVector aFilters;
const ::rtl::OUString aExt( aURL.getExtension() );
getMediaFilters( aFilters );
unsigned int i;
for( i = 0; ( i < aFilters.size() ) && !bRet; ++i )
{
for( sal_Int32 nIndex = 0; nIndex >= 0 && !bRet; )
{
if( aExt.equalsIgnoreAsciiCase( aFilters[ i ].second.getToken( 0, ';', nIndex ) ) )
bRet = true;
}
}
}
}
return bRet;
}
// -------------------------------------------------------------------------
uno::Reference< media::XPlayer > MediaWindow::createPlayer( const ::rtl::OUString& rURL )
{
return priv::MediaWindowImpl::createPlayer( rURL );
}
// -------------------------------------------------------------------------
uno::Reference< graphic::XGraphic > MediaWindow::grabFrame( const ::rtl::OUString& rURL,
bool bAllowToCreateReplacementGraphic,
double fMediaTime )
{
uno::Reference< media::XPlayer > xPlayer( createPlayer( rURL ) );
uno::Reference< graphic::XGraphic > xRet;
::std::auto_ptr< Graphic > apGraphic;
if( xPlayer.is() )
{
uno::Reference< media::XFrameGrabber > xGrabber( xPlayer->createFrameGrabber() );
if( xGrabber.is() )
{
if( AVMEDIA_FRAMEGRABBER_DEFAULTFRAME == fMediaTime )
fMediaTime = AVMEDIA_FRAMEGRABBER_DEFAULTFRAME_MEDIATIME;
if( fMediaTime >= xPlayer->getDuration() )
fMediaTime = ( xPlayer->getDuration() * 0.5 );
xRet = xGrabber->grabFrame( fMediaTime );
}
if( !xRet.is() && bAllowToCreateReplacementGraphic )
{
awt::Size aPrefSize( xPlayer->getPreferredPlayerWindowSize() );
if( !aPrefSize.Width && !aPrefSize.Height )
{
const BitmapEx aBmpEx( AVMEDIA_RESID( AVMEDIA_BMP_AUDIOLOGO ) );
apGraphic.reset( new Graphic( aBmpEx ) );
}
}
}
if( !xRet.is() && !apGraphic.get() && bAllowToCreateReplacementGraphic )
{
const BitmapEx aBmpEx( AVMEDIA_RESID( AVMEDIA_BMP_EMPTYLOGO ) );
apGraphic.reset( new Graphic( aBmpEx ) );
}
if( apGraphic.get() )
xRet = apGraphic->GetXGraphic();
return xRet;
}
} // namespace avemdia
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>fix typos<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#include <stdio.h>
#include <avmedia/mediawindow.hxx>
#include "mediawindow_impl.hxx"
#include "mediamisc.hxx"
#include "mediawindow.hrc"
#include <tools/urlobj.hxx>
#include <vcl/msgbox.hxx>
#include <unotools/pathoptions.hxx>
#include <sfx2/filedlghelper.hxx>
#include <comphelper/processfactory.hxx>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/media/XManager.hpp>
#include "com/sun/star/ui/dialogs/TemplateDescription.hpp"
#define AVMEDIA_FRAMEGRABBER_DEFAULTFRAME_MEDIATIME 3.0
using namespace ::com::sun::star;
namespace avmedia {
// ---------------
// - MediaWindow -
// ---------------
MediaWindow::MediaWindow( Window* parent, bool bInternalMediaControl ) :
mpImpl( new priv::MediaWindowImpl( parent, this, bInternalMediaControl ) )
{
mpImpl->Show();
}
// -------------------------------------------------------------------------
MediaWindow::~MediaWindow()
{
mpImpl->cleanUp();
delete mpImpl;
mpImpl = NULL;
}
// -------------------------------------------------------------------------
void MediaWindow::setURL( const ::rtl::OUString& rURL )
{
if( mpImpl )
mpImpl->setURL( rURL );
}
// -------------------------------------------------------------------------
const ::rtl::OUString& MediaWindow::getURL() const
{
return mpImpl->getURL();
}
// -------------------------------------------------------------------------
bool MediaWindow::isValid() const
{
return( mpImpl != NULL && mpImpl->isValid() );
}
// -------------------------------------------------------------------------
void MediaWindow::MouseMove( const MouseEvent& /* rMEvt */ )
{
}
// ---------------------------------------------------------------------
void MediaWindow::MouseButtonDown( const MouseEvent& /* rMEvt */ )
{
}
// ---------------------------------------------------------------------
void MediaWindow::MouseButtonUp( const MouseEvent& /* rMEvt */ )
{
}
// -------------------------------------------------------------------------
void MediaWindow::KeyInput( const KeyEvent& /* rKEvt */ )
{
}
// -------------------------------------------------------------------------
void MediaWindow::KeyUp( const KeyEvent& /* rKEvt */ )
{
}
// -------------------------------------------------------------------------
void MediaWindow::Command( const CommandEvent& /* rCEvt */ )
{
}
// -------------------------------------------------------------------------
sal_Int8 MediaWindow::AcceptDrop( const AcceptDropEvent& /* rEvt */ )
{
return 0;
}
// -------------------------------------------------------------------------
sal_Int8 MediaWindow::ExecuteDrop( const ExecuteDropEvent& /* rEvt */ )
{
return 0;
}
// -------------------------------------------------------------------------
void MediaWindow::StartDrag( sal_Int8 /* nAction */, const Point& /* rPosPixel */ )
{
}
// -------------------------------------------------------------------------
bool MediaWindow::hasPreferredSize() const
{
return( mpImpl != NULL && mpImpl->hasPreferredSize() );
}
// -------------------------------------------------------------------------
Size MediaWindow::getPreferredSize() const
{
return mpImpl->getPreferredSize();
}
// -------------------------------------------------------------------------
void MediaWindow::setPosSize( const Rectangle& rNewRect )
{
if( mpImpl )
{
mpImpl->setPosSize( rNewRect );
}
}
// -------------------------------------------------------------------------
Rectangle MediaWindow::getPosSize() const
{
return Rectangle( mpImpl->GetPosPixel(), mpImpl->GetSizePixel() );
}
// -------------------------------------------------------------------------
void MediaWindow::setPointer( const Pointer& rPointer )
{
if( mpImpl )
mpImpl->setPointer( rPointer );
}
// -------------------------------------------------------------------------
const Pointer& MediaWindow::getPointer() const
{
return mpImpl->getPointer();
}
// -------------------------------------------------------------------------
bool MediaWindow::setZoom( ::com::sun::star::media::ZoomLevel eLevel )
{
return( mpImpl != NULL && mpImpl->setZoom( eLevel ) );
}
// -------------------------------------------------------------------------
::com::sun::star::media::ZoomLevel MediaWindow::getZoom() const
{
return mpImpl->getZoom();
}
// -------------------------------------------------------------------------
bool MediaWindow::start()
{
return( mpImpl != NULL && mpImpl->start() );
}
// -------------------------------------------------------------------------
void MediaWindow::stop()
{
if( mpImpl )
mpImpl->stop();
}
// -------------------------------------------------------------------------
bool MediaWindow::isPlaying() const
{
return( mpImpl != NULL && mpImpl->isPlaying() );
}
// -------------------------------------------------------------------------
double MediaWindow::getDuration() const
{
return mpImpl->getDuration();
}
// -------------------------------------------------------------------------
void MediaWindow::setMediaTime( double fTime )
{
if( mpImpl )
mpImpl->setMediaTime( fTime );
}
// -------------------------------------------------------------------------
double MediaWindow::getMediaTime() const
{
return mpImpl->getMediaTime();
}
// -------------------------------------------------------------------------
void MediaWindow::setStopTime( double fTime )
{
if( mpImpl )
mpImpl->setStopTime( fTime );
}
// -------------------------------------------------------------------------
double MediaWindow::getStopTime() const
{
return mpImpl->getStopTime();
}
// -------------------------------------------------------------------------
void MediaWindow::setRate( double fRate )
{
if( mpImpl )
mpImpl->setRate( fRate );
}
// -------------------------------------------------------------------------
double MediaWindow::getRate() const
{
return mpImpl->getRate();
}
// -------------------------------------------------------------------------
void MediaWindow::setPlaybackLoop( bool bSet )
{
if( mpImpl )
mpImpl->setPlaybackLoop( bSet );
}
// -------------------------------------------------------------------------
bool MediaWindow::isPlaybackLoop() const
{
return mpImpl->isPlaybackLoop();
}
// -------------------------------------------------------------------------
void MediaWindow::setMute( bool bSet )
{
if( mpImpl )
mpImpl->setMute( bSet );
}
// -------------------------------------------------------------------------
bool MediaWindow::isMute() const
{
return mpImpl->isMute();
}
// -------------------------------------------------------------------------
void MediaWindow::updateMediaItem( MediaItem& rItem ) const
{
if( mpImpl )
mpImpl->updateMediaItem( rItem );
}
// -------------------------------------------------------------------------
void MediaWindow::executeMediaItem( const MediaItem& rItem )
{
if( mpImpl )
mpImpl->executeMediaItem( rItem );
}
// -------------------------------------------------------------------------
void MediaWindow::show()
{
if( mpImpl )
mpImpl->Show();
}
// -------------------------------------------------------------------------
void MediaWindow::hide()
{
if( mpImpl )
mpImpl->Hide();
}
// -------------------------------------------------------------------------
void MediaWindow::enable()
{
if( mpImpl )
mpImpl->Enable();
}
// -------------------------------------------------------------------------
void MediaWindow::disable()
{
if( mpImpl )
mpImpl->Disable();
}
// -------------------------------------------------------------------------
Window* MediaWindow::getWindow() const
{
return mpImpl;
}
// -------------------------------------------------------------------------
void MediaWindow::getMediaFilters( FilterNameVector& rFilterNameVector )
{
static const char* pFilters[] = { "AIF Audio", "aif;aiff",
"AU Audio", "au",
"AVI", "avi",
"CD Audio", "cda",
"FLAC Audio", "flac",
"Matroska Media", "mkv",
"MIDI Audio", "mid;midi",
"MPEG Audio", "mp2;mp3;mpa",
"MPEG Video", "mpg;mpeg;mpv;mp4",
"Ogg bitstream", "ogg",
"Quicktime Video", "mov",
"Vivo Video", "viv",
"WAVE Audio", "wav",
"WebM Video", "webm" };
for( size_t i = 0; i < SAL_N_ELEMENTS(pFilters); i += 2 )
{
rFilterNameVector.push_back( ::std::make_pair< ::rtl::OUString, ::rtl::OUString >(
::rtl::OUString::createFromAscii(pFilters[i]),
::rtl::OUString::createFromAscii(pFilters[i+1]) ) );
}
}
// -------------------------------------------------------------------------
bool MediaWindow::executeMediaURLDialog( Window* /* pParent */, ::rtl::OUString& rURL, bool bInsertDialog )
{
::sfx2::FileDialogHelper aDlg( com::sun::star::ui::dialogs::TemplateDescription::FILEOPEN_SIMPLE, 0 );
static const ::rtl::OUString aWildcard( RTL_CONSTASCII_USTRINGPARAM( "*." ) );
FilterNameVector aFilters;
const ::rtl::OUString aSeparator( RTL_CONSTASCII_USTRINGPARAM( ";" ) );
::rtl::OUString aAllTypes;
aDlg.SetTitle( AVMEDIA_RESID( bInsertDialog ? AVMEDIA_STR_INSERTMEDIA_DLG : AVMEDIA_STR_OPENMEDIA_DLG ) );
getMediaFilters( aFilters );
unsigned int i;
for( i = 0; i < aFilters.size(); ++i )
{
for( sal_Int32 nIndex = 0; nIndex >= 0; )
{
if( aAllTypes.getLength() )
aAllTypes += aSeparator;
( aAllTypes += aWildcard ) += aFilters[ i ].second.getToken( 0, ';', nIndex );
}
}
// add filter for all media types
aDlg.AddFilter( AVMEDIA_RESID( AVMEDIA_STR_ALL_MEDIAFILES ), aAllTypes );
for( i = 0; i < aFilters.size(); ++i )
{
::rtl::OUString aTypes;
for( sal_Int32 nIndex = 0; nIndex >= 0; )
{
if( aTypes.getLength() )
aTypes += aSeparator;
( aTypes += aWildcard ) += aFilters[ i ].second.getToken( 0, ';', nIndex );
}
// add single filters
aDlg.AddFilter( aFilters[ i ].first, aTypes );
}
// add filter for all types
aDlg.AddFilter( AVMEDIA_RESID( AVMEDIA_STR_ALL_FILES ), String( RTL_CONSTASCII_USTRINGPARAM( "*.*" ) ) );
if( aDlg.Execute() == ERRCODE_NONE )
{
const INetURLObject aURL( aDlg.GetPath() );
rURL = aURL.GetMainURL( INetURLObject::DECODE_UNAMBIGUOUS );
}
else if( rURL.getLength() )
rURL = ::rtl::OUString();
return( rURL.getLength() > 0 );
}
// -------------------------------------------------------------------------
void MediaWindow::executeFormatErrorBox( Window* pParent )
{
ErrorBox aErrBox( pParent, AVMEDIA_RESID( AVMEDIA_ERR_URL ) );
aErrBox.Execute();
}
// -------------------------------------------------------------------------
bool MediaWindow::isMediaURL( const ::rtl::OUString& rURL, bool bDeep, Size* pPreferredSizePixel )
{
const INetURLObject aURL( rURL );
bool bRet = false;
if( aURL.GetProtocol() != INET_PROT_NOT_VALID )
{
if( bDeep || pPreferredSizePixel )
{
try
{
uno::Reference< media::XPlayer > xPlayer( priv::MediaWindowImpl::createPlayer(
aURL.GetMainURL( INetURLObject::DECODE_UNAMBIGUOUS ) ) );
if( xPlayer.is() )
{
bRet = true;
if( pPreferredSizePixel )
{
const awt::Size aAwtSize( xPlayer->getPreferredPlayerWindowSize() );
pPreferredSizePixel->Width() = aAwtSize.Width;
pPreferredSizePixel->Height() = aAwtSize.Height;
}
}
}
catch( ... )
{
}
}
else
{
FilterNameVector aFilters;
const ::rtl::OUString aExt( aURL.getExtension() );
getMediaFilters( aFilters );
unsigned int i;
for( i = 0; ( i < aFilters.size() ) && !bRet; ++i )
{
for( sal_Int32 nIndex = 0; nIndex >= 0 && !bRet; )
{
if( aExt.equalsIgnoreAsciiCase( aFilters[ i ].second.getToken( 0, ';', nIndex ) ) )
bRet = true;
}
}
}
}
return bRet;
}
// -------------------------------------------------------------------------
uno::Reference< media::XPlayer > MediaWindow::createPlayer( const ::rtl::OUString& rURL )
{
return priv::MediaWindowImpl::createPlayer( rURL );
}
// -------------------------------------------------------------------------
uno::Reference< graphic::XGraphic > MediaWindow::grabFrame( const ::rtl::OUString& rURL,
bool bAllowToCreateReplacementGraphic,
double fMediaTime )
{
uno::Reference< media::XPlayer > xPlayer( createPlayer( rURL ) );
uno::Reference< graphic::XGraphic > xRet;
::std::auto_ptr< Graphic > apGraphic;
if( xPlayer.is() )
{
uno::Reference< media::XFrameGrabber > xGrabber( xPlayer->createFrameGrabber() );
if( xGrabber.is() )
{
if( AVMEDIA_FRAMEGRABBER_DEFAULTFRAME == fMediaTime )
fMediaTime = AVMEDIA_FRAMEGRABBER_DEFAULTFRAME_MEDIATIME;
if( fMediaTime >= xPlayer->getDuration() )
fMediaTime = ( xPlayer->getDuration() * 0.5 );
xRet = xGrabber->grabFrame( fMediaTime );
}
if( !xRet.is() && bAllowToCreateReplacementGraphic )
{
awt::Size aPrefSize( xPlayer->getPreferredPlayerWindowSize() );
if( !aPrefSize.Width && !aPrefSize.Height )
{
const BitmapEx aBmpEx( AVMEDIA_RESID( AVMEDIA_BMP_AUDIOLOGO ) );
apGraphic.reset( new Graphic( aBmpEx ) );
}
}
}
if( !xRet.is() && !apGraphic.get() && bAllowToCreateReplacementGraphic )
{
const BitmapEx aBmpEx( AVMEDIA_RESID( AVMEDIA_BMP_EMPTYLOGO ) );
apGraphic.reset( new Graphic( aBmpEx ) );
}
if( apGraphic.get() )
xRet = apGraphic->GetXGraphic();
return xRet;
}
} // namespace avemdia
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>
|
<commit_before><commit_msg>fdo#56832 Explicitly mention Ogg Audio and Video<commit_after><|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.
//
//===----------------------------------------------------------------------===//
// <random>
// template<class RealType = double>
// class piecewise_linear_distribution
// param_type param() const;
#include <random>
#include <cassert>
int main()
{
{
typedef std::piecewise_linear_distribution<> D;
typedef D::param_type P;
double b[] = {10, 14, 16, 17};
double p[] = {25, 62.5, 12.5, 10};
const size_t Np = sizeof(p) / sizeof(p[0]);
P pa(b, b+Np+1, p);
D d(pa);
assert(d.param() == pa);
}
}
<commit_msg>Fix bug in test; found by AddressSanitizer<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.
//
//===----------------------------------------------------------------------===//
// <random>
// template<class RealType = double>
// class piecewise_linear_distribution
// param_type param() const;
#include <random>
#include <cassert>
int main()
{
{
typedef std::piecewise_linear_distribution<> D;
typedef D::param_type P;
double b[] = {10, 14, 16, 17};
double p[] = {25, 62.5, 12.5, 10};
const size_t Np = sizeof(p) / sizeof(p[0]);
P pa(b, b+Np, p);
D d(pa);
assert(d.param() == pa);
}
}
<|endoftext|>
|
<commit_before>/*
* message queues
*
* Based on wine/server/queue.c
* Copyright (C) 2000 Alexandre Julliard
*
* Modifications for ring3k
* Copyright 2006-2009 Mike McCormack
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*/
#include <stdarg.h>
#include <stdio.h>
#include <assert.h>
#include <new>
#include "ntstatus.h"
#define WIN32_NO_STATUS
#include "windef.h"
#include "winternl.h"
#include "ntcall.h"
#include "object.h"
#include "ntwin32.h"
#include "mem.h"
#include "debug.h"
#include "list.h"
#include "timer.h"
#include "win.h"
#include "queue.h"
#include "spy.h"
DEFAULT_DEBUG_CHANNEL(queue);
#include "object.inl"
CMSG::CMSG( HWND _hwnd, UINT _message, WPARAM _wparam, LPARAM _lparam ) :
HWnd( _hwnd ),
Message( _message ),
WParam( _wparam ),
LParam( _lparam )
{
Time = TIMEOUT::GetTickCount();
}
THREAD_MESSAGE_QUEUE::THREAD_MESSAGE_QUEUE() :
QuitMessage( 0 ),
ExitCode( 0 )
{
}
THREAD_MESSAGE_QUEUE::~THREAD_MESSAGE_QUEUE()
{
CMSG *msg;
while ((msg = MsgList.Head()))
{
MsgList.Unlink( msg );
delete msg;
}
}
bool THREAD_MESSAGE_QUEUE::GetQuitMessage( MSG& msg )
{
bool ret = QuitMessage;
if (QuitMessage)
{
msg.message = WM_QUIT;
msg.wParam = ExitCode;
QuitMessage = false;
}
return ret;
}
bool THREAD_MESSAGE_QUEUE::GetPaintMessage( HWND Window, MSG& msg )
{
WINDOW *win = WINDOW::FindWindowToRepaint( Window, Current );
if (!win)
return FALSE;
msg.message = WM_PAINT;
msg.time = TIMEOUT::GetTickCount();
msg.hwnd = win->handle;
return TRUE;
}
BOOLEAN THREAD_MESSAGE_QUEUE::IsSignalled( void )
{
return FALSE;
}
void THREAD_MESSAGE_QUEUE::PostQuitMessage( ULONG ret )
{
QuitMessage = true;
ExitCode = ret;
}
BOOL THREAD_MESSAGE_QUEUE::PostMessage(
HWND Window, UINT Message, WPARAM Wparam, LPARAM Lparam )
{
MSG_WAITER *waiter = WaiterList.Head();
if (waiter)
{
MSG& msg = waiter->Msg;
msg.hwnd = Window;
msg.message = Message;
msg.wParam = Wparam;
msg.lParam = Lparam;
msg.time = TIMEOUT::GetTickCount();
msg.pt.x = 0;
msg.pt.y = 0;
// remove from the list first
WaiterList.Unlink( waiter );
SetTimeout( 0 );
// start the thread (might reschedule here )
waiter->T->Start();
return TRUE;
}
// no waiter, so store the message
CMSG* msg = new CMSG( Window, Message, Wparam, Lparam );
if (!msg)
return FALSE;
MsgList.Append( msg );
// FIXME: wake up a thread that is waiting
return TRUE;
}
// return true if we copied a message
bool THREAD_MESSAGE_QUEUE::GetPostedMessage( HWND Window, MSG& Message )
{
CMSG *m = MsgList.Head();
if (!m)
return false;
MsgList.Unlink( m );
Message.hwnd = m->HWnd;
Message.message = m->Message;
Message.wParam = m->WParam;
Message.lParam = m->LParam;
Message.time = m->Time;
Message.pt.x = 0;
Message.pt.y = 0;
delete m;
return true;
}
MSG_WAITER::MSG_WAITER( MSG& m):
Msg( m )
{
T = Current;
}
WIN_TIMER::WIN_TIMER( HWND Window, UINT Identifier ) :
HWnd( Window ),
Id( Identifier ),
LParam(0),
Period(0)
{
Expiry.QuadPart = 0LL;
}
WIN_TIMER* THREAD_MESSAGE_QUEUE::FindTimer( HWND Window, UINT Identifier )
{
for (WIN_TIMER_ITER i(TimerList); i; i.Next())
{
WIN_TIMER *t = i;
if (t->Id != Identifier)
continue;
if (t->HWnd != Window )
continue;
return t;
}
return NULL;
}
void WIN_TIMER::Reset()
{
Expiry = TIMEOUT::CurrentTime();
Expiry.QuadPart += Period*10000LL;
}
bool WIN_TIMER::Expired() const
{
LARGE_INTEGER now = TIMEOUT::CurrentTime();
return (now.QuadPart >= Expiry.QuadPart);
}
void THREAD_MESSAGE_QUEUE::TimerAdd( WIN_TIMER* timer )
{
WIN_TIMER *t = NULL;
// maintain list in order of expiry time
for (WIN_TIMER_ITER i(TimerList); i; i.Next())
{
t = i;
if (t->Expiry.QuadPart >= timer->Expiry.QuadPart)
break;
}
if (t)
TimerList.InsertBefore( t, timer );
else
TimerList.Append( timer );
}
bool THREAD_MESSAGE_QUEUE::GetTimerMessage( HWND Window, MSG& msg )
{
LARGE_INTEGER now = TIMEOUT::CurrentTime();
WIN_TIMER *t = NULL;
for (WIN_TIMER_ITER i(TimerList); i; i.Next())
{
t = i;
// stop searching after we reach a timer that has not expired
if (t->Expiry.QuadPart > now.QuadPart)
return false;
if (Window == NULL || t->HWnd == Window)
break;
}
if (!t)
return false;
// remove from the front of the queue
TimerList.Unlink( t );
msg.hwnd = t->HWnd;
msg.message = WM_TIMER;
msg.wParam = t->Id;
msg.lParam = (UINT) t->LParam;
msg.time = TIMEOUT::GetTickCount();
msg.pt.x = 0;
msg.pt.y = 0;
// reset and add back to the queue
t->Reset();
TimerAdd( t );
return true;
}
BOOLEAN THREAD_MESSAGE_QUEUE::SetTimer( HWND Window, UINT Identifier, UINT Elapse, PVOID TimerProc )
{
WIN_TIMER* timer = FindTimer( Window, Identifier );
if (timer)
TimerList.Unlink( timer );
else
timer = new WIN_TIMER( Window, Identifier );
TRACE("adding timer %p hwnd %p id %d\n", timer, Window, Identifier );
timer->Period = Elapse;
timer->LParam = TimerProc;
TimerAdd( timer );
return TRUE;
}
BOOLEAN THREAD_MESSAGE_QUEUE::KillTimer( HWND Window, UINT Identifier )
{
WIN_TIMER* timer = FindTimer( Window, Identifier );
if (!timer)
return FALSE;
TRACE("deleting timer %p hwnd %p id %d\n", timer, Window, Identifier );
TimerList.Unlink( timer );
delete timer;
return TRUE;
}
bool THREAD_MESSAGE_QUEUE::GetMessageTimeout( HWND Window, LARGE_INTEGER& timeout )
{
for (WIN_TIMER_ITER i(TimerList); i; i.Next())
{
WIN_TIMER *t = i;
if (Window != NULL && t->HWnd != Window)
continue;
timeout = t->Expiry;
return true;
}
return false;
}
// return true if we succeeded in copying a message
BOOLEAN THREAD_MESSAGE_QUEUE::GetMessageNoWait(
MSG& Message, HWND Window, ULONG MinMessage, ULONG MaxMessage)
{
//trace("checking posted messages\n");
if (GetPostedMessage( Window, Message ))
return true;
//trace("checking quit messages\n");
if (GetQuitMessage( Message ))
return true;
//trace("checking paint messages\n");
if (GetPaintMessage( Window, Message ))
return true;
//trace("checking timer messages\n");
if (GetTimerMessage( Window, Message ))
return true;
return false;
}
void THREAD_MESSAGE_QUEUE::SignalTimeout()
{
MSG_WAITER *waiter = WaiterList.Head();
if (waiter)
{
WaiterList.Unlink( waiter );
SetTimeout( 0 );
// start the thread (might reschedule here )
waiter->T->Start();
}
}
BOOLEAN THREAD_MESSAGE_QUEUE::GetMessage(
MSG& Message, HWND Window, ULONG MinMessage, ULONG MaxMessage)
{
if (GetMessageNoWait( Message, Window, MinMessage, MaxMessage))
return true;
LARGE_INTEGER t;
if (GetMessageTimeout( Window, t ))
{
//trace("setting timeout %lld\n", t.QuadPart);
SetTimeout( &t );
}
// wait for a message
// a thread sending a message will restart us
MSG_WAITER wait( Message );
WaiterList.Append( &wait );
Current->Stop();
return !Current->IsTerminated();
}
BOOLEAN NTAPI NtUserGetMessage(PMSG Message, HWND Window, ULONG MinMessage, ULONG MaxMessage)
{
// no input queue...
THREAD_MESSAGE_QUEUE* queue = Current->Queue;
if (!queue)
return FALSE;
NTSTATUS r = VerifyForWrite( Message, sizeof *Message );
if (r != STATUS_SUCCESS)
return FALSE;
MSG msg;
memset( &msg, 0, sizeof msg );
if (queue->GetMessage( msg, Window, MinMessage, MaxMessage ))
CopyToUser( Message, &msg, sizeof msg );
if (OptionTrace)
{
fprintf(stderr, "%lx.%lx: %s\n", Current->Process->Id, Current->GetID(), __FUNCTION__);
fprintf(stderr, " msg.hwnd = %p\n", msg.hwnd);
fprintf(stderr, " msg.message = %08x (%s)\n", msg.message, GetMessageName(msg.message));
fprintf(stderr, " msg.wParam = %08x\n", msg.wParam);
fprintf(stderr, " msg.lParam = %08lx\n", msg.lParam);
fprintf(stderr, " msg.time = %08lx\n", msg.time);
fprintf(stderr, " msg.pt.x = %08lx\n", msg.pt.x);
fprintf(stderr, " msg.pt.y = %08lx\n", msg.pt.y);
}
return msg.message != WM_QUIT;
}
BOOLEAN NTAPI NtUserPostMessage( HWND Window, UINT Message, WPARAM Wparam, LPARAM Lparam )
{
WINDOW *win = WindowFromHandle( Window );
if (!win)
return FALSE;
THREAD*& thread = win->GetWinThread();
assert(thread != NULL);
return thread->Queue->PostMessage( Window, Message, Wparam, Lparam );
}
BOOLEAN NTAPI NtUserPeekMessage( PMSG Message, HWND Window, UINT MaxMessage, UINT MinMessage, UINT Remove)
{
THREAD_MESSAGE_QUEUE* queue = Current->Queue;
if (!queue)
return FALSE;
NTSTATUS r = VerifyForWrite( Message, sizeof *Message );
if (r != STATUS_SUCCESS)
return FALSE;
MSG msg;
memset( &msg, 0, sizeof msg );
BOOL ret = queue->GetMessageNoWait( msg, Window, MinMessage, MaxMessage );
if (ret)
CopyToUser( Message, &msg, sizeof msg );
return ret;
}
UINT NTAPI NtUserSetTimer( HWND Window, UINT Identifier, UINT Elapse, PVOID TimerProc )
{
WINDOW *win = WindowFromHandle( Window );
if (!win)
return FALSE;
THREAD*& thread = win->GetWinThread();
assert(thread != NULL);
return thread->Queue->SetTimer( Window, Identifier, Elapse, TimerProc );
}
BOOLEAN NTAPI NtUserKillTimer( HWND Window, UINT Identifier )
{
WINDOW *win = WindowFromHandle( Window );
if (!win)
return FALSE;
THREAD*& thread = win->GetWinThread();
assert(thread != NULL);
return thread->Queue->KillTimer( Window, Identifier );
}
<commit_msg>kernel: Create input queue if it's missing in a call to GetMessage (used by Winlogon when running in setup mode). Leave a warning there, in case something misbehaves. But so far, Wine's behaviour is exactly that: creating message queue if it doesn't exist.<commit_after>/*
* message queues
*
* Based on wine/server/queue.c
* Copyright (C) 2000 Alexandre Julliard
*
* Modifications for ring3k
* Copyright 2006-2009 Mike McCormack
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*/
#include <stdarg.h>
#include <stdio.h>
#include <assert.h>
#include <new>
#include "ntstatus.h"
#define WIN32_NO_STATUS
#include "windef.h"
#include "winternl.h"
#include "ntcall.h"
#include "object.h"
#include "ntwin32.h"
#include "mem.h"
#include "debug.h"
#include "list.h"
#include "timer.h"
#include "win.h"
#include "queue.h"
#include "spy.h"
DEFAULT_DEBUG_CHANNEL(queue);
#include "object.inl"
CMSG::CMSG( HWND _hwnd, UINT _message, WPARAM _wparam, LPARAM _lparam ) :
HWnd( _hwnd ),
Message( _message ),
WParam( _wparam ),
LParam( _lparam )
{
Time = TIMEOUT::GetTickCount();
}
THREAD_MESSAGE_QUEUE::THREAD_MESSAGE_QUEUE() :
QuitMessage( 0 ),
ExitCode( 0 )
{
}
THREAD_MESSAGE_QUEUE::~THREAD_MESSAGE_QUEUE()
{
CMSG *msg;
while ((msg = MsgList.Head()))
{
MsgList.Unlink( msg );
delete msg;
}
}
bool THREAD_MESSAGE_QUEUE::GetQuitMessage( MSG& msg )
{
bool ret = QuitMessage;
if (QuitMessage)
{
msg.message = WM_QUIT;
msg.wParam = ExitCode;
QuitMessage = false;
}
return ret;
}
bool THREAD_MESSAGE_QUEUE::GetPaintMessage( HWND Window, MSG& msg )
{
WINDOW *win = WINDOW::FindWindowToRepaint( Window, Current );
if (!win)
return FALSE;
msg.message = WM_PAINT;
msg.time = TIMEOUT::GetTickCount();
msg.hwnd = win->handle;
return TRUE;
}
BOOLEAN THREAD_MESSAGE_QUEUE::IsSignalled( void )
{
return FALSE;
}
void THREAD_MESSAGE_QUEUE::PostQuitMessage( ULONG ret )
{
QuitMessage = true;
ExitCode = ret;
}
BOOL THREAD_MESSAGE_QUEUE::PostMessage(
HWND Window, UINT Message, WPARAM Wparam, LPARAM Lparam )
{
MSG_WAITER *waiter = WaiterList.Head();
if (waiter)
{
MSG& msg = waiter->Msg;
msg.hwnd = Window;
msg.message = Message;
msg.wParam = Wparam;
msg.lParam = Lparam;
msg.time = TIMEOUT::GetTickCount();
msg.pt.x = 0;
msg.pt.y = 0;
// remove from the list first
WaiterList.Unlink( waiter );
SetTimeout( 0 );
// start the thread (might reschedule here )
waiter->T->Start();
return TRUE;
}
// no waiter, so store the message
CMSG* msg = new CMSG( Window, Message, Wparam, Lparam );
if (!msg)
return FALSE;
MsgList.Append( msg );
// FIXME: wake up a thread that is waiting
return TRUE;
}
// return true if we copied a message
bool THREAD_MESSAGE_QUEUE::GetPostedMessage( HWND Window, MSG& Message )
{
CMSG *m = MsgList.Head();
if (!m)
return false;
MsgList.Unlink( m );
Message.hwnd = m->HWnd;
Message.message = m->Message;
Message.wParam = m->WParam;
Message.lParam = m->LParam;
Message.time = m->Time;
Message.pt.x = 0;
Message.pt.y = 0;
delete m;
return true;
}
MSG_WAITER::MSG_WAITER( MSG& m):
Msg( m )
{
T = Current;
}
WIN_TIMER::WIN_TIMER( HWND Window, UINT Identifier ) :
HWnd( Window ),
Id( Identifier ),
LParam(0),
Period(0)
{
Expiry.QuadPart = 0LL;
}
WIN_TIMER* THREAD_MESSAGE_QUEUE::FindTimer( HWND Window, UINT Identifier )
{
for (WIN_TIMER_ITER i(TimerList); i; i.Next())
{
WIN_TIMER *t = i;
if (t->Id != Identifier)
continue;
if (t->HWnd != Window )
continue;
return t;
}
return NULL;
}
void WIN_TIMER::Reset()
{
Expiry = TIMEOUT::CurrentTime();
Expiry.QuadPart += Period*10000LL;
}
bool WIN_TIMER::Expired() const
{
LARGE_INTEGER now = TIMEOUT::CurrentTime();
return (now.QuadPart >= Expiry.QuadPart);
}
void THREAD_MESSAGE_QUEUE::TimerAdd( WIN_TIMER* timer )
{
WIN_TIMER *t = NULL;
// maintain list in order of expiry time
for (WIN_TIMER_ITER i(TimerList); i; i.Next())
{
t = i;
if (t->Expiry.QuadPart >= timer->Expiry.QuadPart)
break;
}
if (t)
TimerList.InsertBefore( t, timer );
else
TimerList.Append( timer );
}
bool THREAD_MESSAGE_QUEUE::GetTimerMessage( HWND Window, MSG& msg )
{
LARGE_INTEGER now = TIMEOUT::CurrentTime();
WIN_TIMER *t = NULL;
for (WIN_TIMER_ITER i(TimerList); i; i.Next())
{
t = i;
// stop searching after we reach a timer that has not expired
if (t->Expiry.QuadPart > now.QuadPart)
return false;
if (Window == NULL || t->HWnd == Window)
break;
}
if (!t)
return false;
// remove from the front of the queue
TimerList.Unlink( t );
msg.hwnd = t->HWnd;
msg.message = WM_TIMER;
msg.wParam = t->Id;
msg.lParam = (UINT) t->LParam;
msg.time = TIMEOUT::GetTickCount();
msg.pt.x = 0;
msg.pt.y = 0;
// reset and add back to the queue
t->Reset();
TimerAdd( t );
return true;
}
BOOLEAN THREAD_MESSAGE_QUEUE::SetTimer( HWND Window, UINT Identifier, UINT Elapse, PVOID TimerProc )
{
WIN_TIMER* timer = FindTimer( Window, Identifier );
if (timer)
TimerList.Unlink( timer );
else
timer = new WIN_TIMER( Window, Identifier );
TRACE("adding timer %p hwnd %p id %d\n", timer, Window, Identifier );
timer->Period = Elapse;
timer->LParam = TimerProc;
TimerAdd( timer );
return TRUE;
}
BOOLEAN THREAD_MESSAGE_QUEUE::KillTimer( HWND Window, UINT Identifier )
{
WIN_TIMER* timer = FindTimer( Window, Identifier );
if (!timer)
return FALSE;
TRACE("deleting timer %p hwnd %p id %d\n", timer, Window, Identifier );
TimerList.Unlink( timer );
delete timer;
return TRUE;
}
bool THREAD_MESSAGE_QUEUE::GetMessageTimeout( HWND Window, LARGE_INTEGER& timeout )
{
for (WIN_TIMER_ITER i(TimerList); i; i.Next())
{
WIN_TIMER *t = i;
if (Window != NULL && t->HWnd != Window)
continue;
timeout = t->Expiry;
return true;
}
return false;
}
// return true if we succeeded in copying a message
BOOLEAN THREAD_MESSAGE_QUEUE::GetMessageNoWait(
MSG& Message, HWND Window, ULONG MinMessage, ULONG MaxMessage)
{
//trace("checking posted messages\n");
if (GetPostedMessage( Window, Message ))
return true;
//trace("checking quit messages\n");
if (GetQuitMessage( Message ))
return true;
//trace("checking paint messages\n");
if (GetPaintMessage( Window, Message ))
return true;
//trace("checking timer messages\n");
if (GetTimerMessage( Window, Message ))
return true;
return false;
}
void THREAD_MESSAGE_QUEUE::SignalTimeout()
{
MSG_WAITER *waiter = WaiterList.Head();
if (waiter)
{
WaiterList.Unlink( waiter );
SetTimeout( 0 );
// start the thread (might reschedule here )
waiter->T->Start();
}
}
BOOLEAN THREAD_MESSAGE_QUEUE::GetMessage(
MSG& Message, HWND Window, ULONG MinMessage, ULONG MaxMessage)
{
if (GetMessageNoWait( Message, Window, MinMessage, MaxMessage))
return true;
LARGE_INTEGER t;
if (GetMessageTimeout( Window, t ))
{
//trace("setting timeout %lld\n", t.QuadPart);
SetTimeout( &t );
}
// wait for a message
// a thread sending a message will restart us
MSG_WAITER wait( Message );
WaiterList.Append( &wait );
Current->Stop();
return !Current->IsTerminated();
}
BOOLEAN NTAPI NtUserGetMessage(PMSG Message, HWND Window, ULONG MinMessage, ULONG MaxMessage)
{
// create a thread message queue if necessary
if (!Current->Queue)
{
WARN("Calling GetMessage for a thread without input queue, creating it!\n");
Current->Queue = new THREAD_MESSAGE_QUEUE;
}
NTSTATUS r = VerifyForWrite( Message, sizeof *Message );
if (r != STATUS_SUCCESS)
return FALSE;
MSG msg;
memset( &msg, 0, sizeof msg );
if (Current->Queue->GetMessage(msg, Window, MinMessage, MaxMessage))
CopyToUser( Message, &msg, sizeof msg );
if (OptionTrace)
{
fprintf(stderr, "%lx.%lx: %s\n", Current->Process->Id, Current->GetID(), __FUNCTION__);
fprintf(stderr, " msg.hwnd = %p\n", msg.hwnd);
fprintf(stderr, " msg.message = %08x (%s)\n", msg.message, GetMessageName(msg.message));
fprintf(stderr, " msg.wParam = %08x\n", msg.wParam);
fprintf(stderr, " msg.lParam = %08lx\n", msg.lParam);
fprintf(stderr, " msg.time = %08lx\n", msg.time);
fprintf(stderr, " msg.pt.x = %08lx\n", msg.pt.x);
fprintf(stderr, " msg.pt.y = %08lx\n", msg.pt.y);
}
return msg.message != WM_QUIT;
}
BOOLEAN NTAPI NtUserPostMessage( HWND Window, UINT Message, WPARAM Wparam, LPARAM Lparam )
{
WINDOW *win = WindowFromHandle( Window );
if (!win)
return FALSE;
THREAD*& thread = win->GetWinThread();
assert(thread != NULL);
return thread->Queue->PostMessage( Window, Message, Wparam, Lparam );
}
BOOLEAN NTAPI NtUserPeekMessage( PMSG Message, HWND Window, UINT MaxMessage, UINT MinMessage, UINT Remove)
{
THREAD_MESSAGE_QUEUE* queue = Current->Queue;
if (!queue)
return FALSE;
NTSTATUS r = VerifyForWrite( Message, sizeof *Message );
if (r != STATUS_SUCCESS)
return FALSE;
MSG msg;
memset( &msg, 0, sizeof msg );
BOOL ret = queue->GetMessageNoWait( msg, Window, MinMessage, MaxMessage );
if (ret)
CopyToUser( Message, &msg, sizeof msg );
return ret;
}
UINT NTAPI NtUserSetTimer( HWND Window, UINT Identifier, UINT Elapse, PVOID TimerProc )
{
WINDOW *win = WindowFromHandle( Window );
if (!win)
return FALSE;
THREAD*& thread = win->GetWinThread();
assert(thread != NULL);
return thread->Queue->SetTimer( Window, Identifier, Elapse, TimerProc );
}
BOOLEAN NTAPI NtUserKillTimer( HWND Window, UINT Identifier )
{
WINDOW *win = WindowFromHandle( Window );
if (!win)
return FALSE;
THREAD*& thread = win->GetWinThread();
assert(thread != NULL);
return thread->Queue->KillTimer( Window, Identifier );
}
<|endoftext|>
|
<commit_before>/* simple hash table for kmail. inspired by QDict */
/* Author: Ronen Tzur <rtzur@shani.net> */
#include "kmdict.h"
#include <string.h>
//-----------------------------------------------------------------------------
KMDict::KMDict(int size)
{
init(size);
}
//-----------------------------------------------------------------------------
KMDict::~KMDict()
{
clear();
}
//-----------------------------------------------------------------------------
void KMDict::init(int size)
{
mSize = size;
mVecs = new KMDictItem *[mSize];
memset(mVecs, 0, mSize * sizeof(KMDictItem *));
}
//-----------------------------------------------------------------------------
void KMDict::clear()
{
if (!mVecs)
return;
for (int i = 0; i < mSize; i++) {
KMDictItem *item = mVecs[i];
while (item) {
KMDictItem *nextItem = item->next;
delete item;
item = nextItem;
}
}
delete mVecs;
mVecs = 0;
}
//-----------------------------------------------------------------------------
void KMDict::replace(long key, KMDictItem *item)
{
item->key = key;
int idx = (unsigned long)key % mSize; // insert in
item->next = mVecs[idx]; // appropriate
mVecs[idx] = item; // column
removeFollowing(item, key); // remove other items with same key
}
//-----------------------------------------------------------------------------
void KMDict::remove(long key)
{
int idx = (unsigned long)key % mSize;
KMDictItem *item = mVecs[idx];
if (item) {
if (item->key == key) { // if first in the column
mVecs[idx] = item->next;
delete item;
} else
removeFollowing(item, key); // if deep in the column
}
}
//-----------------------------------------------------------------------------
void KMDict::removeFollowing(KMDictItem *item, long key)
{
while (item) {
KMDictItem *itemNext = item->next;
if (itemNext && itemNext->key == key) {
KMDictItem *itemNextNext = itemNext->next;
delete itemNext;
item->next = itemNextNext;
} else
item = itemNext;
}
}
//-----------------------------------------------------------------------------
KMDictItem *KMDict::find(long key)
{
int idx = (unsigned long)key % mSize;
KMDictItem *item = mVecs[idx];
while (item) {
if (item->key == key)
break;
item = item->next;
}
return item;
}
<commit_msg>- delete mVecs; + delete [] mVecs;<commit_after>/* simple hash table for kmail. inspired by QDict */
/* Author: Ronen Tzur <rtzur@shani.net> */
#include "kmdict.h"
#include <string.h>
//-----------------------------------------------------------------------------
KMDict::KMDict(int size)
{
init(size);
}
//-----------------------------------------------------------------------------
KMDict::~KMDict()
{
clear();
}
//-----------------------------------------------------------------------------
void KMDict::init(int size)
{
mSize = size;
mVecs = new KMDictItem *[mSize];
memset(mVecs, 0, mSize * sizeof(KMDictItem *));
}
//-----------------------------------------------------------------------------
void KMDict::clear()
{
if (!mVecs)
return;
for (int i = 0; i < mSize; i++) {
KMDictItem *item = mVecs[i];
while (item) {
KMDictItem *nextItem = item->next;
delete item;
item = nextItem;
}
}
delete [] mVecs;
mVecs = 0;
}
//-----------------------------------------------------------------------------
void KMDict::replace(long key, KMDictItem *item)
{
item->key = key;
int idx = (unsigned long)key % mSize; // insert in
item->next = mVecs[idx]; // appropriate
mVecs[idx] = item; // column
removeFollowing(item, key); // remove other items with same key
}
//-----------------------------------------------------------------------------
void KMDict::remove(long key)
{
int idx = (unsigned long)key % mSize;
KMDictItem *item = mVecs[idx];
if (item) {
if (item->key == key) { // if first in the column
mVecs[idx] = item->next;
delete item;
} else
removeFollowing(item, key); // if deep in the column
}
}
//-----------------------------------------------------------------------------
void KMDict::removeFollowing(KMDictItem *item, long key)
{
while (item) {
KMDictItem *itemNext = item->next;
if (itemNext && itemNext->key == key) {
KMDictItem *itemNextNext = itemNext->next;
delete itemNext;
item->next = itemNextNext;
} else
item = itemNext;
}
}
//-----------------------------------------------------------------------------
KMDictItem *KMDict::find(long key)
{
int idx = (unsigned long)key % mSize;
KMDictItem *item = mVecs[idx];
while (item) {
if (item->key == key)
break;
item = item->next;
}
return item;
}
<|endoftext|>
|
<commit_before>#pragma once
#include <tuple>
#include <utility>
#include <core/function_traits.hpp>
#include <core/traits.hpp>
#include <core/tuple_meta.hpp>
namespace fc
{
template <class... ports>
struct mux_port;
template <class op>
struct unloaded_merge_port;
template <class op, class... ports>
struct loaded_merge_port;
struct default_tag {};
struct merge_tag {};
struct mux_tag {};
template <typename T>
struct port_traits
{
using mux_category = default_tag;
};
template <class... ports>
struct port_traits<mux_port<ports...>>
{
using mux_category = mux_tag;
};
template <class op>
struct port_traits<unloaded_merge_port<op>>
{
using mux_category = merge_tag;
};
namespace detail
{
template <bool... vals>
constexpr bool any()
{
bool values[] = {vals...};
for (auto value : values)
if (value)
return true;
return false;
}
template <typename... T>
constexpr bool always_false_fun(T...)
{
return false;
}
template <bool... vals>
constexpr bool all()
{
bool values[] = {vals...};
for (auto value : values)
if (!value)
return false;
return true;
}
} // namespace detail
template <class base>
struct node_aware;
struct many_to_many_tag {};
struct one_to_many_tag {};
struct many_to_one_tag {};
template <size_t left_ports, size_t right_ports>
struct mux_traits
{
static_assert(
detail::always_false_fun(left_ports, right_ports),
"Only N->N, 1->N and N->1 connections possible between muxed ports. PS: don't try 1->1.");
};
template <size_t ports>
struct mux_traits<ports, ports>
{
using connection_category = many_to_many_tag;
};
template <size_t ports>
struct mux_traits<ports, 1>
{
using connection_category = many_to_one_tag;
};
template <size_t ports>
struct mux_traits<1, ports>
{
using connection_category = one_to_many_tag;
};
template <class... port_ts>
struct mux_port
{
std::tuple<port_ts...> ports;
private:
template <class T>
auto connect(T t, merge_tag)
{
static_assert(
detail::has_result_of_type<decltype(t.merge), decltype(std::declval<port_ts>()())...>(),
"The muxed ports can not be merged using the provided merge function.");
static_assert(!detail::any<detail::is_derived_from<node_aware, port_ts>::value...>(),
"Merge port can not be used with node aware ports. See merge_node.");
return loaded_merge_port<decltype(t.merge), port_ts...>{t.merge, std::move(ports)};
}
template <class other_mux>
auto connect(other_mux&& other, mux_tag)
{
constexpr size_t this_ports = sizeof...(port_ts);
constexpr size_t other_ports = std::tuple_size<decltype(other.ports)>::value;
using connection_tag = typename mux_traits<this_ports, other_ports>::connection_category;
return connect_mux(std::forward<other_mux>(other), connection_tag{});
}
template <class other_mux_port>
auto connect_mux(other_mux_port&& other, many_to_many_tag)
{
auto pairwise_connect = [](auto&& l, auto&& r)
{
return std::forward<decltype(l)>(l) >> std::forward<decltype(r)>(r);
};
return fc::tuple::transform(std::move(ports), std::forward<other_mux_port>(other).ports,
pairwise_connect);
}
template <class sink_t>
auto connect_mux(mux_port<sink_t>&& other, many_to_one_tag)
{
sink_t&& sink = std::get<0>(std::move(other).ports);
auto all_to_sink = [&sink](auto&& port)
{
return std::forward<decltype(port)>(port) >> static_cast<sink_t>(sink);
};
return fc::tuple::transform(std::move(ports), all_to_sink);
}
template <class other_mux_port>
auto connect_mux(other_mux_port&& other, one_to_many_tag)
{
static_assert(
sizeof...(port_ts) == 1,
"(*this).ports should have a single port; if you are here, your logic must be wrong.");
using src_t = typename std::tuple_element<0, decltype(ports)>::type;
src_t&& src = std::get<0>(std::move(ports));
auto src_to_all = [&src](auto&& port)
{
return static_cast<src_t>(src) >> std::forward<decltype(port)>(port);
};
return fc::tuple::transform(std::forward<other_mux_port>(other).ports, src_to_all);
}
template <class T>
auto connect(T&& t, default_tag)
{
auto connect_to_copy = [&t](auto&& elem)
{
// t needs to be copied if it's not an lvalue ref, forward won't work because can't move
// from smth multiple times.
return std::forward<decltype(elem)>(elem) >> static_cast<T>(t);
};
return mux_from_tuple(fc::tuple::transform(std::move(ports), connect_to_copy));
}
public:
template <class T>
auto operator>>(T&& t)
{
using decayed = std::decay_t<T>;
using tag = typename fc::port_traits<decayed>::mux_category;
return this->connect(std::forward<T>(t), tag{});
}
};
template <class T, class... ports,
class = std::enable_if_t<is_active_source<std::remove_reference_t<T>>{} &&
detail::all<is_connectable<ports>{}...>()>>
auto operator>>(T&& src, mux_port<ports...> mux)
{
return mux_port<T>{std::forward_as_tuple(std::forward<T>(src))} >> std::move(mux);
}
template <class... port_ts>
auto mux(port_ts&... ports)
{
return mux_port<std::remove_const_t<port_ts>&...>{std::tie(ports...)};
}
template <class... conn_ts>
mux_port<conn_ts...> mux_from_tuple(std::tuple<conn_ts...> tuple_)
{
return mux_port<conn_ts...>{std::move(tuple_)};
}
template <class merge_op>
struct unloaded_merge_port
{
merge_op merge;
};
template <class merge_op, class... port_ts>
struct loaded_merge_port
{
merge_op op;
std::tuple<port_ts...> ports;
auto operator()()
{
auto op = this->op;
auto call_and_apply = [op](auto&&... src)
{
return op(std::forward<decltype(src)>(src)()...);
};
return tuple::invoke_function(call_and_apply, ports,
std::make_index_sequence<sizeof...(port_ts)>{});
}
};
template <class merge_op>
auto merge(merge_op op)
{
return unloaded_merge_port<merge_op>{op};
}
} // namespace fc
<commit_msg>ports: mux: add API documentation.<commit_after>#pragma once
#include <tuple>
#include <utility>
#include <core/function_traits.hpp>
#include <core/traits.hpp>
#include <core/tuple_meta.hpp>
namespace fc
{
template <class... ports>
struct mux_port;
template <class op>
struct unloaded_merge_port;
template <class op, class... ports>
struct loaded_merge_port;
struct default_tag {};
struct merge_tag {};
struct mux_tag {};
/// Traits used to determine whether a muxed port is connecting to a muxed
/// port, a merge port or any other connectable object.
template <typename T>
struct port_traits
{
using mux_category = default_tag;
};
template <class... ports>
struct port_traits<mux_port<ports...>>
{
using mux_category = mux_tag;
};
template <class op>
struct port_traits<unloaded_merge_port<op>>
{
using mux_category = merge_tag;
};
namespace detail
{
/// Helper: check if any of the passed bools are true.
template <bool... vals>
constexpr bool any()
{
bool values[] = {vals...};
for (auto value : values)
if (value)
return true;
return false;
}
/** \brief Helper: return false regardless of what the parameters are.
*
* Useful for static_assert conditions in templates that are always invalid -
* prevents them from firing before the template is instantiated.
*/
template <typename... T>
constexpr bool always_false_fun(T...)
{
return false;
}
/// Helper: check if all of the passed bools are true.
template <bool... vals>
constexpr bool all()
{
bool values[] = {vals...};
for (auto value : values)
if (!value)
return false;
return true;
}
} // namespace detail
template <class base>
struct node_aware;
struct many_to_many_tag {};
struct one_to_many_tag {};
struct many_to_one_tag {};
/// Trait used to determine how many muxed ports are being connected on each side.
template <size_t left_ports, size_t right_ports>
struct mux_traits
{
static_assert(
detail::always_false_fun(left_ports, right_ports),
"Only N->N, 1->N and N->1 connections possible between muxed ports. PS: don't try 1->1.");
};
template <size_t ports>
struct mux_traits<ports, ports>
{
using connection_category = many_to_many_tag;
};
template <size_t ports>
struct mux_traits<ports, 1>
{
using connection_category = many_to_one_tag;
};
template <size_t ports>
struct mux_traits<1, ports>
{
using connection_category = one_to_many_tag;
};
/** \brief A wrapper around multiple ports that simplifies establishing
* *identical* connections.
*
* Basically will lead to the following transformation:
*
* mux(a,b,c) >> d ===> a >> d
* b >> d
* c >> d
*
* with special cases for mux(...) >> mux(...), and mux(...) >> merge_port.
*
* Mux ports can be used on both sides of a connection but need to be at the
* ends of a connection chain. Mux ports don't fulfill the concept of
* connectable (or active connectable for that matter) but they do have special
* overloads of operator>> which allow them to participate in connections.
*/
template <class... port_ts>
struct mux_port
{
std::tuple<port_ts...> ports;
private:
/** \brief Overload for connecting to an unloaded_merge_port
*
* T is expected to be an instantiation of unloaded_merge_port.
* T and T.merge are assumed to be copyable.
*
* \returns loaded_merge_port with the supplied merge operation and the
* ports previously held by *this.
*/
template <class T>
auto connect(T t, merge_tag)
{
static_assert(
detail::has_result_of_type<decltype(t.merge), decltype(std::declval<port_ts>()())...>(),
"The muxed ports can not be merged using the provided merge function.");
static_assert(!detail::any<detail::is_derived_from<node_aware, port_ts>::value...>(),
"Merge port can not be used with node aware ports. See merge_node.");
return loaded_merge_port<decltype(t.merge), port_ts...>{t.merge, std::move(ports)};
}
/** \brief Overload for connecting to another muxed port.
*
* other_mux is expected to be an instantiation of mux_port, the ports
* in *this and in other should have compatible types.
* The amount of ports on both sides also needs to be compatible:
*
* * N - N
* * 1 - N
* * N - 1
*
* for N > 1. The appropriate overload of connect_mux is selected using mux_traits.
*/
template <class other_mux>
auto connect(other_mux&& other, mux_tag)
{
constexpr size_t this_ports = sizeof...(port_ts);
constexpr size_t other_ports = std::tuple_size<decltype(other.ports)>::value;
using connection_tag = typename mux_traits<this_ports, other_ports>::connection_category;
return connect_mux(std::forward<other_mux>(other), connection_tag{});
}
/** \brief Connect each port in *this with each port in other.
*
* mux-mux connections should be the end of a connection chain.
* \returns (if used correctly) std::tuple<port_connections...>
*/
template <class other_mux_port>
auto connect_mux(other_mux_port&& other, many_to_many_tag)
{
auto pairwise_connect = [](auto&& l, auto&& r)
{
return std::forward<decltype(l)>(l) >> std::forward<decltype(r)>(r);
};
return fc::tuple::transform(std::move(ports), std::forward<other_mux_port>(other).ports,
pairwise_connect);
}
/** \brief Connect each port in *this with the one (sink) port in other.
*
* The sink port is copied if it was held by value inside other, or else it
* will be passed to the connection as an lvalue.
*
* \returns std::tuple<port_connections...>
*/
template <class sink_t>
auto connect_mux(mux_port<sink_t>&& other, many_to_one_tag)
{
sink_t&& sink = std::get<0>(std::move(other).ports);
auto all_to_sink = [&sink](auto&& port)
{
return std::forward<decltype(port)>(port) >> static_cast<sink_t>(sink);
};
return fc::tuple::transform(std::move(ports), all_to_sink);
}
/** \brief Connect each port in other with the (source) port in *this.
*
* The source port will be copied, for each connection, if it was held by
* value inside *this, otherwise it will be connected as an lvalue.
*
* \returns std::tuple<port_connections...>
*/
template <class other_mux_port>
auto connect_mux(other_mux_port&& other, one_to_many_tag)
{
static_assert(
sizeof...(port_ts) == 1,
"(*this).ports should have a single port; if you are here, your logic must be wrong.");
using src_t = typename std::tuple_element<0, decltype(ports)>::type;
src_t&& src = std::get<0>(std::move(ports));
auto src_to_all = [&src](auto&& port)
{
return static_cast<src_t>(src) >> std::forward<decltype(port)>(port);
};
return fc::tuple::transform(std::forward<other_mux_port>(other).ports, src_to_all);
}
/** \brief Overload for connecting all ports in *this with a connectable.
*
* \param T the connectable - will be copied unless it is an lvalue.
* \returns mux_port<connection...> (or mux_port<port_connection...>)
*/
template <class T>
auto connect(T&& t, default_tag)
{
auto connect_to_copy = [&t](auto&& elem)
{
// t needs to be copied if it's not an lvalue ref, forward won't work because can't move
// from smth multiple times.
return std::forward<decltype(elem)>(elem) >> static_cast<T>(t);
};
return mux_from_tuple(fc::tuple::transform(std::move(ports), connect_to_copy));
}
public:
/// Function to forward to the correct connect overload based on the type of T.
template <class T>
auto operator>>(T&& t)
{
using decayed = std::decay_t<T>;
using tag = typename fc::port_traits<decayed>::mux_category;
return this->connect(std::forward<T>(t), tag{});
}
};
/// Connect src with all ports in mux. Useful only with event_sources.
template <class T, class... ports,
class = std::enable_if_t<is_active_source<std::remove_reference_t<T>>{} &&
detail::all<is_connectable<ports>{}...>()>>
auto operator>>(T&& src, mux_port<ports...> mux)
{
return mux_port<T>{std::forward_as_tuple(std::forward<T>(src))} >> std::move(mux);
}
/** \brief Create a mux port from lvalue references to the supplied ports.
*
* \params ports should be non-const lvalue references to ports.
*/
template <class... port_ts>
auto mux(port_ts&... ports)
{
return mux_port<std::remove_const_t<port_ts>&...>{std::tie(ports...)};
}
template <class... conn_ts>
mux_port<conn_ts...> mux_from_tuple(std::tuple<conn_ts...> tuple_)
{
return mux_port<conn_ts...>{std::move(tuple_)};
}
/// A merge port that is not connected to a mux_port yet. Think of this as a proxy.
template <class merge_op>
struct unloaded_merge_port
{
merge_op merge;
};
/** \brief A merge_port with a merge operation and a set of ports (connectables).
*
* If a connectable is held by value then loaded_merge_port is the owner of
* that connectable.
*/
template <class merge_op, class... port_ts>
struct loaded_merge_port
{
merge_op op;
std::tuple<port_ts...> ports;
auto operator()()
{
auto op = this->op;
auto call_and_apply = [op](auto&&... src)
{
return op(std::forward<decltype(src)>(src)()...);
};
return tuple::invoke_function(call_and_apply, ports,
std::make_index_sequence<sizeof...(port_ts)>{});
}
};
/// Create a merge_port proxy that only holds the merge operation.
template <class merge_op>
auto merge(merge_op op)
{
return unloaded_merge_port<merge_op>{op};
}
} // namespace fc
<|endoftext|>
|
<commit_before>//! Copyright (c) 2014 ASMlover. 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 ofconditions 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 materialsprovided with the
//! distribution.
//!
//! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
//! "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
//! LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
//! FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
//! COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//! INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
//! BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//! LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
//! CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
//! LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
//! ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//! POSSIBILITY OF SUCH DAMAGE.
#include "global.h"
#include "user_data.h"
#include "user_cache.h"
UserCache::UserCache(void)
: redis_(static_cast<redisContext*>(NULL)) {
}
UserCache::~UserCache(void) {
}
bool UserCache::Init(const char* addr, int port) {
struct timeval tv = {1, 500000};
redis_ = util::SmartPtr<redisContext>(
redisConnectWithTimeout(addr, port, tv),
redisFree);
if (NULL == redis_.Get() || 0 != redis_->err) {
fprintf(stderr, "Connect to redis-server %s:%d FAILED\n", addr, port);
return false;
}
return true;
}
void UserCache::Destroy(void) {
}
bool UserCache::Get(const std::string& account, UserData& data) {
return true;
}
bool UserCache::Set(const std::string& account, const UserData& data) {
return true;
}
bool UserCache::Del(const std::string& account) {
return true;
}
<commit_msg>implementation of global user cache<commit_after>//! Copyright (c) 2014 ASMlover. 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 ofconditions 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 materialsprovided with the
//! distribution.
//!
//! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
//! "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
//! LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
//! FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
//! COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//! INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
//! BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//! LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
//! CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
//! LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
//! ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//! POSSIBILITY OF SUCH DAMAGE.
#include "global.h"
#include "user_data.h"
#include "user_cache.h"
UserCache::UserCache(void)
: redis_(static_cast<redisContext*>(NULL)) {
}
UserCache::~UserCache(void) {
}
bool UserCache::Init(const char* addr, int port) {
struct timeval tv = {1, 500000};
redis_ = util::SmartPtr<redisContext>(
redisConnectWithTimeout(addr, port, tv),
redisFree);
if (NULL == redis_.Get() || 0 != redis_->err) {
fprintf(stderr, "Connect to redis-server %s:%d FAILED\n", addr, port);
return false;
}
return true;
}
void UserCache::Destroy(void) {
}
bool UserCache::Get(const std::string& account, UserData& data) {
util::SmartPtr<redisReply> reply(
static_cast<redisReply*>(redisCommand(
redis_.Get(), "exists %s", account.c_str())),
freeReplyObject);
if (NULL == reply.Get())
return false;
if (REDIS_REPLY_INTEGER != reply->type)
return false;
if (0 == reply->integer)
return false;
reply = util::SmartPtr<redisReply>(
static_cast<redisReply*>(redisCommand(
redis_.Get(),
"hmget %s "
"account "
"user_id "
"user_name "
"gender "
"face "
"level "
"exp "
"scores "
"coins "
"win_count "
"lost_count "
"flee_count "
"win_streak "
"play_time "
"login_count "
"reg_time "
"reg_addr "
"last_login_time "
"last_login_addr",
account.c_str())),
freeReplyObject);
if (REDIS_REPLY_ARRAY != reply->type)
return false;
data.account = reply->element[0]->str;
data.user_id = atoi(reply->element[1]->str);
data.user_name = reply->element[2]->str;
data.gender = static_cast<UserData::GenderType>(
atoi(reply->element[3]->str));
data.face = atoi(reply->element[4]->str);
data.level = atoi(reply->element[5]->str);
data.exp = atoi(reply->element[6]->str);
data.scores = atoi(reply->element[7]->str);
data.coins = atoi(reply->element[8]->str);
data.win_count = atoi(reply->element[9]->str);
data.lost_count = atoi(reply->element[10]->str);
data.flee_count = atoi(reply->element[11]->str);
data.win_streak = atoi(reply->element[12]->str);
data.play_time = atoi(reply->element[13]->str);
data.login_count = atoi(reply->element[14]->str);
data.reg_time = atoi(reply->element[15]->str);
data.reg_addr = atoi(reply->element[16]->str);
data.last_login_time = atoi(reply->element[17]->str);
data.last_login_addr = atoi(reply->element[18]->str);
return true;
}
bool UserCache::Set(const std::string& account, const UserData& data) {
util::SmartPtr<redisReply> reply(
static_cast<redisReply*>(redisCommand(
redis_.Get(),
"hmset %s "
"account %s "
"user_id %u "
"user_name %s "
"gender %u "
"face %u "
"level %u "
"exp %u "
"scores %u "
"coins %u "
"win_count %u "
"lost_counta %u "
"flee_count %u "
"win_streak %u "
"play_time %u "
"login_count %u "
"reg_time %u "
"reg_addr %u "
"last_login_time %u "
"last_login_addr %u",
data.account.c_str(),
data.user_id,
data.user_name.c_str(),
data.gender,
data.face,
data.level,
data.exp,
data.scores,
data.coins,
data.win_count,
data.lost_count,
data.flee_count,
data.win_streak,
data.play_time,
data.login_count,
data.reg_time,
data.reg_addr,
data.last_login_time,
data.last_login_addr)),
freeReplyObject);
if (0 == reply->len)
return false;
if (0 != strcmp("OK", reply->str))
return false;
return true;
}
bool UserCache::Del(const std::string& account) {
util::SmartPtr<redisReply> reply(
static_cast<redisReply*>(redisCommand(
redis_.Get(), "del %s", account.c_str())),
freeReplyObject);
return (1 == reply->integer);
}
<|endoftext|>
|
<commit_before>#pragma once
#include <bts/blockchain/types.hpp>
namespace bts { namespace blockchain {
static std::map<uint32_t, bts::blockchain::block_id_type> CHECKPOINT_BLOCKS
{
{ 1, bts::blockchain::block_id_type( "8523e28fde6eed4eb749a84e28c9c7b56870c9cc" ) },
{ 25001, bts::blockchain::block_id_type( "f5bbb4c5728d809e3d0877354964ea24e9961904" ) },
{ 120001, bts::blockchain::block_id_type( "1557fee97884c893aaebba9a1fed803e7fd005d9" ) },
{ 129601, bts::blockchain::block_id_type( "18bcec3430d35538470d7fddc2a51a28cb71fcde" ) },
{ 172718, bts::blockchain::block_id_type( "e452dd44902bc86110923285da03ac12e8cfbe6f" ) },
{ 173585, bts::blockchain::block_id_type( "1d1695bc8ebd3ebae0168007afb2912269adbef1" ) },
{ 187001, bts::blockchain::block_id_type( "72d06a6ba3e79c02327d8048852f9e51b6c8ea71" ) },
{ 237501, bts::blockchain::block_id_type( "42d7bb317f51082f7faffee3f7c79bf59f47acac" ) },
{ 549500, bts::blockchain::block_id_type( "e2e7d94a4076e051f882ee4587d3a1ba07b97db4" ) }
};
// Initialized in load_checkpoints()
static uint32_t LAST_CHECKPOINT_BLOCK_NUM = 0;
} } // bts::blockchain
<commit_msg>Update checkpoint<commit_after>#pragma once
#include <bts/blockchain/types.hpp>
namespace bts { namespace blockchain {
static std::map<uint32_t, bts::blockchain::block_id_type> CHECKPOINT_BLOCKS
{
{ 1, bts::blockchain::block_id_type( "8523e28fde6eed4eb749a84e28c9c7b56870c9cc" ) },
{ 25001, bts::blockchain::block_id_type( "f5bbb4c5728d809e3d0877354964ea24e9961904" ) },
{ 120001, bts::blockchain::block_id_type( "1557fee97884c893aaebba9a1fed803e7fd005d9" ) },
{ 129601, bts::blockchain::block_id_type( "18bcec3430d35538470d7fddc2a51a28cb71fcde" ) },
{ 172718, bts::blockchain::block_id_type( "e452dd44902bc86110923285da03ac12e8cfbe6f" ) },
{ 173585, bts::blockchain::block_id_type( "1d1695bc8ebd3ebae0168007afb2912269adbef1" ) },
{ 187001, bts::blockchain::block_id_type( "72d06a6ba3e79c02327d8048852f9e51b6c8ea71" ) },
{ 237501, bts::blockchain::block_id_type( "42d7bb317f51082f7faffee3f7c79bf59f47acac" ) },
{ 583500, bts::blockchain::block_id_type( "28daf0ea584f3988bf9449fe6119f9e69a4f0bb9" ) }
};
// Initialized in load_checkpoints()
static uint32_t LAST_CHECKPOINT_BLOCK_NUM = 0;
} } // bts::blockchain
<|endoftext|>
|
<commit_before>/**
* @file
*/
#include "bi/visitor/Resolver.hpp"
#include "bi/visitor/Gatherer.hpp"
#include "bi/exception/all.hpp"
bi::Resolver::Resolver(Scope* scope) :
inInputs(false),
membershipScope(nullptr) {
if (scope) {
push(scope);
}
}
bi::Resolver::~Resolver() {
//
}
void bi::Resolver::modify(File* o) {
if (o->state == File::RESOLVING) {
throw CyclicImportException(o);
} else if (o->state == File::UNRESOLVED) {
o->state = File::RESOLVING;
o->scope = new Scope();
files.push(o);
push(o->scope.get());
o->imports = o->imports->accept(this);
o->root = o->root->accept(this);
undefer();
pop();
files.pop();
o->state = File::RESOLVED;
}
}
bi::Expression* bi::Resolver::modify(ExpressionList* o) {
Modifier::modify(o);
o->type = new TypeList(o->head->type->accept(&cloner),
o->tail->type->accept(&cloner));
o->type = o->type->accept(this);
return o;
}
bi::Expression* bi::Resolver::modify(ParenthesesExpression* o) {
Modifier::modify(o);
o->type = new ParenthesesType(o->single->type->accept(&cloner));
o->type = o->type->accept(this);
return o;
}
bi::Expression* bi::Resolver::modify(Range* o) {
Modifier::modify(o);
return o;
}
bi::Expression* bi::Resolver::modify(Member* o) {
o->left = o->left->accept(this);
ModelReference* ref = dynamic_cast<ModelReference*>(o->left->type.get());
if (ref) {
membershipScope = ref->target->scope.get();
} else {
RandomType* random = dynamic_cast<RandomType*>(o->left->type.get());
if (random) {
membershipScope = random->scope.get();
}
}
if (!membershipScope) {
throw MemberException(o);
}
o->right = o->right->accept(this);
o->type = o->right->type->accept(&cloner)->accept(this);
return o;
}
bi::Expression* bi::Resolver::modify(This* o) {
if (!model()) {
throw ThisException(o);
} else {
Modifier::modify(o);
o->type = new ModelReference(model()->name, new EmptyExpression(),
nullptr, model());
}
return o;
}
bi::Expression* bi::Resolver::modify(BracketsExpression* o) {
Modifier::modify(o);
ModelReference* ref = dynamic_cast<ModelReference*>(o->single->type.get());
assert(ref); ///@todo Exception
const int typeSize = ref->ndims;
const int indexSize = o->brackets->tupleSize();
const int indexDims = o->brackets->tupleDims();
assert(typeSize == indexSize); ///@todo Exception
ref = new ModelReference(ref->name, indexDims);
o->type = ref->accept(this);
return o;
}
bi::Expression* bi::Resolver::modify(VarReference* o) {
Scope* membershipScope = takeMembershipScope();
Modifier::modify(o);
resolve(o, membershipScope);
o->type = o->target->type->accept(&cloner)->accept(this);
o->type->assignable = o->target->type->assignable;
/* substitute with random variable if possible */
RandomReference* random = new RandomReference(o);
try {
random->accept(this);
} catch (UnresolvedReferenceException e) {
delete random;
return o;
}
return random;
}
bi::Expression* bi::Resolver::modify(FuncReference* o) {
Scope* membershipScope = takeMembershipScope();
Modifier::modify(o);
resolve(o, membershipScope);
o->type = o->target->type->accept(&cloner)->accept(this);
o->form = o->target->form;
if (o->isAssignment()) {
if (inInputs) {
o->getLeft()->type->assignable = true;
} else if (!o->getLeft()->type->assignable) {
throw NotAssignableException(o);
}
}
Gatherer<VarParameter> gatherer;
o->target->parens->accept(&gatherer);
for (auto iter = gatherer.gathered.begin(); iter != gatherer.gathered.end();
++iter) {
o->args.push_back((*iter)->arg);
}
return o;
}
bi::Expression* bi::Resolver::modify(RandomReference* o) {
Scope* membershipScope = takeMembershipScope();
Modifier::modify(o);
resolve(o, membershipScope);
o->type = o->target->type->accept(&cloner)->accept(this);
o->type->assignable = true;
o->right->type = o->target->right->type->accept(&cloner)->accept(this);
return o;
}
bi::Type* bi::Resolver::modify(ModelReference* o) {
Scope* membershipScope = takeMembershipScope();
Modifier::modify(o);
resolve(o, membershipScope);
return o;
}
bi::Expression* bi::Resolver::modify(VarParameter* o) {
Modifier::modify(o);
if (!inInputs) {
o->type->assignable = true;
}
if (!o->name->isEmpty()) {
top()->add(o);
}
return o;
}
bi::Expression* bi::Resolver::modify(FuncParameter* o) {
push();
inInputs = true;
o->parens = o->parens->accept(this);
inInputs = false;
o->result = o->result->accept(this);
o->type = o->result->type->accept(&cloner)->accept(this);
defer(o->braces.get());
o->scope = pop();
top()->add(o);
if (o->isAssignment()) {
o->getLeft()->type->assignable = true;
}
Gatherer<VarParameter> gatherer1;
o->parens->accept(&gatherer1);
o->inputs = gatherer1.gathered;
Gatherer<VarParameter> gatherer2;
o->result->accept(&gatherer2);
o->outputs = gatherer2.gathered;
return o;
}
bi::Expression* bi::Resolver::modify(RandomParameter* o) {
Modifier::modify(o);
if (!inInputs && !o->left->type->assignable) {
throw NotAssignableException(o->left.get());
} else {
o->left->type->assignable = true;
}
o->right->type->assignable = true;
o->type = new RandomType(o->left->type->accept(&cloner),
o->right->type->accept(&cloner));
o->type->accept(this);
if (!inInputs) {
o->pull = new FuncReference(o->left->accept(&cloner), new Name("<~"),
o->right->accept(&cloner));
o->pull->accept(this);
o->push = new FuncReference(o->left->accept(&cloner), new Name("~>"),
o->right->accept(&cloner));
o->push->accept(this);
}
top()->add(o);
return o;
}
bi::Prog* bi::Resolver::modify(ProgParameter* o) {
push();
o->parens = o->parens->accept(this);
defer(o->braces.get());
o->scope = pop();
top()->add(o);
Gatherer<VarParameter> gatherer1;
o->parens->accept(&gatherer1);
o->inputs = gatherer1.gathered;
return o;
}
bi::Type* bi::Resolver::modify(ModelParameter* o) {
push();
o->parens = o->parens->accept(this);
o->base = o->base->accept(this);
models.push(o);
o->braces = o->braces->accept(this);
models.pop();
o->scope = pop();
top()->add(o);
if (*o->op != "=") {
/* create constructor */
Expression* parens1 = o->parens->accept(&cloner);
VarParameter* result1 = new VarParameter(new Name(),
new ModelReference(o->name, 0, o));
o->constructor = new FuncParameter(o->name, parens1, result1,
new EmptyExpression(), CONSTRUCTOR);
o->constructor =
dynamic_cast<FuncParameter*>(o->constructor->accept(this));
assert(o->constructor);
/* create assignment operator */
Expression* right = new VarParameter(new Name(),
new ModelReference(o->name, 0, o));
Expression* left = new VarParameter(new Name(),
new ModelReference(o->name, 0, o));
Expression* parens2 = new ParenthesesExpression(
new ExpressionList(left, right));
Expression* result2 = new VarParameter(new Name(),
new ModelReference(o->name, 0, o));
o->assignment = new FuncParameter(new Name("<-"), parens2, result2,
new EmptyExpression(), ASSIGNMENT_OPERATOR);
o->assignment = dynamic_cast<FuncParameter*>(o->assignment->accept(this));
assert(o->assignment);
}
return o;
}
bi::Statement* bi::Resolver::modify(Import* o) {
o->file->accept(this);
top()->import(o->file->scope.get());
return o;
}
bi::Statement* bi::Resolver::modify(VarDeclaration* o) {
Modifier::modify(o);
o->param->type->assignable = true;
return o;
}
bi::Statement* bi::Resolver::modify(Conditional* o) {
push();
Modifier::modify(o);
o->scope = pop();
///@todo Check that condition is of type Boolean
return o;
}
bi::Statement* bi::Resolver::modify(Loop* o) {
push();
Modifier::modify(o);
o->scope = pop();
///@todo Check that condition is of type Boolean
return o;
}
bi::Type* bi::Resolver::modify(RandomType* o) {
push();
Modifier::modify(o);
o->x = new VarParameter(new Name("x"), o->left->accept(&cloner));
o->x->accept(this);
o->m = new VarParameter(new Name("m"), o->right->accept(&cloner));
o->m->accept(this);
o->scope = pop();
return o;
}
bi::Scope* bi::Resolver::takeMembershipScope() {
Scope* scope = membershipScope;
membershipScope = nullptr;
return scope;
}
bi::Scope* bi::Resolver::top() {
return scopes.back();
}
void bi::Resolver::push(Scope* scope) {
if (scope) {
scopes.push_back(scope);
} else {
scopes.push_back(new Scope());
}
}
bi::Scope* bi::Resolver::pop() {
/* pre-conditions */
assert(scopes.size() > 0);
Scope* res = scopes.back();
scopes.pop_back();
return res;
}
template<class ReferenceType>
void bi::Resolver::resolve(ReferenceType* ref, Scope* scope) {
if (scope) {
/* use provided scope, usually a membership scope */
ref->target = scope->resolve(ref);
} else {
/* use current stack of scopes */
ref->target = nullptr;
for (auto iter = scopes.rbegin(); !ref->target && iter != scopes.rend();
++iter) {
ref->target = (*iter)->resolve(ref);
}
}
if (!ref->target) {
throw UnresolvedReferenceException(ref);
}
}
void bi::Resolver::defer(Expression* o) {
if (files.size() == 1) {
/* can ignore bodies in imported files */
defers.push_back(std::make_tuple(o, top(), model()));
}
}
void bi::Resolver::undefer() {
if (files.size() == 1) {
auto iter = defers.begin();
while (iter != defers.end()) {
auto o = std::get<0>(*iter);
auto scope = std::get<1>(*iter);
auto model = std::get<2>(*iter);
push(scope);
models.push(model);
o->accept(this);
models.pop();
pop();
++iter;
}
defers.clear();
}
}
bi::ModelParameter* bi::Resolver::model() {
if (models.empty()) {
return nullptr;
} else {
return models.top();
}
}
template void bi::Resolver::resolve(VarReference* ref, Scope* scope);
template void bi::Resolver::resolve(FuncReference* ref, Scope* scope);
template void bi::Resolver::resolve(RandomReference* ref, Scope* scope);
template void bi::Resolver::resolve(ModelReference* ref, Scope* scope);
<commit_msg>Member accesses (e.g. `m.x`) now inherit assignability of the object (i.e. `m`).<commit_after>/**
* @file
*/
#include "bi/visitor/Resolver.hpp"
#include "bi/visitor/Gatherer.hpp"
#include "bi/exception/all.hpp"
bi::Resolver::Resolver(Scope* scope) :
inInputs(false),
membershipScope(nullptr) {
if (scope) {
push(scope);
}
}
bi::Resolver::~Resolver() {
//
}
void bi::Resolver::modify(File* o) {
if (o->state == File::RESOLVING) {
throw CyclicImportException(o);
} else if (o->state == File::UNRESOLVED) {
o->state = File::RESOLVING;
o->scope = new Scope();
files.push(o);
push(o->scope.get());
o->imports = o->imports->accept(this);
o->root = o->root->accept(this);
undefer();
pop();
files.pop();
o->state = File::RESOLVED;
}
}
bi::Expression* bi::Resolver::modify(ExpressionList* o) {
Modifier::modify(o);
o->type = new TypeList(o->head->type->accept(&cloner),
o->tail->type->accept(&cloner));
o->type = o->type->accept(this);
return o;
}
bi::Expression* bi::Resolver::modify(ParenthesesExpression* o) {
Modifier::modify(o);
o->type = new ParenthesesType(o->single->type->accept(&cloner));
o->type = o->type->accept(this);
return o;
}
bi::Expression* bi::Resolver::modify(Range* o) {
Modifier::modify(o);
return o;
}
bi::Expression* bi::Resolver::modify(Member* o) {
o->left = o->left->accept(this);
ModelReference* ref = dynamic_cast<ModelReference*>(o->left->type.get());
if (ref) {
membershipScope = ref->target->scope.get();
} else {
RandomType* random = dynamic_cast<RandomType*>(o->left->type.get());
if (random) {
membershipScope = random->scope.get();
}
}
if (!membershipScope) {
throw MemberException(o);
}
o->right = o->right->accept(this);
o->right->type->assignable = o->left->type->assignable;
o->type = o->right->type->accept(&cloner)->accept(this);
o->type->assignable = o->right->type->assignable;
return o;
}
bi::Expression* bi::Resolver::modify(This* o) {
if (!model()) {
throw ThisException(o);
} else {
Modifier::modify(o);
o->type = new ModelReference(model()->name, new EmptyExpression(),
nullptr, model());
}
return o;
}
bi::Expression* bi::Resolver::modify(BracketsExpression* o) {
Modifier::modify(o);
ModelReference* ref = dynamic_cast<ModelReference*>(o->single->type.get());
assert(ref); ///@todo Exception
const int typeSize = ref->ndims;
const int indexSize = o->brackets->tupleSize();
const int indexDims = o->brackets->tupleDims();
assert(typeSize == indexSize); ///@todo Exception
ref = new ModelReference(ref->name, indexDims);
o->type = ref->accept(this);
return o;
}
bi::Expression* bi::Resolver::modify(VarReference* o) {
Scope* membershipScope = takeMembershipScope();
Modifier::modify(o);
resolve(o, membershipScope);
o->type = o->target->type->accept(&cloner)->accept(this);
o->type->assignable = o->target->type->assignable;
/* substitute with random variable if possible */
RandomReference* random = new RandomReference(o);
try {
random->accept(this);
} catch (UnresolvedReferenceException e) {
delete random;
return o;
}
return random;
}
bi::Expression* bi::Resolver::modify(FuncReference* o) {
Scope* membershipScope = takeMembershipScope();
Modifier::modify(o);
resolve(o, membershipScope);
o->type = o->target->type->accept(&cloner)->accept(this);
o->form = o->target->form;
if (o->isAssignment()) {
if (inInputs) {
o->getLeft()->type->assignable = true;
} else if (!o->getLeft()->type->assignable) {
throw NotAssignableException(o);
}
}
Gatherer<VarParameter> gatherer;
o->target->parens->accept(&gatherer);
for (auto iter = gatherer.gathered.begin(); iter != gatherer.gathered.end();
++iter) {
o->args.push_back((*iter)->arg);
}
return o;
}
bi::Expression* bi::Resolver::modify(RandomReference* o) {
Scope* membershipScope = takeMembershipScope();
Modifier::modify(o);
resolve(o, membershipScope);
o->type = o->target->type->accept(&cloner)->accept(this);
o->type->assignable = true;
o->right->type = o->target->right->type->accept(&cloner)->accept(this);
return o;
}
bi::Type* bi::Resolver::modify(ModelReference* o) {
Scope* membershipScope = takeMembershipScope();
Modifier::modify(o);
resolve(o, membershipScope);
return o;
}
bi::Expression* bi::Resolver::modify(VarParameter* o) {
Modifier::modify(o);
if (!inInputs) {
o->type->assignable = true;
}
if (!o->name->isEmpty()) {
top()->add(o);
}
return o;
}
bi::Expression* bi::Resolver::modify(FuncParameter* o) {
push();
inInputs = true;
o->parens = o->parens->accept(this);
inInputs = false;
o->result = o->result->accept(this);
o->type = o->result->type->accept(&cloner)->accept(this);
defer(o->braces.get());
o->scope = pop();
top()->add(o);
if (o->isAssignment()) {
o->getLeft()->type->assignable = true;
}
Gatherer<VarParameter> gatherer1;
o->parens->accept(&gatherer1);
o->inputs = gatherer1.gathered;
Gatherer<VarParameter> gatherer2;
o->result->accept(&gatherer2);
o->outputs = gatherer2.gathered;
return o;
}
bi::Expression* bi::Resolver::modify(RandomParameter* o) {
Modifier::modify(o);
if (!inInputs && !o->left->type->assignable) {
throw NotAssignableException(o->left.get());
} else {
o->left->type->assignable = true;
}
o->right->type->assignable = true;
o->type = new RandomType(o->left->type->accept(&cloner),
o->right->type->accept(&cloner));
o->type->accept(this);
if (!inInputs) {
o->pull = new FuncReference(o->left->accept(&cloner), new Name("<~"),
o->right->accept(&cloner));
o->pull->accept(this);
o->push = new FuncReference(o->left->accept(&cloner), new Name("~>"),
o->right->accept(&cloner));
o->push->accept(this);
}
top()->add(o);
return o;
}
bi::Prog* bi::Resolver::modify(ProgParameter* o) {
push();
o->parens = o->parens->accept(this);
defer(o->braces.get());
o->scope = pop();
top()->add(o);
Gatherer<VarParameter> gatherer1;
o->parens->accept(&gatherer1);
o->inputs = gatherer1.gathered;
return o;
}
bi::Type* bi::Resolver::modify(ModelParameter* o) {
push();
o->parens = o->parens->accept(this);
o->base = o->base->accept(this);
models.push(o);
o->braces = o->braces->accept(this);
models.pop();
o->scope = pop();
top()->add(o);
if (*o->op != "=") {
/* create constructor */
Expression* parens1 = o->parens->accept(&cloner);
VarParameter* result1 = new VarParameter(new Name(),
new ModelReference(o->name, 0, o));
o->constructor = new FuncParameter(o->name, parens1, result1,
new EmptyExpression(), CONSTRUCTOR);
o->constructor =
dynamic_cast<FuncParameter*>(o->constructor->accept(this));
assert(o->constructor);
/* create assignment operator */
Expression* right = new VarParameter(new Name(),
new ModelReference(o->name, 0, o));
Expression* left = new VarParameter(new Name(),
new ModelReference(o->name, 0, o));
Expression* parens2 = new ParenthesesExpression(
new ExpressionList(left, right));
Expression* result2 = new VarParameter(new Name(),
new ModelReference(o->name, 0, o));
o->assignment = new FuncParameter(new Name("<-"), parens2, result2,
new EmptyExpression(), ASSIGNMENT_OPERATOR);
o->assignment = dynamic_cast<FuncParameter*>(o->assignment->accept(this));
assert(o->assignment);
}
return o;
}
bi::Statement* bi::Resolver::modify(Import* o) {
o->file->accept(this);
top()->import(o->file->scope.get());
return o;
}
bi::Statement* bi::Resolver::modify(VarDeclaration* o) {
Modifier::modify(o);
o->param->type->assignable = true;
return o;
}
bi::Statement* bi::Resolver::modify(Conditional* o) {
push();
Modifier::modify(o);
o->scope = pop();
///@todo Check that condition is of type Boolean
return o;
}
bi::Statement* bi::Resolver::modify(Loop* o) {
push();
Modifier::modify(o);
o->scope = pop();
///@todo Check that condition is of type Boolean
return o;
}
bi::Type* bi::Resolver::modify(RandomType* o) {
push();
Modifier::modify(o);
o->x = new VarParameter(new Name("x"), o->left->accept(&cloner));
o->x->accept(this);
o->m = new VarParameter(new Name("m"), o->right->accept(&cloner));
o->m->accept(this);
o->scope = pop();
return o;
}
bi::Scope* bi::Resolver::takeMembershipScope() {
Scope* scope = membershipScope;
membershipScope = nullptr;
return scope;
}
bi::Scope* bi::Resolver::top() {
return scopes.back();
}
void bi::Resolver::push(Scope* scope) {
if (scope) {
scopes.push_back(scope);
} else {
scopes.push_back(new Scope());
}
}
bi::Scope* bi::Resolver::pop() {
/* pre-conditions */
assert(scopes.size() > 0);
Scope* res = scopes.back();
scopes.pop_back();
return res;
}
template<class ReferenceType>
void bi::Resolver::resolve(ReferenceType* ref, Scope* scope) {
if (scope) {
/* use provided scope, usually a membership scope */
ref->target = scope->resolve(ref);
} else {
/* use current stack of scopes */
ref->target = nullptr;
for (auto iter = scopes.rbegin(); !ref->target && iter != scopes.rend();
++iter) {
ref->target = (*iter)->resolve(ref);
}
}
if (!ref->target) {
throw UnresolvedReferenceException(ref);
}
}
void bi::Resolver::defer(Expression* o) {
if (files.size() == 1) {
/* can ignore bodies in imported files */
defers.push_back(std::make_tuple(o, top(), model()));
}
}
void bi::Resolver::undefer() {
if (files.size() == 1) {
auto iter = defers.begin();
while (iter != defers.end()) {
auto o = std::get<0>(*iter);
auto scope = std::get<1>(*iter);
auto model = std::get<2>(*iter);
push(scope);
models.push(model);
o->accept(this);
models.pop();
pop();
++iter;
}
defers.clear();
}
}
bi::ModelParameter* bi::Resolver::model() {
if (models.empty()) {
return nullptr;
} else {
return models.top();
}
}
template void bi::Resolver::resolve(VarReference* ref, Scope* scope);
template void bi::Resolver::resolve(FuncReference* ref, Scope* scope);
template void bi::Resolver::resolve(RandomReference* ref, Scope* scope);
template void bi::Resolver::resolve(ModelReference* ref, Scope* scope);
<|endoftext|>
|
<commit_before>//
// Projectname: amos-ss16-proj5
//
// Copyright (c) 2016 de.fau.cs.osr.amos2016.gruppe5
//
// This file is part of the AMOS Project 2016 @ FAU
// (Friedrich-Alexander University Erlangen-Nürnberg)
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public
// License along with this program. If not, see
// <http://www.gnu.org/licenses/>.
//
#include <opencv2/opencv.hpp>
using namespace cv;
void detectAndDisplay(cv::Mat *image);
const int KEY_ESC = 27;
HOGDescriptor hog;
int main (int argc, const char * argv[])
{
if(argc < 2){
std::cout << "Usage " << argv[0] << " video.mp4" << std::endl;
return 0;
}
//set hog detector
// TO DO: test the daimler detector again with proper settings
hog.setSVMDetector(cv::HOGDescriptor::getDefaultPeopleDetector());
//open video
cv::VideoCapture capture(argv[1]);
if (!capture.isOpened()){
std::cout << "Failed to open video" << std::endl;
return -1;
}
//run video
cv::Mat frame;
do{
if (!capture.read(frame))
break;
detectAndDisplay(&frame);
char key = cvWaitKey(10);
if (key == KEY_ESC)
break;
} while(1);
return 0;
}
void detectAndDisplay(cv::Mat *frame){
//resize the image to width of 400px to reduce detection time and improve detection accuracy
//0.3125 is used because the test video is 1280 x 720, so the width resized images is 400px this has to be changed to our image size (best would be no hard coded scaling so other images sizes work too!)
cv::Mat resizedImage;
resize(*frame, resizedImage, Size(0, 0), 0.3125, 0.3125, CV_INTER_AREA);
//detect people in the resizedImage
std::vector<Rect> foundHumans;
hog.detectMultiScale(resizedImage, foundHumans, 0.35, Size(4,4), Size(16,16), 1.04, 1);
//add retangle to found humans
for (int i=0; i<foundHumans.size(); i++){
Rect r = foundHumans[i];
rectangle(resizedImage, r.tl(), r.br(), Scalar(0,255,0), 2);
}
imshow("demo", resizedImage);
}
<commit_msg>you can now stop the stream by pressing space<commit_after>//
// Projectname: amos-ss16-proj5
//
// Copyright (c) 2016 de.fau.cs.osr.amos2016.gruppe5
//
// This file is part of the AMOS Project 2016 @ FAU
// (Friedrich-Alexander University Erlangen-Nürnberg)
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public
// License along with this program. If not, see
// <http://www.gnu.org/licenses/>.
//
#include <opencv2/opencv.hpp>
using namespace cv;
void detectAndDisplay(cv::Mat *image);
const int KEY_ESC = 27;
const int KEY_SPACE = 32;
HOGDescriptor hog;
int main (int argc, const char * argv[])
{
if(argc < 2){
std::cout << "Usage " << argv[0] << " video.mp4" << std::endl;
return 0;
}
//set hog detector
// TO DO: test the daimler detector again with proper settings
hog.setSVMDetector(cv::HOGDescriptor::getDefaultPeopleDetector());
//open video
cv::VideoCapture capture(argv[1]);
if (!capture.isOpened()){
std::cout << "Failed to open video" << std::endl;
return -1;
}
//run video
cv::Mat frame;
do{
if (!capture.read(frame))
break;
detectAndDisplay(&frame);
char key = cvWaitKey(10);
if (key == KEY_SPACE)
key = cvWaitKey(0);
if (key == KEY_ESC)
break;
} while(1);
return 0;
}
void detectAndDisplay(cv::Mat *frame){
//resize the image to width of 400px to reduce detection time and improve detection accuracy
//0.3125 is used because the test video is 1280 x 720, so the width resized images is 400px this has to be changed to our image size (best would be no hard coded scaling so other images sizes work too!)
cv::Mat resizedImage;
resize(*frame, resizedImage, Size(0, 0), 0.3125, 0.3125, CV_INTER_AREA);
//detect people in the resizedImage
std::vector<Rect> foundHumans;
hog.detectMultiScale(resizedImage, foundHumans, 0.35, Size(4,4), Size(16,16), 1.04, 1);
//add retangle to found humans
for (int i=0; i<foundHumans.size(); i++){
Rect r = foundHumans[i];
rectangle(resizedImage, r.tl(), r.br(), Scalar(0,255,0), 2);
}
imshow("demo", resizedImage);
}
<|endoftext|>
|
<commit_before>/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* Written (W) 1999-2009 Soeren Sonnenburg
* Written (W) 2011-2012 Heiko Strathmann
* Copyright (C) 1999-2009 Fraunhofer Institute FIRST and Max-Planck-Society
*/
#include <shogun/machine/Machine.h>
#include <shogun/base/Parameter.h>
#include <shogun/mathematics/Math.h>
#include <shogun/base/ParameterMap.h>
using namespace shogun;
CMachine::CMachine() : CSGObject(), m_max_train_time(0), m_labels(NULL),
m_solver_type(ST_AUTO)
{
m_data_locked=false;
m_store_model_features=false;
SG_ADD(&m_max_train_time, "max_train_time",
"Maximum training time.", MS_NOT_AVAILABLE);
SG_ADD((machine_int_t*) &m_solver_type, "solver_type",
"Type of solver.", MS_NOT_AVAILABLE);
SG_ADD((CSGObject**) &m_labels, "labels",
"Labels to be used.", MS_NOT_AVAILABLE);
SG_ADD(&m_store_model_features, "store_model_features",
"Should feature data of model be stored after training?", MS_NOT_AVAILABLE);
SG_ADD(&m_data_locked, "data_locked",
"Indicates whether data is locked", MS_NOT_AVAILABLE);
m_parameter_map->put(
new SGParamInfo("data_locked", CT_SCALAR, ST_NONE, PT_BOOL, 1),
new SGParamInfo()
);
m_parameter_map->finalize_map();
}
CMachine::~CMachine()
{
SG_UNREF(m_labels);
}
bool CMachine::train(CFeatures* data)
{
/* not allowed to train on locked data */
if (m_data_locked)
{
SG_ERROR("%s::train data_lock() was called, only train_locked() is"
" possible. Call data_unlock if you want to call train()\n",
get_name());
}
if (train_require_labels())
{
if (m_labels == NULL)
SG_ERROR("%s@%p: No labels given", get_name(), this);
m_labels->ensure_valid(get_name());
}
bool result = train_machine(data);
if (m_store_model_features)
store_model_features();
return result;
}
void CMachine::set_labels(CLabels* lab)
{
if (lab != NULL)
if (!is_label_valid(lab))
SG_ERROR("Invalid label for %s", get_name());
SG_UNREF(m_labels);
SG_REF(lab);
m_labels = lab;
}
CLabels* CMachine::get_labels()
{
SG_REF(m_labels);
return m_labels;
}
void CMachine::set_max_train_time(float64_t t)
{
m_max_train_time = t;
}
float64_t CMachine::get_max_train_time()
{
return m_max_train_time;
}
EMachineType CMachine::get_classifier_type()
{
return CT_NONE;
}
void CMachine::set_solver_type(ESolverType st)
{
m_solver_type = st;
}
ESolverType CMachine::get_solver_type()
{
return m_solver_type;
}
void CMachine::set_store_model_features(bool store_model)
{
m_store_model_features = store_model;
}
void CMachine::data_lock(CLabels* labs, CFeatures* features)
{
SG_DEBUG("entering %s::data_lock\n", get_name());
if (!supports_locking())
{
{
SG_ERROR("%s::data_lock(): Machine does not support data locking!\n",
get_name());
}
}
if (!labs)
{
SG_ERROR("%s::data_lock() is not possible will NULL labels!\n",
get_name());
}
/* first set labels */
set_labels(labs);
if (m_data_locked)
{
SG_ERROR("%s::data_lock() was already called. Dont lock twice!",
get_name());
}
m_data_locked=true;
post_lock(labs,features);
SG_DEBUG("leaving %s::data_lock\n", get_name());
}
void CMachine::data_unlock()
{
SG_DEBUG("entering %s::data_lock\n", get_name());
if (m_data_locked)
m_data_locked=false;
SG_DEBUG("leaving %s::data_lock\n", get_name());
}
CLabels* CMachine::apply(CFeatures* data)
{
SG_DEBUG("entering %s::apply(%s at %p)\n",
get_name(), data ? data->get_name() : "NULL", data);
CLabels* result=NULL;
switch (get_machine_problem_type())
{
case PT_BINARY:
result=apply_binary(data);
break;
case PT_REGRESSION:
result=apply_regression(data);
break;
case PT_MULTICLASS:
result=apply_multiclass(data);
break;
case PT_STRUCTURED:
result=apply_structured(data);
break;
default:
SG_ERROR("Unknown problem type");
break;
}
SG_DEBUG("leaving %s::apply(%s at %p)\n",
get_name(), data ? data->get_name() : "NULL", data);
return result;
}
CLabels* CMachine::apply_locked(SGVector<index_t> indices)
{
switch (get_machine_problem_type())
{
case PT_BINARY:
return apply_locked_binary(indices);
case PT_REGRESSION:
return apply_locked_regression(indices);
case PT_MULTICLASS:
return apply_locked_multiclass(indices);
case PT_STRUCTURED:
return apply_locked_structured(indices);
case PT_LATENT:
return apply_locked_latent(indices);
default:
SG_ERROR("Unknown problem type");
break;
}
return NULL;
}
CBinaryLabels* CMachine::apply_binary(CFeatures* data)
{
SG_ERROR("This machine does not support apply_binary()\n");
return NULL;
}
CRegressionLabels* CMachine::apply_regression(CFeatures* data)
{
SG_ERROR("This machine does not support apply_regression()\n");
return NULL;
}
CMulticlassLabels* CMachine::apply_multiclass(CFeatures* data)
{
SG_ERROR("This machine does not support apply_multiclass()\n");
return NULL;
}
CStructuredLabels* CMachine::apply_structured(CFeatures* data)
{
SG_ERROR("This machine does not support apply_structured()\n");
return NULL;
}
CLatentLabels* CMachine::apply_latent(CFeatures* data)
{
SG_ERROR("This machine does not support apply_latent()\n");
return NULL;
}
CBinaryLabels* CMachine::apply_locked_binary(SGVector<index_t> indices)
{
SG_ERROR("apply_locked_binary(SGVector<index_t>) is not yet implemented "
"for %s\n", get_name());
return NULL;
}
CRegressionLabels* CMachine::apply_locked_regression(SGVector<index_t> indices)
{
SG_ERROR("apply_locked_regression(SGVector<index_t>) is not yet implemented "
"for %s\n", get_name());
return NULL;
}
CMulticlassLabels* CMachine::apply_locked_multiclass(SGVector<index_t> indices)
{
SG_ERROR("apply_locked_multiclass(SGVector<index_t>) is not yet implemented "
"for %s\n", get_name());
return NULL;
}
CStructuredLabels* CMachine::apply_locked_structured(SGVector<index_t> indices)
{
SG_ERROR("apply_locked_structured(SGVector<index_t>) is not yet implemented "
"for %s\n", get_name());
return NULL;
}
CLatentLabels* CMachine::apply_locked_latent(SGVector<index_t> indices)
{
SG_ERROR("apply_locked_latent(SGVector<index_t>) is not yet implemented "
"for %s\n", get_name());
return NULL;
}
<commit_msg>Added missed latent problem handling in apply of machine<commit_after>/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* Written (W) 1999-2009 Soeren Sonnenburg
* Written (W) 2011-2012 Heiko Strathmann
* Copyright (C) 1999-2009 Fraunhofer Institute FIRST and Max-Planck-Society
*/
#include <shogun/machine/Machine.h>
#include <shogun/base/Parameter.h>
#include <shogun/mathematics/Math.h>
#include <shogun/base/ParameterMap.h>
using namespace shogun;
CMachine::CMachine() : CSGObject(), m_max_train_time(0), m_labels(NULL),
m_solver_type(ST_AUTO)
{
m_data_locked=false;
m_store_model_features=false;
SG_ADD(&m_max_train_time, "max_train_time",
"Maximum training time.", MS_NOT_AVAILABLE);
SG_ADD((machine_int_t*) &m_solver_type, "solver_type",
"Type of solver.", MS_NOT_AVAILABLE);
SG_ADD((CSGObject**) &m_labels, "labels",
"Labels to be used.", MS_NOT_AVAILABLE);
SG_ADD(&m_store_model_features, "store_model_features",
"Should feature data of model be stored after training?", MS_NOT_AVAILABLE);
SG_ADD(&m_data_locked, "data_locked",
"Indicates whether data is locked", MS_NOT_AVAILABLE);
m_parameter_map->put(
new SGParamInfo("data_locked", CT_SCALAR, ST_NONE, PT_BOOL, 1),
new SGParamInfo()
);
m_parameter_map->finalize_map();
}
CMachine::~CMachine()
{
SG_UNREF(m_labels);
}
bool CMachine::train(CFeatures* data)
{
/* not allowed to train on locked data */
if (m_data_locked)
{
SG_ERROR("%s::train data_lock() was called, only train_locked() is"
" possible. Call data_unlock if you want to call train()\n",
get_name());
}
if (train_require_labels())
{
if (m_labels == NULL)
SG_ERROR("%s@%p: No labels given", get_name(), this);
m_labels->ensure_valid(get_name());
}
bool result = train_machine(data);
if (m_store_model_features)
store_model_features();
return result;
}
void CMachine::set_labels(CLabels* lab)
{
if (lab != NULL)
if (!is_label_valid(lab))
SG_ERROR("Invalid label for %s", get_name());
SG_UNREF(m_labels);
SG_REF(lab);
m_labels = lab;
}
CLabels* CMachine::get_labels()
{
SG_REF(m_labels);
return m_labels;
}
void CMachine::set_max_train_time(float64_t t)
{
m_max_train_time = t;
}
float64_t CMachine::get_max_train_time()
{
return m_max_train_time;
}
EMachineType CMachine::get_classifier_type()
{
return CT_NONE;
}
void CMachine::set_solver_type(ESolverType st)
{
m_solver_type = st;
}
ESolverType CMachine::get_solver_type()
{
return m_solver_type;
}
void CMachine::set_store_model_features(bool store_model)
{
m_store_model_features = store_model;
}
void CMachine::data_lock(CLabels* labs, CFeatures* features)
{
SG_DEBUG("entering %s::data_lock\n", get_name());
if (!supports_locking())
{
{
SG_ERROR("%s::data_lock(): Machine does not support data locking!\n",
get_name());
}
}
if (!labs)
{
SG_ERROR("%s::data_lock() is not possible will NULL labels!\n",
get_name());
}
/* first set labels */
set_labels(labs);
if (m_data_locked)
{
SG_ERROR("%s::data_lock() was already called. Dont lock twice!",
get_name());
}
m_data_locked=true;
post_lock(labs,features);
SG_DEBUG("leaving %s::data_lock\n", get_name());
}
void CMachine::data_unlock()
{
SG_DEBUG("entering %s::data_lock\n", get_name());
if (m_data_locked)
m_data_locked=false;
SG_DEBUG("leaving %s::data_lock\n", get_name());
}
CLabels* CMachine::apply(CFeatures* data)
{
SG_DEBUG("entering %s::apply(%s at %p)\n",
get_name(), data ? data->get_name() : "NULL", data);
CLabels* result=NULL;
switch (get_machine_problem_type())
{
case PT_BINARY:
result=apply_binary(data);
break;
case PT_REGRESSION:
result=apply_regression(data);
break;
case PT_MULTICLASS:
result=apply_multiclass(data);
break;
case PT_STRUCTURED:
result=apply_structured(data);
break;
case PT_LATENT:
result=apply_latent(data);
break;
default:
SG_ERROR("Unknown problem type");
break;
}
SG_DEBUG("leaving %s::apply(%s at %p)\n",
get_name(), data ? data->get_name() : "NULL", data);
return result;
}
CLabels* CMachine::apply_locked(SGVector<index_t> indices)
{
switch (get_machine_problem_type())
{
case PT_BINARY:
return apply_locked_binary(indices);
case PT_REGRESSION:
return apply_locked_regression(indices);
case PT_MULTICLASS:
return apply_locked_multiclass(indices);
case PT_STRUCTURED:
return apply_locked_structured(indices);
case PT_LATENT:
return apply_locked_latent(indices);
default:
SG_ERROR("Unknown problem type");
break;
}
return NULL;
}
CBinaryLabels* CMachine::apply_binary(CFeatures* data)
{
SG_ERROR("This machine does not support apply_binary()\n");
return NULL;
}
CRegressionLabels* CMachine::apply_regression(CFeatures* data)
{
SG_ERROR("This machine does not support apply_regression()\n");
return NULL;
}
CMulticlassLabels* CMachine::apply_multiclass(CFeatures* data)
{
SG_ERROR("This machine does not support apply_multiclass()\n");
return NULL;
}
CStructuredLabels* CMachine::apply_structured(CFeatures* data)
{
SG_ERROR("This machine does not support apply_structured()\n");
return NULL;
}
CLatentLabels* CMachine::apply_latent(CFeatures* data)
{
SG_ERROR("This machine does not support apply_latent()\n");
return NULL;
}
CBinaryLabels* CMachine::apply_locked_binary(SGVector<index_t> indices)
{
SG_ERROR("apply_locked_binary(SGVector<index_t>) is not yet implemented "
"for %s\n", get_name());
return NULL;
}
CRegressionLabels* CMachine::apply_locked_regression(SGVector<index_t> indices)
{
SG_ERROR("apply_locked_regression(SGVector<index_t>) is not yet implemented "
"for %s\n", get_name());
return NULL;
}
CMulticlassLabels* CMachine::apply_locked_multiclass(SGVector<index_t> indices)
{
SG_ERROR("apply_locked_multiclass(SGVector<index_t>) is not yet implemented "
"for %s\n", get_name());
return NULL;
}
CStructuredLabels* CMachine::apply_locked_structured(SGVector<index_t> indices)
{
SG_ERROR("apply_locked_structured(SGVector<index_t>) is not yet implemented "
"for %s\n", get_name());
return NULL;
}
CLatentLabels* CMachine::apply_locked_latent(SGVector<index_t> indices)
{
SG_ERROR("apply_locked_latent(SGVector<index_t>) is not yet implemented "
"for %s\n", get_name());
return NULL;
}
<|endoftext|>
|
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: http://www.qt-project.org/
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**************************************************************************/
#include "nodeinstanceserverinterface.h"
#include <qmetatype.h>
#include "propertyabstractcontainer.h"
#include "propertyvaluecontainer.h"
#include "propertybindingcontainer.h"
#include "instancecontainer.h"
#include "createinstancescommand.h"
#include "createscenecommand.h"
#include "changevaluescommand.h"
#include "changebindingscommand.h"
#include "changeauxiliarycommand.h"
#include "changefileurlcommand.h"
#include "removeinstancescommand.h"
#include "clearscenecommand.h"
#include "removepropertiescommand.h"
#include "reparentinstancescommand.h"
#include "changeidscommand.h"
#include "changestatecommand.h"
#include "completecomponentcommand.h"
#include "addimportcontainer.h"
#include "changenodesourcecommand.h"
#include "informationchangedcommand.h"
#include "pixmapchangedcommand.h"
#include "valueschangedcommand.h"
#include "childrenchangedcommand.h"
#include "imagecontainer.h"
#include "statepreviewimagechangedcommand.h"
#include "componentcompletedcommand.h"
#include "synchronizecommand.h"
#include "tokencommand.h"
#include "removesharedmemorycommand.h"
namespace QmlDesigner {
static bool isRegistered=false;
NodeInstanceServerInterface::NodeInstanceServerInterface(QObject *parent) :
QObject(parent)
{
registerCommands();
}
void NodeInstanceServerInterface::registerCommands()
{
if (isRegistered)
return;
isRegistered = true;
qRegisterMetaType<CreateInstancesCommand>("CreateInstancesCommand");
qRegisterMetaTypeStreamOperators<CreateInstancesCommand>("CreateInstancesCommand");
qRegisterMetaType<ClearSceneCommand>("ClearSceneCommand");
qRegisterMetaTypeStreamOperators<ClearSceneCommand>("ClearSceneCommand");
qRegisterMetaType<CreateSceneCommand>("CreateSceneCommand");
qRegisterMetaTypeStreamOperators<CreateSceneCommand>("CreateSceneCommand");
qRegisterMetaType<ChangeBindingsCommand>("ChangeBindingsCommand");
qRegisterMetaTypeStreamOperators<ChangeBindingsCommand>("ChangeBindingsCommand");
qRegisterMetaType<ChangeValuesCommand>("ChangeValuesCommand");
qRegisterMetaTypeStreamOperators<ChangeValuesCommand>("ChangeValuesCommand");
qRegisterMetaType<ChangeFileUrlCommand>("ChangeFileUrlCommand");
qRegisterMetaTypeStreamOperators<ChangeFileUrlCommand>("ChangeFileUrlCommand");
qRegisterMetaType<ChangeStateCommand>("ChangeStateCommand");
qRegisterMetaTypeStreamOperators<PropertyAbstractContainer>("ChangeStateCommand");
qRegisterMetaType<RemoveInstancesCommand>("RemoveInstancesCommand");
qRegisterMetaTypeStreamOperators<RemoveInstancesCommand>("RemoveInstancesCommand");
qRegisterMetaType<RemovePropertiesCommand>("RemovePropertiesCommand");
qRegisterMetaTypeStreamOperators<RemovePropertiesCommand>("RemovePropertiesCommand");
qRegisterMetaType<ReparentInstancesCommand>("ReparentInstancesCommand");
qRegisterMetaTypeStreamOperators<ReparentInstancesCommand>("ReparentInstancesCommand");
qRegisterMetaType<ChangeIdsCommand>("ChangeIdsCommand");
qRegisterMetaTypeStreamOperators<ChangeIdsCommand>("ChangeIdsCommand");
qRegisterMetaType<ChangeStateCommand>("ChangeStateCommand");
qRegisterMetaTypeStreamOperators<ChangeStateCommand>("ChangeStateCommand");
qRegisterMetaType<InformationChangedCommand>("InformationChangedCommand");
qRegisterMetaTypeStreamOperators<InformationChangedCommand>("InformationChangedCommand");
qRegisterMetaType<ValuesChangedCommand>("ValuesChangedCommand");
qRegisterMetaTypeStreamOperators<ValuesChangedCommand>("ValuesChangedCommand");
qRegisterMetaType<PixmapChangedCommand>("PixmapChangedCommand");
qRegisterMetaTypeStreamOperators<PixmapChangedCommand>("PixmapChangedCommand");
qRegisterMetaType<InformationContainer>("InformationContainer");
qRegisterMetaTypeStreamOperators<InformationContainer>("InformationContainer");
qRegisterMetaType<PropertyValueContainer>("PropertyValueContainer");
qRegisterMetaTypeStreamOperators<PropertyValueContainer>("PropertyValueContainer");
qRegisterMetaType<PropertyBindingContainer>("PropertyBindingContainer");
qRegisterMetaTypeStreamOperators<PropertyBindingContainer>("PropertyBindingContainer");
qRegisterMetaType<PropertyAbstractContainer>("PropertyAbstractContainer");
qRegisterMetaTypeStreamOperators<PropertyAbstractContainer>("PropertyAbstractContainer");
qRegisterMetaType<InstanceContainer>("InstanceContainer");
qRegisterMetaTypeStreamOperators<InstanceContainer>("InstanceContainer");
qRegisterMetaType<IdContainer>("IdContainer");
qRegisterMetaTypeStreamOperators<IdContainer>("IdContainer");
qRegisterMetaType<ChildrenChangedCommand>("ChildrenChangedCommand");
qRegisterMetaTypeStreamOperators<ChildrenChangedCommand>("ChildrenChangedCommand");
qRegisterMetaType<ImageContainer>("ImageContainer");
qRegisterMetaTypeStreamOperators<ImageContainer>("ImageContainer");
qRegisterMetaType<StatePreviewImageChangedCommand>("StatePreviewImageChangedCommand");
qRegisterMetaTypeStreamOperators<StatePreviewImageChangedCommand>("StatePreviewImageChangedCommand");
qRegisterMetaType<CompleteComponentCommand>("CompleteComponentCommand");
qRegisterMetaTypeStreamOperators<CompleteComponentCommand>("CompleteComponentCommand");
qRegisterMetaType<ComponentCompletedCommand>("ComponentCompletedCommand");
qRegisterMetaTypeStreamOperators<ComponentCompletedCommand>("ComponentCompletedCommand");
qRegisterMetaType<AddImportContainer>("AddImportContainer");
qRegisterMetaTypeStreamOperators<AddImportContainer>("AddImportContainer");
qRegisterMetaType<SynchronizeCommand>("SynchronizeCommand");
qRegisterMetaTypeStreamOperators<SynchronizeCommand>("SynchronizeCommand");
qRegisterMetaType<ChangeNodeSourceCommand>("ChangeNodeSourceCommand");
qRegisterMetaTypeStreamOperators<ChangeNodeSourceCommand>("ChangeNodeSourceCommand");
qRegisterMetaType<ChangeAuxiliaryCommand>("ChangeAuxiliaryCommand");
qRegisterMetaTypeStreamOperators<ChangeAuxiliaryCommand>("ChangeAuxiliaryCommand");
qRegisterMetaType<TokenCommand>("TokenCommand");
qRegisterMetaTypeStreamOperators<TokenCommand>("TokenCommand");
qRegisterMetaType<RemoveSharedMemoryCommand>("RemoveSharedMemoryCommand");
qRegisterMetaTypeStreamOperators<RemoveSharedMemoryCommand>("RemoveSharedMemoryCommand");
}
}
<commit_msg>QmlDesigner.Instances: Fix type registration<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: http://www.qt-project.org/
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**************************************************************************/
#include "nodeinstanceserverinterface.h"
#include <qmetatype.h>
#include "propertyabstractcontainer.h"
#include "propertyvaluecontainer.h"
#include "propertybindingcontainer.h"
#include "instancecontainer.h"
#include "createinstancescommand.h"
#include "createscenecommand.h"
#include "changevaluescommand.h"
#include "changebindingscommand.h"
#include "changeauxiliarycommand.h"
#include "changefileurlcommand.h"
#include "removeinstancescommand.h"
#include "clearscenecommand.h"
#include "removepropertiescommand.h"
#include "reparentinstancescommand.h"
#include "changeidscommand.h"
#include "changestatecommand.h"
#include "completecomponentcommand.h"
#include "addimportcontainer.h"
#include "changenodesourcecommand.h"
#include "informationchangedcommand.h"
#include "pixmapchangedcommand.h"
#include "valueschangedcommand.h"
#include "childrenchangedcommand.h"
#include "imagecontainer.h"
#include "statepreviewimagechangedcommand.h"
#include "componentcompletedcommand.h"
#include "synchronizecommand.h"
#include "tokencommand.h"
#include "removesharedmemorycommand.h"
namespace QmlDesigner {
static bool isRegistered=false;
NodeInstanceServerInterface::NodeInstanceServerInterface(QObject *parent) :
QObject(parent)
{
registerCommands();
}
void NodeInstanceServerInterface::registerCommands()
{
if (isRegistered)
return;
isRegistered = true;
qRegisterMetaType<CreateInstancesCommand>("CreateInstancesCommand");
qRegisterMetaTypeStreamOperators<CreateInstancesCommand>("CreateInstancesCommand");
qRegisterMetaType<ClearSceneCommand>("ClearSceneCommand");
qRegisterMetaTypeStreamOperators<ClearSceneCommand>("ClearSceneCommand");
qRegisterMetaType<CreateSceneCommand>("CreateSceneCommand");
qRegisterMetaTypeStreamOperators<CreateSceneCommand>("CreateSceneCommand");
qRegisterMetaType<ChangeBindingsCommand>("ChangeBindingsCommand");
qRegisterMetaTypeStreamOperators<ChangeBindingsCommand>("ChangeBindingsCommand");
qRegisterMetaType<ChangeValuesCommand>("ChangeValuesCommand");
qRegisterMetaTypeStreamOperators<ChangeValuesCommand>("ChangeValuesCommand");
qRegisterMetaType<ChangeFileUrlCommand>("ChangeFileUrlCommand");
qRegisterMetaTypeStreamOperators<ChangeFileUrlCommand>("ChangeFileUrlCommand");
qRegisterMetaType<ChangeStateCommand>("ChangeStateCommand");
qRegisterMetaTypeStreamOperators<ChangeStateCommand>("ChangeStateCommand");
qRegisterMetaType<RemoveInstancesCommand>("RemoveInstancesCommand");
qRegisterMetaTypeStreamOperators<RemoveInstancesCommand>("RemoveInstancesCommand");
qRegisterMetaType<RemovePropertiesCommand>("RemovePropertiesCommand");
qRegisterMetaTypeStreamOperators<RemovePropertiesCommand>("RemovePropertiesCommand");
qRegisterMetaType<ReparentInstancesCommand>("ReparentInstancesCommand");
qRegisterMetaTypeStreamOperators<ReparentInstancesCommand>("ReparentInstancesCommand");
qRegisterMetaType<ChangeIdsCommand>("ChangeIdsCommand");
qRegisterMetaTypeStreamOperators<ChangeIdsCommand>("ChangeIdsCommand");
qRegisterMetaType<ChangeStateCommand>("ChangeStateCommand");
qRegisterMetaTypeStreamOperators<ChangeStateCommand>("ChangeStateCommand");
qRegisterMetaType<InformationChangedCommand>("InformationChangedCommand");
qRegisterMetaTypeStreamOperators<InformationChangedCommand>("InformationChangedCommand");
qRegisterMetaType<ValuesChangedCommand>("ValuesChangedCommand");
qRegisterMetaTypeStreamOperators<ValuesChangedCommand>("ValuesChangedCommand");
qRegisterMetaType<PixmapChangedCommand>("PixmapChangedCommand");
qRegisterMetaTypeStreamOperators<PixmapChangedCommand>("PixmapChangedCommand");
qRegisterMetaType<InformationContainer>("InformationContainer");
qRegisterMetaTypeStreamOperators<InformationContainer>("InformationContainer");
qRegisterMetaType<PropertyValueContainer>("PropertyValueContainer");
qRegisterMetaTypeStreamOperators<PropertyValueContainer>("PropertyValueContainer");
qRegisterMetaType<PropertyBindingContainer>("PropertyBindingContainer");
qRegisterMetaTypeStreamOperators<PropertyBindingContainer>("PropertyBindingContainer");
qRegisterMetaType<PropertyAbstractContainer>("PropertyAbstractContainer");
qRegisterMetaTypeStreamOperators<PropertyAbstractContainer>("PropertyAbstractContainer");
qRegisterMetaType<InstanceContainer>("InstanceContainer");
qRegisterMetaTypeStreamOperators<InstanceContainer>("InstanceContainer");
qRegisterMetaType<IdContainer>("IdContainer");
qRegisterMetaTypeStreamOperators<IdContainer>("IdContainer");
qRegisterMetaType<ChildrenChangedCommand>("ChildrenChangedCommand");
qRegisterMetaTypeStreamOperators<ChildrenChangedCommand>("ChildrenChangedCommand");
qRegisterMetaType<ImageContainer>("ImageContainer");
qRegisterMetaTypeStreamOperators<ImageContainer>("ImageContainer");
qRegisterMetaType<StatePreviewImageChangedCommand>("StatePreviewImageChangedCommand");
qRegisterMetaTypeStreamOperators<StatePreviewImageChangedCommand>("StatePreviewImageChangedCommand");
qRegisterMetaType<CompleteComponentCommand>("CompleteComponentCommand");
qRegisterMetaTypeStreamOperators<CompleteComponentCommand>("CompleteComponentCommand");
qRegisterMetaType<ComponentCompletedCommand>("ComponentCompletedCommand");
qRegisterMetaTypeStreamOperators<ComponentCompletedCommand>("ComponentCompletedCommand");
qRegisterMetaType<AddImportContainer>("AddImportContainer");
qRegisterMetaTypeStreamOperators<AddImportContainer>("AddImportContainer");
qRegisterMetaType<SynchronizeCommand>("SynchronizeCommand");
qRegisterMetaTypeStreamOperators<SynchronizeCommand>("SynchronizeCommand");
qRegisterMetaType<ChangeNodeSourceCommand>("ChangeNodeSourceCommand");
qRegisterMetaTypeStreamOperators<ChangeNodeSourceCommand>("ChangeNodeSourceCommand");
qRegisterMetaType<ChangeAuxiliaryCommand>("ChangeAuxiliaryCommand");
qRegisterMetaTypeStreamOperators<ChangeAuxiliaryCommand>("ChangeAuxiliaryCommand");
qRegisterMetaType<TokenCommand>("TokenCommand");
qRegisterMetaTypeStreamOperators<TokenCommand>("TokenCommand");
qRegisterMetaType<RemoveSharedMemoryCommand>("RemoveSharedMemoryCommand");
qRegisterMetaTypeStreamOperators<RemoveSharedMemoryCommand>("RemoveSharedMemoryCommand");
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2015 Chaobin Zhang. All rights reserved.
// Use of this source code is governed by the BSD license that can be
// found in the LICENSE file.
#include "slave/slave_main_runner.h"
#include <set>
#include <vector>
#include "base/bind.h"
#include "base/files/file_util.h"
#include "base/hash.h"
#include "base/md5.h"
#include "base/stl_util.h"
#include "base/threading/thread_restrictions.h"
#include "common/util.h"
#include "ninja/ninja_main.h"
#include "proto/slave_services.pb.h"
#include "slave/slave_file_thread.h"
#include "slave/slave_rpc.h"
#include "thread/ninja_thread.h"
namespace {
slave::RunCommandResponse::ExitStatus TransformExitStatus(ExitStatus status) {
switch (status) {
case ExitSuccess:
return slave::RunCommandResponse::kExitSuccess;
case ExitFailure:
return slave::RunCommandResponse::kExitFailure;
case ExitInterrupted:
return slave::RunCommandResponse::kExitInterrupted;
default:
NOTREACHED();
return slave::RunCommandResponse::kExitFailure;
}
}
void FindAllEdges(Edge* e, std::set<Edge*>* seen, std::vector<Edge*>* edges) {
if (e == NULL || seen->insert(e).second == false)
return;
for (size_t i = 0; i < e->inputs_.size(); ++i)
FindAllEdges(e->inputs_[i]->in_edge(), seen, edges);
edges->push_back(e);
}
} // namespace
namespace slave {
SlaveMainRunner::SlaveMainRunner(const std::string& master, uint16 port)
: master_(master),
port_(port),
command_executor_(new common::CommandExecutor()) {
command_executor_->AddObserver(this);
}
SlaveMainRunner::~SlaveMainRunner() {
command_executor_->RemoveObserver(this);
}
void SlaveMainRunner::OnCommandStarted(const std::string& command) {
}
void SlaveMainRunner::OnCommandFinished(const std::string& command,
const CommandRunner::Result* result) {
uint32 command_hash = base::Hash(command);
DCHECK(command_hash_edge_map_.find(command_hash) !=
command_hash_edge_map_.end());
plan_.EdgeFinished(command_hash_edge_map_[command_hash]);
StartReadyEdges();
RunCommandContextMap::iterator it =
run_command_context_map_.find(command_hash);
if (it == run_command_context_map_.end())
return;
it->second.response->set_output(result->output);
it->second.response->set_status(TransformExitStatus(result->status));
NinjaThread::PostBlockingPoolTask(
FROM_HERE,
base::Bind(&SlaveMainRunner::MD5OutputsOnBlockingPool, this, it->second));
run_command_context_map_.erase(it);
}
bool SlaveMainRunner::PostCreateThreads() {
slave_rpc_.reset(new SlaveRPC(master_, port_, this));
slave_file_thread_.reset(new SlaveFileThread());
std::set<Edge*> edges;
ninja_main()->GetAllEdges(&edges);
for (std::set<Edge*>::iterator it = edges.begin(); it != edges.end(); ++it) {
uint32 hash = common::HashEdge(*it);
CHECK(hash_edge_map_.find(hash) == hash_edge_map_.end());
hash_edge_map_[hash] = (*it);
}
ninja_main()->InitForSlave();
return true;
}
void SlaveMainRunner::RunCommand(const RunCommandRequest* request,
RunCommandResponse* response,
::google::protobuf::Closure* done) {
uint32 edge_id = request->edge_id();
response->set_edge_id(edge_id);
if (!ContainsKey(hash_edge_map_, edge_id)) {
response->set_status(RunCommandResponse::kExitFailure);
response->set_output("This command is NOT ALLOWED to run.");
NinjaThread::PostTask(
NinjaThread::RPC, FROM_HERE,
base::Bind(&SlaveRPC::OnRunCommandDone,
base::Unretained(slave_rpc_.get()),
done));
return;
}
Edge* edge = hash_edge_map_[edge_id];
const std::string& command = edge->EvaluateCommand();
run_command_context_map_[base::Hash(command)] = {request, response, done};
if (edge->outputs_ready()) {
CommandRunner::Result result;
result.status = ExitSuccess;
OnCommandFinished(edge->EvaluateCommand(), &result);
return;
}
std::string error;
for (size_t i = 0; i < edge->outputs_.size(); ++i) {
if (!plan_.AddTarget(edge->outputs_[i], &error)) {
LOG(ERROR) << error;
}
}
StartReadyEdges();
}
void SlaveMainRunner::Wait() {
}
bool SlaveMainRunner::CreateDirsAndResponseFile(
const RunCommandRequest* request) {
base::ThreadRestrictions::AssertIOAllowed();
for (int i = 0; i < request->output_paths_size(); ++i) {
base::FilePath dir =
base::FilePath::FromUTF8Unsafe(request->output_paths(i));
if (!base::CreateDirectory(dir.DirName()))
return false;
}
if (request->has_rspfile_name()) {
if (!ninja_main()->disk_interface()->WriteFile(request->rspfile_name(),
request->rspfile_content()))
return false;
}
return true;
}
void SlaveMainRunner::MD5OutputsOnBlockingPool(
const RunCommandContext& context) {
if (context.response->status() == slave::RunCommandResponse::kExitSuccess) {
for (int i = 0; i < context.request->output_paths_size(); ++i) {
base::FilePath filename =
base::FilePath::FromUTF8Unsafe(context.request->output_paths(i));
std::string md5 = "";
if (base::PathExists(filename)) {
md5 = common::GetMd5Digest(filename);
CHECK(!md5.empty());
}
context.response->add_md5()->assign(md5);
}
}
NinjaThread::PostTask(
NinjaThread::RPC, FROM_HERE,
base::Bind(&SlaveRPC::OnRunCommandDone,
base::Unretained(slave_rpc_.get()),
context.done));
}
bool SlaveMainRunner::StartEdge(Edge* edge) {
if (edge->is_phony())
return true;
// Create directories necessary for outputs.
for (vector<Node*>::iterator o = edge->outputs_.begin();
o != edge->outputs_.end(); ++o) {
base::FilePath dir =
base::FilePath::FromUTF8Unsafe((*o)->path());
if (!base::CreateDirectory(dir.DirName()))
return false;
}
// Create response file, if needed
std::string rspfile = edge->GetUnescapedRspfile();
if (!rspfile.empty()) {
std::string content = edge->GetBinding("rspfile_content");
if (!ninja_main()->disk_interface()->WriteFile(rspfile, content))
return false;
}
std::string command = edge->EvaluateCommand();
command_executor_->RunCommand(edge->EvaluateCommand());
return true;
}
void SlaveMainRunner::StartReadyEdges() {
Edge* ready_edge = NULL;
while ((ready_edge = plan_.FindWork()) != NULL) {
std::string command = ready_edge->EvaluateCommand();
command_hash_edge_map_[base::Hash(command)] = ready_edge;
StartEdge(ready_edge);
}
}
} // namespace slave
<commit_msg>[Slave] Don't abort if md5 error.<commit_after>// Copyright (c) 2015 Chaobin Zhang. All rights reserved.
// Use of this source code is governed by the BSD license that can be
// found in the LICENSE file.
#include "slave/slave_main_runner.h"
#include <set>
#include <vector>
#include "base/bind.h"
#include "base/files/file_util.h"
#include "base/hash.h"
#include "base/md5.h"
#include "base/stl_util.h"
#include "base/threading/thread_restrictions.h"
#include "common/util.h"
#include "ninja/ninja_main.h"
#include "proto/slave_services.pb.h"
#include "slave/slave_file_thread.h"
#include "slave/slave_rpc.h"
#include "thread/ninja_thread.h"
namespace {
slave::RunCommandResponse::ExitStatus TransformExitStatus(ExitStatus status) {
switch (status) {
case ExitSuccess:
return slave::RunCommandResponse::kExitSuccess;
case ExitFailure:
return slave::RunCommandResponse::kExitFailure;
case ExitInterrupted:
return slave::RunCommandResponse::kExitInterrupted;
default:
NOTREACHED();
return slave::RunCommandResponse::kExitFailure;
}
}
void FindAllEdges(Edge* e, std::set<Edge*>* seen, std::vector<Edge*>* edges) {
if (e == NULL || seen->insert(e).second == false)
return;
for (size_t i = 0; i < e->inputs_.size(); ++i)
FindAllEdges(e->inputs_[i]->in_edge(), seen, edges);
edges->push_back(e);
}
} // namespace
namespace slave {
SlaveMainRunner::SlaveMainRunner(const std::string& master, uint16 port)
: master_(master),
port_(port),
command_executor_(new common::CommandExecutor()) {
command_executor_->AddObserver(this);
}
SlaveMainRunner::~SlaveMainRunner() {
command_executor_->RemoveObserver(this);
}
void SlaveMainRunner::OnCommandStarted(const std::string& command) {
}
void SlaveMainRunner::OnCommandFinished(const std::string& command,
const CommandRunner::Result* result) {
uint32 command_hash = base::Hash(command);
DCHECK(command_hash_edge_map_.find(command_hash) !=
command_hash_edge_map_.end());
plan_.EdgeFinished(command_hash_edge_map_[command_hash]);
StartReadyEdges();
RunCommandContextMap::iterator it =
run_command_context_map_.find(command_hash);
if (it == run_command_context_map_.end())
return;
it->second.response->set_output(result->output);
it->second.response->set_status(TransformExitStatus(result->status));
NinjaThread::PostBlockingPoolTask(
FROM_HERE,
base::Bind(&SlaveMainRunner::MD5OutputsOnBlockingPool, this, it->second));
run_command_context_map_.erase(it);
}
bool SlaveMainRunner::PostCreateThreads() {
slave_rpc_.reset(new SlaveRPC(master_, port_, this));
slave_file_thread_.reset(new SlaveFileThread());
std::set<Edge*> edges;
ninja_main()->GetAllEdges(&edges);
for (std::set<Edge*>::iterator it = edges.begin(); it != edges.end(); ++it) {
uint32 hash = common::HashEdge(*it);
CHECK(hash_edge_map_.find(hash) == hash_edge_map_.end());
hash_edge_map_[hash] = (*it);
}
ninja_main()->InitForSlave();
return true;
}
void SlaveMainRunner::RunCommand(const RunCommandRequest* request,
RunCommandResponse* response,
::google::protobuf::Closure* done) {
uint32 edge_id = request->edge_id();
response->set_edge_id(edge_id);
if (!ContainsKey(hash_edge_map_, edge_id)) {
response->set_status(RunCommandResponse::kExitFailure);
response->set_output("This command is NOT ALLOWED to run.");
NinjaThread::PostTask(
NinjaThread::RPC, FROM_HERE,
base::Bind(&SlaveRPC::OnRunCommandDone,
base::Unretained(slave_rpc_.get()),
done));
return;
}
Edge* edge = hash_edge_map_[edge_id];
const std::string& command = edge->EvaluateCommand();
run_command_context_map_[base::Hash(command)] = {request, response, done};
if (edge->outputs_ready()) {
CommandRunner::Result result;
result.status = ExitSuccess;
OnCommandFinished(edge->EvaluateCommand(), &result);
return;
}
std::string error;
for (size_t i = 0; i < edge->outputs_.size(); ++i) {
if (!plan_.AddTarget(edge->outputs_[i], &error)) {
LOG(ERROR) << error;
}
}
StartReadyEdges();
}
void SlaveMainRunner::Wait() {
}
bool SlaveMainRunner::CreateDirsAndResponseFile(
const RunCommandRequest* request) {
base::ThreadRestrictions::AssertIOAllowed();
for (int i = 0; i < request->output_paths_size(); ++i) {
base::FilePath dir =
base::FilePath::FromUTF8Unsafe(request->output_paths(i));
if (!base::CreateDirectory(dir.DirName()))
return false;
}
if (request->has_rspfile_name()) {
if (!ninja_main()->disk_interface()->WriteFile(request->rspfile_name(),
request->rspfile_content()))
return false;
}
return true;
}
void SlaveMainRunner::MD5OutputsOnBlockingPool(
const RunCommandContext& context) {
if (context.response->status() == slave::RunCommandResponse::kExitSuccess) {
for (int i = 0; i < context.request->output_paths_size(); ++i) {
base::FilePath filename =
base::FilePath::FromUTF8Unsafe(context.request->output_paths(i));
std::string md5 = "";
if (base::PathExists(filename)) {
md5 = common::GetMd5Digest(filename);
if (md5.empty()) {
LOG(ERROR) << "GetMd5Digest of " << filename.value();
}
}
context.response->add_md5()->assign(md5);
}
}
NinjaThread::PostTask(
NinjaThread::RPC, FROM_HERE,
base::Bind(&SlaveRPC::OnRunCommandDone,
base::Unretained(slave_rpc_.get()),
context.done));
}
bool SlaveMainRunner::StartEdge(Edge* edge) {
if (edge->is_phony())
return true;
// Create directories necessary for outputs.
for (vector<Node*>::iterator o = edge->outputs_.begin();
o != edge->outputs_.end(); ++o) {
base::FilePath dir =
base::FilePath::FromUTF8Unsafe((*o)->path());
if (!base::CreateDirectory(dir.DirName()))
return false;
}
// Create response file, if needed
std::string rspfile = edge->GetUnescapedRspfile();
if (!rspfile.empty()) {
std::string content = edge->GetBinding("rspfile_content");
if (!ninja_main()->disk_interface()->WriteFile(rspfile, content))
return false;
}
std::string command = edge->EvaluateCommand();
command_executor_->RunCommand(edge->EvaluateCommand());
return true;
}
void SlaveMainRunner::StartReadyEdges() {
Edge* ready_edge = NULL;
while ((ready_edge = plan_.FindWork()) != NULL) {
std::string command = ready_edge->EvaluateCommand();
command_hash_edge_map_[base::Hash(command)] = ready_edge;
StartEdge(ready_edge);
}
}
} // namespace slave
<|endoftext|>
|
<commit_before>//
// Copyright (c) 2012 Kim Walisch, <kim.walisch@gmail.com>.
// All rights reserved.
//
// This file is part of primesieve.
// Homepage: http://primesieve.googlecode.com
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
// * Neither the name of the author nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.
/// @brief ParallelPrimeSieve sieves primes in parallel
/// using OpenMP 3.0 (2008) or later.
#include "ParallelPrimeSieve.h"
#include "PrimeSieve.h"
#include "imath.h"
#include "config.h"
#include <stdint.h>
#include <cstdlib>
#include <cassert>
#include <algorithm>
#ifdef _OPENMP
#include <omp.h>
#include "openmp_RAII.h"
#endif
using namespace soe;
ParallelPrimeSieve::ParallelPrimeSieve() :
shm_(NULL),
numThreads_(DEFAULT_NUM_THREADS)
{ }
/// API for the primesieve GUI application
void ParallelPrimeSieve::init(SharedMemory& shm)
{
setStart(shm.start);
setStop(shm.stop);
setSieveSize(shm.sieveSize);
setFlags(shm.flags);
setNumThreads(shm.threads);
shm_ = &shm;
}
int ParallelPrimeSieve::getNumThreads() const
{
if (numThreads_ == DEFAULT_NUM_THREADS) {
// Use 1 thread to generate primes in arithmetic order
return isGenerate() ? 1 : idealNumThreads();
}
return numThreads_;
}
void ParallelPrimeSieve::setNumThreads(int threads)
{
numThreads_ = getInBetween(1, threads, getMaxThreads());
}
/// Get an ideal number of threads for the current
/// set start_ and stop_ numbers.
///
int ParallelPrimeSieve::idealNumThreads() const
{
uint64_t threshold = std::max(config::MIN_THREAD_INTERVAL, isqrt(stop_) / 5);
uint64_t threads = getInterval() / threshold;
threads = getInBetween<uint64_t>(1, threads, getMaxThreads());
return static_cast<int>(threads);
}
/// Get an interval size that ensures a good load balance
/// when multiple threads are used.
///
uint64_t ParallelPrimeSieve::getThreadInterval(int threads) const
{
assert(threads > 0);
uint64_t unbalanced = getInterval() / threads;
uint64_t balanced = isqrt(stop_) * 1000;
uint64_t fastest = std::min(balanced, unbalanced);
uint64_t threadInterval = getInBetween(config::MIN_THREAD_INTERVAL, fastest, config::MAX_THREAD_INTERVAL);
uint64_t chunks = getInterval() / threadInterval;
if (chunks < threads * 5u)
threadInterval = std::max(config::MIN_THREAD_INTERVAL, unbalanced);
threadInterval += 30 - threadInterval % 30;
return threadInterval;
}
/// Align n to modulo 30 + 2 to prevent prime k-tuplet
/// (twin primes, prime triplets, ...) gaps.
///
uint64_t ParallelPrimeSieve::align(uint64_t n) const
{
if (n != start_)
n = std::min(n + 32 - n % 30, stop_);
return n;
}
bool ParallelPrimeSieve::tooMany(int threads) const
{
return (threads > 1 && getInterval() / threads < config::MIN_THREAD_INTERVAL);
}
#ifdef _OPENMP
int ParallelPrimeSieve::getMaxThreads()
{
return omp_get_max_threads();
}
/// Sieve the primes and prime k-tuplets within [start, stop]
/// in parallel using OpenMP (version 3.0 or later).
///
void ParallelPrimeSieve::sieve()
{
if (start_ > stop_)
throw primesieve_error("start must be <= stop");
int threads = getNumThreads();
if (tooMany(threads)) threads = idealNumThreads();
OmpInitLock ompInit(&lock_);
if (threads == 1)
PrimeSieve::sieve();
else {
double time = omp_get_wtime();
reset();
uint64_t threadInterval = getThreadInterval(threads);
uint64_t count0 = 0, count1 = 0, count2 = 0, count3 = 0, count4 = 0, count5 = 0, count6 = 0;
// The sieve interval [start_, stop_] is subdivided into chunks of
// size 'threadInterval' that are sieved in parallel using
// multiple threads. This scales well as each thread sieves using
// its own private memory without need of synchronization.
#pragma omp parallel for schedule(dynamic) num_threads(threads) \
reduction(+: count0, count1, count2, count3, count4, count5, count6)
for (uint64_t n = start_; n < stop_; n += threadInterval) {
PrimeSieve ps(*this, omp_get_thread_num());
uint64_t threadStart = align(n);
uint64_t threadStop = align(n + threadInterval);
ps.sieve(threadStart, threadStop);
count0 += ps.getCount(0);
count1 += ps.getCount(1);
count2 += ps.getCount(2);
count3 += ps.getCount(3);
count4 += ps.getCount(4);
count5 += ps.getCount(5);
count6 += ps.getCount(6);
}
seconds_ = omp_get_wtime() - time;
counts_[0] = count0;
counts_[1] = count1;
counts_[2] = count2;
counts_[3] = count3;
counts_[4] = count4;
counts_[5] = count5;
counts_[6] = count6;
}
// communicate the sieving results to the
// primesieve GUI application
if (shm_ != NULL) {
std::copy(counts_.begin(), counts_.end(), shm_->counts);
shm_->seconds = seconds_;
}
}
/// Calculate the sieving status (in percent).
/// @param processed Sum of recently processed segments.
///
bool ParallelPrimeSieve::updateStatus(uint64_t processed, bool waitForLock)
{
OmpLockGuard lock(getLock<omp_lock_t*>(), waitForLock);
if (lock.isSet()) {
PrimeSieve::updateStatus(processed, false);
if (shm_ != NULL)
shm_->status = getStatus();
}
return lock.isSet();
}
/// Used to synchronize threads for prime number generation
void ParallelPrimeSieve::setLock()
{
omp_lock_t* lock = getLock<omp_lock_t*>();
omp_set_lock(lock);
}
void ParallelPrimeSieve::unsetLock()
{
omp_lock_t* lock = getLock<omp_lock_t*>();
omp_unset_lock(lock);
}
#endif /* _OPENMP */
/// If OpenMP is not used then ParallelPrimeSieve behaves like
/// the single threaded PrimeSieve.
///
#if !defined(_OPENMP)
int ParallelPrimeSieve::getMaxThreads()
{
return 1;
}
void ParallelPrimeSieve::sieve()
{
PrimeSieve::sieve();
}
bool ParallelPrimeSieve::updateStatus(uint64_t processed, bool waitForLock)
{
return PrimeSieve::updateStatus(processed, waitForLock);
}
void ParallelPrimeSieve::setLock() { }
void ParallelPrimeSieve::unsetLock() { }
#endif
<commit_msg>added support for OpenMP 2.x<commit_after>//
// Copyright (c) 2012 Kim Walisch, <kim.walisch@gmail.com>.
// All rights reserved.
//
// This file is part of primesieve.
// Homepage: http://primesieve.googlecode.com
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
// * Neither the name of the author nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.
/// @brief ParallelPrimeSieve sieves primes in parallel using
/// OpenMP 2.0 (2002) or later.
#include "ParallelPrimeSieve.h"
#include "PrimeSieve.h"
#include "imath.h"
#include "config.h"
#include <stdint.h>
#include <cstdlib>
#include <cassert>
#include <algorithm>
#ifdef _OPENMP
#include <omp.h>
#include "openmp_RAII.h"
#endif
using namespace soe;
ParallelPrimeSieve::ParallelPrimeSieve() :
shm_(NULL),
numThreads_(DEFAULT_NUM_THREADS)
{ }
/// API for the primesieve GUI application
void ParallelPrimeSieve::init(SharedMemory& shm)
{
setStart(shm.start);
setStop(shm.stop);
setSieveSize(shm.sieveSize);
setFlags(shm.flags);
setNumThreads(shm.threads);
shm_ = &shm;
}
int ParallelPrimeSieve::getNumThreads() const
{
if (numThreads_ == DEFAULT_NUM_THREADS) {
// Use 1 thread to generate primes in arithmetic order
return isGenerate() ? 1 : idealNumThreads();
}
return numThreads_;
}
void ParallelPrimeSieve::setNumThreads(int threads)
{
numThreads_ = getInBetween(1, threads, getMaxThreads());
}
/// Get an ideal number of threads for the current
/// set start_ and stop_ numbers.
///
int ParallelPrimeSieve::idealNumThreads() const
{
uint64_t threshold = std::max(config::MIN_THREAD_INTERVAL, isqrt(stop_) / 5);
uint64_t threads = getInterval() / threshold;
threads = getInBetween<uint64_t>(1, threads, getMaxThreads());
return static_cast<int>(threads);
}
/// Get an interval size that ensures a good load balance
/// when multiple threads are used.
///
uint64_t ParallelPrimeSieve::getThreadInterval(int threads) const
{
assert(threads > 0);
uint64_t unbalanced = getInterval() / threads;
uint64_t balanced = isqrt(stop_) * 1000;
uint64_t fastest = std::min(balanced, unbalanced);
uint64_t threadInterval = getInBetween(config::MIN_THREAD_INTERVAL, fastest, config::MAX_THREAD_INTERVAL);
uint64_t chunks = getInterval() / threadInterval;
if (chunks < threads * 5u)
threadInterval = std::max(config::MIN_THREAD_INTERVAL, unbalanced);
threadInterval += 30 - threadInterval % 30;
return threadInterval;
}
/// Align n to modulo 30 + 2 to prevent prime k-tuplet
/// (twin primes, prime triplets, ...) gaps.
///
uint64_t ParallelPrimeSieve::align(uint64_t n) const
{
if (n != start_)
n = std::min(n + 32 - n % 30, stop_);
return n;
}
bool ParallelPrimeSieve::tooMany(int threads) const
{
return (threads > 1 && getInterval() / threads < config::MIN_THREAD_INTERVAL);
}
#ifdef _OPENMP
int ParallelPrimeSieve::getMaxThreads()
{
return omp_get_max_threads();
}
/// Sieve the primes and prime k-tuplets within [start, stop]
/// in parallel using OpenMP multi-threading.
///
void ParallelPrimeSieve::sieve()
{
if (start_ > stop_)
throw primesieve_error("start must be <= stop");
int threads = getNumThreads();
if (tooMany(threads)) threads = idealNumThreads();
OmpInitLock ompInit(&lock_);
if (threads == 1)
PrimeSieve::sieve();
else {
double time = omp_get_wtime();
reset();
uint64_t count0 = 0, count1 = 0, count2 = 0, count3 = 0, count4 = 0, count5 = 0, count6 = 0;
uint64_t threadInterval = getThreadInterval(threads);
#if _OPENMP >= 200800 /* OpenMP >= 3.0 (2008) */
// The sieve interval [start_, stop_] is subdivided into chunks of
// size 'threadInterval' that are sieved in parallel using
// multiple threads. This scales well as each thread sieves using
// its own private memory without need of synchronization.
#pragma omp parallel for schedule(dynamic) num_threads(threads) \
reduction(+: count0, count1, count2, count3, count4, count5, count6)
for (uint64_t n = start_; n < stop_; n += threadInterval) {
PrimeSieve ps(*this, omp_get_thread_num());
uint64_t threadStart = align(n);
uint64_t threadStop = align(n + threadInterval);
ps.sieve(threadStart, threadStop);
count0 += ps.getCount(0);
count1 += ps.getCount(1);
count2 += ps.getCount(2);
count3 += ps.getCount(3);
count4 += ps.getCount(4);
count5 += ps.getCount(5);
count6 += ps.getCount(6);
}
#else /* OpenMP 2.x */
int64_t iters = idivCeil(getInterval(), threadInterval);
#pragma omp parallel for schedule(dynamic) num_threads(threads) \
reduction(+: count0, count1, count2, count3, count4, count5, count6)
for (int64_t i = 0; i < iters; i++) {
PrimeSieve ps(*this, omp_get_thread_num());
uint64_t threadStart = align(start_ + i * threadInterval);
uint64_t threadStop = align(start_ + (i + 1) * threadInterval);
ps.sieve(threadStart, threadStop);
count0 += ps.getCount(0);
count1 += ps.getCount(1);
count2 += ps.getCount(2);
count3 += ps.getCount(3);
count4 += ps.getCount(4);
count5 += ps.getCount(5);
count6 += ps.getCount(6);
}
#endif
seconds_ = omp_get_wtime() - time;
counts_[0] = count0;
counts_[1] = count1;
counts_[2] = count2;
counts_[3] = count3;
counts_[4] = count4;
counts_[5] = count5;
counts_[6] = count6;
}
// communicate the sieving results to the
// primesieve GUI application
if (shm_ != NULL) {
std::copy(counts_.begin(), counts_.end(), shm_->counts);
shm_->seconds = seconds_;
}
}
/// Calculate the sieving status (in percent).
/// @param processed Sum of recently processed segments.
///
bool ParallelPrimeSieve::updateStatus(uint64_t processed, bool waitForLock)
{
OmpLockGuard lock(getLock<omp_lock_t*>(), waitForLock);
if (lock.isSet()) {
PrimeSieve::updateStatus(processed, false);
if (shm_ != NULL)
shm_->status = getStatus();
}
return lock.isSet();
}
/// Used to synchronize threads for prime number generation
void ParallelPrimeSieve::setLock()
{
omp_lock_t* lock = getLock<omp_lock_t*>();
omp_set_lock(lock);
}
void ParallelPrimeSieve::unsetLock()
{
omp_lock_t* lock = getLock<omp_lock_t*>();
omp_unset_lock(lock);
}
#endif /* _OPENMP */
/// If OpenMP is not used then ParallelPrimeSieve behaves like
/// the single threaded PrimeSieve.
///
#if !defined(_OPENMP)
int ParallelPrimeSieve::getMaxThreads()
{
return 1;
}
void ParallelPrimeSieve::sieve()
{
PrimeSieve::sieve();
}
bool ParallelPrimeSieve::updateStatus(uint64_t processed, bool waitForLock)
{
return PrimeSieve::updateStatus(processed, waitForLock);
}
void ParallelPrimeSieve::setLock() { }
void ParallelPrimeSieve::unsetLock() { }
#endif
<|endoftext|>
|
<commit_before>/****************************************************************************
*
* (c) 2009-2016 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
*
* QGroundControl is licensed according to the terms in the file
* COPYING.md in the root of the source code directory.
*
****************************************************************************/
#include "QGCGeoBoundingCube.h"
#include <QDebug>
double QGCGeoBoundingCube::MaxAlt = 1000000.0;
double QGCGeoBoundingCube::MinAlt = -1000000.0;
double QGCGeoBoundingCube::MaxNorth = 90.0;
double QGCGeoBoundingCube::MaxSouth = -90.0;
double QGCGeoBoundingCube::MaxWest = -180.0;
double QGCGeoBoundingCube::MaxEast = 180.0;
//-----------------------------------------------------------------------------
bool
QGCGeoBoundingCube::isValid() const
{
return pointNW.isValid() && pointSE.isValid() && pointNW.latitude() != MaxSouth && pointSE.latitude() != MaxNorth && \
pointNW.longitude() != MaxEast && pointSE.longitude() != MaxWest && pointNW.altitude() < MaxAlt and pointSE.altitude() > MinAlt;
}
//-----------------------------------------------------------------------------
void
QGCGeoBoundingCube::reset()
{
pointSE = QGeoCoordinate();
pointNW = QGeoCoordinate();
}
//-----------------------------------------------------------------------------
QGeoCoordinate
QGCGeoBoundingCube::center() const
{
if(!isValid())
return QGeoCoordinate();
double lat = (((pointNW.latitude() + 90.0) + (pointSE.latitude() + 90.0)) / 2.0) - 90.0;
double lon = (((pointNW.longitude() + 180.0) + (pointSE.longitude() + 180.0)) / 2.0) - 180.0;
double alt = (pointNW.altitude() + pointSE.altitude()) / 2.0;
return QGeoCoordinate(lat, lon, alt);
}
//-----------------------------------------------------------------------------
QList<QGeoCoordinate>
QGCGeoBoundingCube::polygon2D() const
{
QList<QGeoCoordinate> coords;
if(isValid()) {
coords.append(QGeoCoordinate(pointNW.latitude(), pointNW.longitude(), pointSE.altitude()));
coords.append(QGeoCoordinate(pointNW.latitude(), pointSE.longitude(), pointSE.altitude()));
coords.append(QGeoCoordinate(pointSE.latitude(), pointSE.longitude(), pointSE.altitude()));
coords.append(QGeoCoordinate(pointSE.latitude(), pointNW.longitude(), pointSE.altitude()));
coords.append(QGeoCoordinate(pointNW.latitude(), pointNW.longitude(), pointSE.altitude()));
}
return coords;
}
//-----------------------------------------------------------------------------
bool
QGCGeoBoundingCube::operator ==(const QList<QGeoCoordinate>& coords) const
{
QList<QGeoCoordinate> c = polygon2D();
if(c.size() != coords.size()) return false;
for(int i = 0; i < c.size(); i++) {
if(c[i] != coords[i]) return false;
}
return true;
}
//-----------------------------------------------------------------------------
double
QGCGeoBoundingCube::width() const
{
if(!isValid())
return 0.0;
QGeoCoordinate ne = QGeoCoordinate(pointNW.latitude(), pointSE.longitude());
return pointNW.distanceTo(ne);
}
//-----------------------------------------------------------------------------
double
QGCGeoBoundingCube::height() const
{
if(!isValid())
return 0.0;
QGeoCoordinate sw = QGeoCoordinate(pointSE.latitude(), pointNW.longitude());
return pointNW.distanceTo(sw);
}
//-----------------------------------------------------------------------------
double
QGCGeoBoundingCube::area() const
{
if(!isValid())
return 0.0;
// Area in km^2
double a = (height() / 1000.0) * (width() / 1000.0);
//qDebug() << "Area:" << a;
return a;
}
//-----------------------------------------------------------------------------
double
QGCGeoBoundingCube::radius() const
{
if(!isValid())
return 0.0;
return pointNW.distanceTo(pointSE) / 2.0;
}
<commit_msg>Fix Windows build. I have no idea how this was building elsewhere at all.<commit_after>/****************************************************************************
*
* (c) 2009-2016 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
*
* QGroundControl is licensed according to the terms in the file
* COPYING.md in the root of the source code directory.
*
****************************************************************************/
#include "QGCGeoBoundingCube.h"
#include <QDebug>
double QGCGeoBoundingCube::MaxAlt = 1000000.0;
double QGCGeoBoundingCube::MinAlt = -1000000.0;
double QGCGeoBoundingCube::MaxNorth = 90.0;
double QGCGeoBoundingCube::MaxSouth = -90.0;
double QGCGeoBoundingCube::MaxWest = -180.0;
double QGCGeoBoundingCube::MaxEast = 180.0;
//-----------------------------------------------------------------------------
bool
QGCGeoBoundingCube::isValid() const
{
return pointNW.isValid() && pointSE.isValid() && pointNW.latitude() != MaxSouth && pointSE.latitude() != MaxNorth && \
pointNW.longitude() != MaxEast && pointSE.longitude() != MaxWest && pointNW.altitude() < MaxAlt && pointSE.altitude() > MinAlt;
}
//-----------------------------------------------------------------------------
void
QGCGeoBoundingCube::reset()
{
pointSE = QGeoCoordinate();
pointNW = QGeoCoordinate();
}
//-----------------------------------------------------------------------------
QGeoCoordinate
QGCGeoBoundingCube::center() const
{
if(!isValid())
return QGeoCoordinate();
double lat = (((pointNW.latitude() + 90.0) + (pointSE.latitude() + 90.0)) / 2.0) - 90.0;
double lon = (((pointNW.longitude() + 180.0) + (pointSE.longitude() + 180.0)) / 2.0) - 180.0;
double alt = (pointNW.altitude() + pointSE.altitude()) / 2.0;
return QGeoCoordinate(lat, lon, alt);
}
//-----------------------------------------------------------------------------
QList<QGeoCoordinate>
QGCGeoBoundingCube::polygon2D() const
{
QList<QGeoCoordinate> coords;
if(isValid()) {
coords.append(QGeoCoordinate(pointNW.latitude(), pointNW.longitude(), pointSE.altitude()));
coords.append(QGeoCoordinate(pointNW.latitude(), pointSE.longitude(), pointSE.altitude()));
coords.append(QGeoCoordinate(pointSE.latitude(), pointSE.longitude(), pointSE.altitude()));
coords.append(QGeoCoordinate(pointSE.latitude(), pointNW.longitude(), pointSE.altitude()));
coords.append(QGeoCoordinate(pointNW.latitude(), pointNW.longitude(), pointSE.altitude()));
}
return coords;
}
//-----------------------------------------------------------------------------
bool
QGCGeoBoundingCube::operator ==(const QList<QGeoCoordinate>& coords) const
{
QList<QGeoCoordinate> c = polygon2D();
if(c.size() != coords.size()) return false;
for(int i = 0; i < c.size(); i++) {
if(c[i] != coords[i]) return false;
}
return true;
}
//-----------------------------------------------------------------------------
double
QGCGeoBoundingCube::width() const
{
if(!isValid())
return 0.0;
QGeoCoordinate ne = QGeoCoordinate(pointNW.latitude(), pointSE.longitude());
return pointNW.distanceTo(ne);
}
//-----------------------------------------------------------------------------
double
QGCGeoBoundingCube::height() const
{
if(!isValid())
return 0.0;
QGeoCoordinate sw = QGeoCoordinate(pointSE.latitude(), pointNW.longitude());
return pointNW.distanceTo(sw);
}
//-----------------------------------------------------------------------------
double
QGCGeoBoundingCube::area() const
{
if(!isValid())
return 0.0;
// Area in km^2
double a = (height() / 1000.0) * (width() / 1000.0);
//qDebug() << "Area:" << a;
return a;
}
//-----------------------------------------------------------------------------
double
QGCGeoBoundingCube::radius() const
{
if(!isValid())
return 0.0;
return pointNW.distanceTo(pointSE) / 2.0;
}
<|endoftext|>
|
<commit_before>/* This file is part of Strigi Desktop Search
*
* Copyright (C) 2006 Jos van den Oever <jos@vandenoever.info>
*
* 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.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "rpminputstream.h"
#include "cpioinputstream.h"
#include "gzipinputstream.h"
#include "bz2inputstream.h"
#include "subinputstream.h"
#include "textutils.h"
#include <list>
using namespace std;
using namespace Strigi;
class RpmInputStream::RpmHeaderInfo {
};
/**
* RPM files as specified here:
* http://www.freestandards.org/spec/refspecs/LSB_1.3.0/gLSB/gLSB/swinstall.html
* and here:
* http://www.rpm.org/max-rpm-snapshot/s1-rpm-file-format-rpm-file-format.html
**/
bool
RpmInputStream::checkHeader(const char* data, int32_t datasize) {
static const char unsigned magic[] = {0xed,0xab,0xee,0xdb,0x03,0x00};
if (datasize < 6) return false;
// this check could be more strict
bool ok = memcmp(data, magic, 6) == 0;
return ok;
}
RpmInputStream::RpmInputStream(InputStream* input)
: SubStreamProvider(input), headerinfo(0) {
uncompressionStream = 0;
cpio = 0;
// skip the header
const char* b;
// lead:96 bytes
if (m_input->read(b, 96, 96) != 96) {
m_status = Error;
m_error = "File is too small to be an RPM file.";
return;
}
// read signature
const unsigned char headmagic[] = {0x8e,0xad,0xe8,0x01};
if (m_input->read(b, 16, 16) != 16 || memcmp(b, headmagic, 4)!=0) {
m_error = "m_error in signature\n";
m_status = Error;
return;
}
int32_t nindex = readBigEndianInt32(b+8);
int32_t hsize = readBigEndianInt32(b+12);
int32_t sz = nindex*16+hsize;
if (sz%8) {
sz+=8-sz%8;
}
if (m_input->read(b, sz, sz) != sz) {
m_status = Error;
m_error = "RPM seems to be truncated or corrupted.";
return;
}
// read header
if (m_input->read(b, 16, 16) != 16 || memcmp(b, headmagic, 4)!=0) {
m_error = "m_error in header\n";
m_status = Error;
return;
}
nindex = readBigEndianInt32(b+8);
hsize = readBigEndianInt32(b+12);
int32_t size = nindex*16+hsize;
if (m_input->read(b, size, size) != size) {
m_error = "could not read header\n";
m_status = Error;
return;
}
for (int32_t i=0; i<nindex; ++i) {
const unsigned char* e = (const unsigned char*)b+i*16;
int32_t tag = readBigEndianInt32(e);
int32_t type = readBigEndianInt32(e+4);
int32_t offset = readBigEndianInt32(e+8);
if (offset < 0 || offset >= hsize) {
m_error = "invalid offset in header\n";
m_status = Error;
return;
}
int32_t count = readBigEndianInt32(e+12);
int32_t end = hsize;
if (i < nindex-1) {
end = readBigEndianInt32(e+8+16);
}
if (end < offset) end = offset;
if (end > hsize) end = hsize;
// TODO actually put the data into the objects so the analyzers can use them
/* if (type == 6) {
string s(b+nindex*16+offset, end-offset);
printf("%s\n", s.c_str());
} else if (type == 8 || type == 9) {
list<string> v;
// TODO handle string arrays
}
printf("%i\t%i\t%i\t%i\n", tag, type, offset, count);*/
}
int64_t pos = m_input->position();
if (m_input->read(b, 16, 16) != 16) {
m_error = "could not read payload\n";
m_status = Error;
return;
}
m_input->reset(pos);
if (BZ2InputStream::checkHeader(b, 16)) {
uncompressionStream = new BZ2InputStream(m_input);
} else {
uncompressionStream = new GZipInputStream(m_input);
}
if (uncompressionStream->status() == Error) {
m_error = uncompressionStream->error();
m_status = Error;
return;
}
cpio = new CpioInputStream(uncompressionStream);
m_status = cpio->status();
}
RpmInputStream::~RpmInputStream() {
if (uncompressionStream) {
delete uncompressionStream;
}
if (cpio) {
delete cpio;
}
if (headerinfo) {
delete headerinfo;
}
}
InputStream*
RpmInputStream::nextEntry() {
if (m_status) return 0;
InputStream* entry = cpio->nextEntry();
m_status = cpio->status();
if (m_status == Ok) {
m_entryinfo = cpio->entryInfo();
} else if (m_status == Error) {
m_error = cpio->error();
}
return entry;
}
<commit_msg>if(bla) delete bla; => delete bla;<commit_after>/* This file is part of Strigi Desktop Search
*
* Copyright (C) 2006 Jos van den Oever <jos@vandenoever.info>
*
* 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.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "rpminputstream.h"
#include "cpioinputstream.h"
#include "gzipinputstream.h"
#include "bz2inputstream.h"
#include "subinputstream.h"
#include "textutils.h"
#include <list>
using namespace std;
using namespace Strigi;
class RpmInputStream::RpmHeaderInfo {
};
/**
* RPM files as specified here:
* http://www.freestandards.org/spec/refspecs/LSB_1.3.0/gLSB/gLSB/swinstall.html
* and here:
* http://www.rpm.org/max-rpm-snapshot/s1-rpm-file-format-rpm-file-format.html
**/
bool
RpmInputStream::checkHeader(const char* data, int32_t datasize) {
static const char unsigned magic[] = {0xed,0xab,0xee,0xdb,0x03,0x00};
if (datasize < 6) return false;
// this check could be more strict
bool ok = memcmp(data, magic, 6) == 0;
return ok;
}
RpmInputStream::RpmInputStream(InputStream* input)
: SubStreamProvider(input), headerinfo(0) {
uncompressionStream = 0;
cpio = 0;
// skip the header
const char* b;
// lead:96 bytes
if (m_input->read(b, 96, 96) != 96) {
m_status = Error;
m_error = "File is too small to be an RPM file.";
return;
}
// read signature
const unsigned char headmagic[] = {0x8e,0xad,0xe8,0x01};
if (m_input->read(b, 16, 16) != 16 || memcmp(b, headmagic, 4)!=0) {
m_error = "m_error in signature\n";
m_status = Error;
return;
}
int32_t nindex = readBigEndianInt32(b+8);
int32_t hsize = readBigEndianInt32(b+12);
int32_t sz = nindex*16+hsize;
if (sz%8) {
sz+=8-sz%8;
}
if (m_input->read(b, sz, sz) != sz) {
m_status = Error;
m_error = "RPM seems to be truncated or corrupted.";
return;
}
// read header
if (m_input->read(b, 16, 16) != 16 || memcmp(b, headmagic, 4)!=0) {
m_error = "m_error in header\n";
m_status = Error;
return;
}
nindex = readBigEndianInt32(b+8);
hsize = readBigEndianInt32(b+12);
int32_t size = nindex*16+hsize;
if (m_input->read(b, size, size) != size) {
m_error = "could not read header\n";
m_status = Error;
return;
}
for (int32_t i=0; i<nindex; ++i) {
const unsigned char* e = (const unsigned char*)b+i*16;
int32_t tag = readBigEndianInt32(e);
int32_t type = readBigEndianInt32(e+4);
int32_t offset = readBigEndianInt32(e+8);
if (offset < 0 || offset >= hsize) {
m_error = "invalid offset in header\n";
m_status = Error;
return;
}
int32_t count = readBigEndianInt32(e+12);
int32_t end = hsize;
if (i < nindex-1) {
end = readBigEndianInt32(e+8+16);
}
if (end < offset) end = offset;
if (end > hsize) end = hsize;
// TODO actually put the data into the objects so the analyzers can use them
/* if (type == 6) {
string s(b+nindex*16+offset, end-offset);
printf("%s\n", s.c_str());
} else if (type == 8 || type == 9) {
list<string> v;
// TODO handle string arrays
}
printf("%i\t%i\t%i\t%i\n", tag, type, offset, count);*/
}
int64_t pos = m_input->position();
if (m_input->read(b, 16, 16) != 16) {
m_error = "could not read payload\n";
m_status = Error;
return;
}
m_input->reset(pos);
if (BZ2InputStream::checkHeader(b, 16)) {
uncompressionStream = new BZ2InputStream(m_input);
} else {
uncompressionStream = new GZipInputStream(m_input);
}
if (uncompressionStream->status() == Error) {
m_error = uncompressionStream->error();
m_status = Error;
return;
}
cpio = new CpioInputStream(uncompressionStream);
m_status = cpio->status();
}
RpmInputStream::~RpmInputStream() {
delete uncompressionStream;
delete cpio;
delete headerinfo;
}
InputStream*
RpmInputStream::nextEntry() {
if (m_status) return 0;
InputStream* entry = cpio->nextEntry();
m_status = cpio->status();
if (m_status == Ok) {
m_entryinfo = cpio->entryInfo();
} else if (m_status == Error) {
m_error = cpio->error();
}
return entry;
}
<|endoftext|>
|
<commit_before>/*******************************************************************************
* SOFA, Simulation Open-Framework Architecture, version 1.0 beta 1 *
* (c) 2006-2007 MGH, INRIA, USTL, UJF, CNRS *
* *
* This library is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Lesser General Public License as published by the *
* Free Software Foundation; either version 2.1 of the License, or (at your *
* option) any later version. *
* *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this library; if not, write to the Free Software Foundation, *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *
* *
* Contact information: contact@sofa-framework.org *
* *
* Authors: J. Allard, P-J. Bensoussan, G. Bousquet, S. Cotin, C. Duriez, *
* H. Delingette, F. Faure, S. Fonteneau, L. Heigeas, C. Mendoza, M. Nesme, *
* P. Neumann and F. Poyer *
*******************************************************************************/
#include <sofa/core/ObjectFactory.h>
#include <sofa/core/componentmodel/behavior/PairInteractionForceField.inl>
#include <sofa/component/forcefield/FrameSpringForceField.inl>
#include <sofa/defaulttype/RigidTypes.h>
namespace sofa
{
namespace core
{
namespace componentmodel
{
namespace behavior
{
template class PairInteractionForceField<Rigid3dTypes>;
template class PairInteractionForceField<Rigid3fTypes>;
}
}
}
namespace component
{
namespace forcefield
{
using namespace sofa::defaulttype;
SOFA_DECL_CLASS ( FrameSpringForceField );
// Register in the Factory
int FrameSpringForceFieldClass = core::RegisterObject ( "Springs for Flexibles" )
.add< FrameSpringForceField<Rigid3dTypes> >()
.add< FrameSpringForceField<Rigid3fTypes> >()
;
template class FrameSpringForceField<Rigid3dTypes>;
template class FrameSpringForceField<Rigid3fTypes>;
} // namespace forcefield
} // namespace component
} // namespace sofa
<commit_msg>r2357/sofa-dev : UPDATE: update float/double for FrameSpringForceField<commit_after>/*******************************************************************************
* SOFA, Simulation Open-Framework Architecture, version 1.0 beta 1 *
* (c) 2006-2007 MGH, INRIA, USTL, UJF, CNRS *
* *
* This library is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Lesser General Public License as published by the *
* Free Software Foundation; either version 2.1 of the License, or (at your *
* option) any later version. *
* *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this library; if not, write to the Free Software Foundation, *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *
* *
* Contact information: contact@sofa-framework.org *
* *
* Authors: J. Allard, P-J. Bensoussan, G. Bousquet, S. Cotin, C. Duriez, *
* H. Delingette, F. Faure, S. Fonteneau, L. Heigeas, C. Mendoza, M. Nesme, *
* P. Neumann and F. Poyer *
*******************************************************************************/
#include <sofa/core/ObjectFactory.h>
#include <sofa/core/componentmodel/behavior/PairInteractionForceField.inl>
#include <sofa/component/forcefield/FrameSpringForceField.inl>
#include <sofa/defaulttype/RigidTypes.h>
namespace sofa
{
namespace component
{
namespace forcefield
{
using namespace sofa::defaulttype;
SOFA_DECL_CLASS ( FrameSpringForceField );
// Register in the Factory
int FrameSpringForceFieldClass = core::RegisterObject ( "Springs for Flexibles" )
#ifndef SOFA_FLOAT
.add< FrameSpringForceField<Rigid3dTypes> >()
#endif
#ifndef SOFA_DOUBLE
.add< FrameSpringForceField<Rigid3fTypes> >()
#endif
;
#ifndef SOFA_FLOAT
template class FrameSpringForceField<Rigid3dTypes>;
#endif
#ifndef SOFA_DOUBLE
template class FrameSpringForceField<Rigid3fTypes>;
#endif
} // namespace forcefield
} // namespace component
} // namespace sofa
<|endoftext|>
|
<commit_before>/*
ExtendOSC.cpp
Created by Joshua Shinavier, 2014
Released into the public domain.
*/
#include "ExtendOSC.h"
#ifdef BOARD_HAS_USB_SERIAL
#include <SLIPEncodedUSBSerial.h>
SLIPEncodedUSBSerial SLIPSerial(thisBoardsSerialUSB);
#else
#include <SLIPEncodedSerial.h>
SLIPEncodedSerial SLIPSerial(Serial);
#endif
ExtendOSC::ExtendOSC(const char *prefix)
{
_addressPrefix = prefix;
}
void ExtendOSC::beginSerial() {
// OSCuino: begin SLIPSerial just like Serial
// set this as high as you can reliably run on your platform
SLIPSerial.begin(115200);
/*
#if ARDUINO >= 100
while(!Serial); // for Arduino Leonardo
#endif
*/
#if ARDUINO >= 100
#ifdef BOARD_HAS_USB_SERIAL
while(!thisBoardsSerialUSB);
#else
while(!Serial);
#endif
#endif
}
int ExtendOSC::receiveOSC(class OSCMessage &messageIn) {
int done = SLIPSerial.endofPacket();
int size;
while ((size = SLIPSerial.available()) > 0) {
while (size--) {
int c = SLIPSerial.read();
messageIn.fill(c);
//sprintf(errstr, "received a byte: %d. bytes: %d, size: %d, hasError: %d", c, messageIn2.bytes(), messageIn2.size(), messageIn2.hasError());
//sendInfo(errstr);
}
}
return done || SLIPSerial.endofPacket();
}
int ExtendOSC::receiveOSCBundle(class OSCBundle &bundleIn) {
int done = SLIPSerial.endofPacket();
int size;
while ((size = SLIPSerial.available()) > 0) {
while (size--) {
int c = SLIPSerial.read();
bundleIn.fill(c);
}
}
return done || SLIPSerial.endofPacket();
}
void ExtendOSC::sendOSC(class OSCMessage &messageOut) {
SLIPSerial.beginPacket();
messageOut.send(SLIPSerial); // send the bytes to the SLIP stream
SLIPSerial.endPacket(); // mark the end of the OSC Packet
messageOut.empty(); // free the space occupied by the message
}
void ExtendOSC::sendInfo(const char *msg, ...)
{
va_list argptr;
va_start(argptr, msg);
vsprintf(_messageBuffer, msg, argptr);
va_end(argptr);
sprintf(_addressBuffer, "%s/info", _addressPrefix);
OSCMessage m(_addressBuffer);
m.add(_messageBuffer);
sendOSC(m);
}
void ExtendOSC::sendError(const char *msg, ...)
{
va_list argptr;
va_start(argptr, msg);
vsprintf(_messageBuffer, msg, argptr);
va_end(argptr);
sprintf(_addressBuffer, "%s/error", _addressPrefix);
OSCMessage m(_addressBuffer);
m.add(_messageBuffer);
sendOSC(m);
}
const char *BUFFER_FULL_msg = "BUFFER_FULL",
*INVALID_OSC_msg = "INVALID_OSC",
*ALLOCFAILED_msg = "ALLOCFAILED",
*INDEX_OUT_OF_BOUNDS_msg = "INDEX_OUT_OF_BOUNDS",
*unknown_msg = "unknown";
void ExtendOSC::sendOSCError(OSCErrorCode code) {
const char *name;
switch(code) {
case BUFFER_FULL:
name = BUFFER_FULL_msg;
break;
case INVALID_OSC:
name = INVALID_OSC_msg;
break;
case ALLOCFAILED:
name = ALLOCFAILED_msg;
break;
case INDEX_OUT_OF_BOUNDS:
name = INDEX_OUT_OF_BOUNDS_msg;
break;
default:
name = unknown_msg;
}
sendError("OSC message hasError (error type: %s)", name);
}
void ExtendOSC::sendOSCMessageError(class OSCMessage &message) {
OSCErrorCode code = message.getError();
sendOSCError(code);
}
void ExtendOSC::sendOSCBundleError(class OSCBundle &bundle) {
OSCErrorCode code = bundle.getError();
sendOSCError(code);
}
int ExtendOSC::validArgs(class OSCMessage &m, int totalExpected) {
if (totalExpected != m.size()) {
sendError("got %d argument(s), expected %d", m.size(), totalExpected);
return 0;
} else {
return 1;
}
}<commit_msg>Keep OSC messages from Arduino below the Bluetooth SPP limit of 128 bytes<commit_after>/*
ExtendOSC.cpp
Created by Joshua Shinavier, 2014
Released into the public domain.
*/
#include "ExtendOSC.h"
#ifdef BOARD_HAS_USB_SERIAL
#include <SLIPEncodedUSBSerial.h>
SLIPEncodedUSBSerial SLIPSerial(thisBoardsSerialUSB);
#else
#include <SLIPEncodedSerial.h>
SLIPEncodedSerial SLIPSerial(Serial);
#endif
ExtendOSC::ExtendOSC(const char *prefix)
{
_addressPrefix = prefix;
}
void ExtendOSC::beginSerial() {
// OSCuino: begin SLIPSerial just like Serial
// set this as high as you can reliably run on your platform
SLIPSerial.begin(115200);
/*
#if ARDUINO >= 100
while(!Serial); // for Arduino Leonardo
#endif
*/
#if ARDUINO >= 100
#ifdef BOARD_HAS_USB_SERIAL
while(!thisBoardsSerialUSB);
#else
while(!Serial);
#endif
#endif
}
int ExtendOSC::receiveOSC(class OSCMessage &messageIn) {
int done = SLIPSerial.endofPacket();
int size;
while ((size = SLIPSerial.available()) > 0) {
while (size--) {
int c = SLIPSerial.read();
messageIn.fill(c);
//sprintf(errstr, "received a byte: %d. bytes: %d, size: %d, hasError: %d", c, messageIn2.bytes(), messageIn2.size(), messageIn2.hasError());
//sendInfo(errstr);
}
}
return done || SLIPSerial.endofPacket();
}
int ExtendOSC::receiveOSCBundle(class OSCBundle &bundleIn) {
int done = SLIPSerial.endofPacket();
int size;
while ((size = SLIPSerial.available()) > 0) {
while (size--) {
int c = SLIPSerial.read();
bundleIn.fill(c);
}
}
return done || SLIPSerial.endofPacket();
}
void ExtendOSC::sendOSC(class OSCMessage &messageOut) {
// 128 bytes is the maximum payload capacity of Bluetooth SPP (Serial Port Profile)
if (messageOut.bytes() > 128) {
sendError("message is %d bytes long, exceeding limit of 128 bytes")
}
SLIPSerial.beginPacket();
messageOut.send(SLIPSerial); // send the bytes to the SLIP stream
SLIPSerial.endPacket(); // mark the end of the OSC Packet
messageOut.empty(); // free the space occupied by the message
}
void ExtendOSC::sendInfo(const char *msg, ...)
{
va_list argptr;
va_start(argptr, msg);
vsprintf(_messageBuffer, msg, argptr);
va_end(argptr);
sprintf(_addressBuffer, "%s/info", _addressPrefix);
OSCMessage m(_addressBuffer);
m.add(_messageBuffer);
sendOSC(m);
}
void ExtendOSC::sendError(const char *msg, ...)
{
va_list argptr;
va_start(argptr, msg);
vsprintf(_messageBuffer, msg, argptr);
va_end(argptr);
sprintf(_addressBuffer, "%s/error", _addressPrefix);
OSCMessage m(_addressBuffer);
m.add(_messageBuffer);
sendOSC(m);
}
const char *BUFFER_FULL_msg = "BUFFER_FULL",
*INVALID_OSC_msg = "INVALID_OSC",
*ALLOCFAILED_msg = "ALLOCFAILED",
*INDEX_OUT_OF_BOUNDS_msg = "INDEX_OUT_OF_BOUNDS",
*unknown_msg = "unknown";
void ExtendOSC::sendOSCError(OSCErrorCode code) {
const char *name;
switch(code) {
case BUFFER_FULL:
name = BUFFER_FULL_msg;
break;
case INVALID_OSC:
name = INVALID_OSC_msg;
break;
case ALLOCFAILED:
name = ALLOCFAILED_msg;
break;
case INDEX_OUT_OF_BOUNDS:
name = INDEX_OUT_OF_BOUNDS_msg;
break;
default:
name = unknown_msg;
}
sendError("OSC message hasError (error type: %s)", name);
}
void ExtendOSC::sendOSCMessageError(class OSCMessage &message) {
OSCErrorCode code = message.getError();
sendOSCError(code);
}
void ExtendOSC::sendOSCBundleError(class OSCBundle &bundle) {
OSCErrorCode code = bundle.getError();
sendOSCError(code);
}
int ExtendOSC::validArgs(class OSCMessage &m, int totalExpected) {
if (totalExpected != m.size()) {
sendError("got %d argument(s), expected %d", m.size(), totalExpected);
return 0;
} else {
return 1;
}
}<|endoftext|>
|
<commit_before>#include "instanciate.h"
using namespace Yuni;
namespace ny
{
namespace Pass
{
namespace Instanciate
{
namespace {
void pragmaBodyStart(SequenceBuilder& seq)
{
assert(seq.frame != nullptr);
assert(not seq.signatureOnly);
assert(seq.codeGenerationLock == 0 and "any good reason to not generate code ?");
assert(seq.out != nullptr and "no output IR sequence");
auto& frame = *seq.frame;
auto& atom = frame.atom;
if (not atom.isFunction())
return;
bool generateCode = seq.canGenerateCode();
uint32_t count = atom.parameters.size();
atom.parameters.each([&](uint32_t i, const AnyString& name, const Vardef& vardef)
{
// lvid for the given parameter
uint32_t lvid = i + 1 + 1; // 1: return type, 2: first parameter
assert(lvid < frame.lvids.size());
// Obviously, the parameters are not synthetic objects
// but real variables
frame.lvids[lvid].synthetic = false;
// Parameters Deep copy (if required)
if (name[0] != '^')
{
// normal input parameter (not captured - does not start with '^')
// clone it if necessary (only non-ref parameters)
if (not seq.cdeftable.classdef(vardef.clid).qualifiers.ref)
{
if (debugmode and generateCode)
seq.out->emitComment(String{"----- deep copy parameter "} << i << " aka " << name);
// a register has already been reserved for cloning parameters
uint32_t clone = 2 + count + i; // 1: return type, 2: first parameter
assert(clone < frame.lvids.size());
// the new value is not synthetic
frame.lvids[clone].synthetic = false;
bool r = seq.instanciateAssignment(frame, clone, lvid, false, false, true);
if (unlikely(not r))
frame.invalidate(clone);
if (seq.canBeAcquired(lvid))
{
frame.lvids[lvid].autorelease = true;
frame.lvids[clone].autorelease = false;
}
if (generateCode)
{
seq.out->emitStore(lvid, clone); // register swap
if (debugmode)
seq.out->emitComment("--\n");
}
}
}
});
// generating some code on the fly
if (atom.isSpecial() /*ctor, operators...*/ and generateCode)
{
// variables initialization (for a ctor)
if (seq.generateClassVarsAutoInit)
{
seq.generateClassVarsAutoInit = false;
seq.generateMemberVarDefaultInitialization();
}
// variables destruction (for dtor)
if (seq.generateClassVarsAutoRelease)
{
seq.generateClassVarsAutoRelease = false;
seq.generateMemberVarDefaultDispose();
}
// variables cloning (copy a ctor)
if (seq.generateClassVarsAutoClone)
{
seq.generateClassVarsAutoClone = false;
seq.generateMemberVarDefaultClone();
}
}
}
void pragmaCodegen(SequenceBuilder& seq, bool onoff)
{
auto& refcount = seq.codeGenerationLock;
if (onoff)
{
if (refcount > 0) // re-enable code generation
--refcount;
}
else
++refcount;
}
void pragmaBlueprintSize(SequenceBuilder& seq, uint32_t opcodeCount)
{
if (0 == seq.layerDepthLimit)
{
// ignore the current blueprint
//*cursor += operands.value.blueprintsize;
assert(seq.frame != nullptr);
assert(seq.frame->offsetOpcodeBlueprint != (uint32_t) -1);
auto startOffset = seq.frame->offsetOpcodeBlueprint;
if (unlikely(opcodeCount < 3))
return (void) (ice() << "invalid blueprint size when instanciating atom");
// goto the end of the blueprint
// -2: the final 'end' opcode must be interpreted
*seq.cursor = &seq.currentSequence.at(startOffset + opcodeCount - 1 - 1);
}
}
void pragmaShortcircuitMutateToBool(SequenceBuilder& seq, const IR::ISA::Operand<IR::ISA::Op::pragma>& operands)
{
uint32_t lvid = operands.value.shortcircuitMutate.lvid;
uint32_t source = operands.value.shortcircuitMutate.source;
seq.frame->lvids[lvid].synthetic = false;
if (true)
{
auto& instr = *(*seq.cursor - 1);
assert(instr.opcodes[0] == static_cast<uint32_t>(IR::ISA::Op::stackalloc));
uint32_t sizeoflvid = instr.to<IR::ISA::Op::stackalloc>().lvid;
// sizeof
auto& atombool = *(seq.cdeftable.atoms().core.object[nyt_bool]);
seq.out->emitSizeof(sizeoflvid, atombool.atomid);
auto& opc = seq.cdeftable.substitute(lvid);
opc.mutateToAtom(&atombool);
opc.qualifiers.ref = true;
// ALLOC: memory allocation of the new temporary object
seq.out->emitMemalloc(lvid, sizeoflvid);
seq.out->emitRef(lvid);
seq.frame->lvids[lvid].autorelease = true;
// reset the internal value of the object
seq.out->emitFieldset(source, /*self*/lvid, 0); // builtin
}
else
seq.out->emitStore(lvid, source);
}
} // anonymous namespace
void SequenceBuilder::visit(const IR::ISA::Operand<IR::ISA::Op::pragma>& operands)
{
assert(static_cast<uint32_t>(operands.pragma) < IR::ISA::PragmaCount);
auto pragma = static_cast<IR::ISA::Pragma>(operands.pragma);
switch (pragma)
{
case IR::ISA::Pragma::codegen:
{
pragmaCodegen(*this, operands.value.codegen != 0);
break;
}
case IR::ISA::Pragma::bodystart:
{
// In 'signature only' mode, we only care about the
// parameter user types. Everything from this point in unrelevant
if (signatureOnly)
currentSequence.invalidateCursor(*cursor);
else
pragmaBodyStart(*this); // params deep copy, implicit var auto-init...
break;
}
case IR::ISA::Pragma::blueprintsize:
{
pragmaBlueprintSize(*this, operands.value.blueprintsize);
break;
}
case IR::ISA::Pragma::visibility:
{
assert(frame != nullptr);
break;
}
case IR::ISA::Pragma::shortcircuitOpNopOffset:
{
shortcircuit.label = operands.value.shortcircuitMetadata.label;
break;
}
case IR::ISA::Pragma::shortcircuitMutateToBool:
{
pragmaShortcircuitMutateToBool(*this, operands);
break;
}
case IR::ISA::Pragma::synthetic:
{
uint32_t lvid = operands.value.synthetic.lvid;
bool onoff = (operands.value.synthetic.onoff != 0);
frame->lvids[lvid].synthetic = onoff;
break;
}
case IR::ISA::Pragma::suggest:
case IR::ISA::Pragma::builtinalias:
case IR::ISA::Pragma::shortcircuit:
case IR::ISA::Pragma::unknown:
break;
}
}
} // namespace Instanciate
} // namespace Pass
} // namespace ny
<commit_msg>added param type check<commit_after>#include "instanciate.h"
using namespace Yuni;
namespace ny
{
namespace Pass
{
namespace Instanciate
{
namespace {
void pragmaBodyStart(SequenceBuilder& seq)
{
assert(seq.frame != nullptr);
assert(not seq.signatureOnly);
assert(seq.codeGenerationLock == 0 and "any good reason to not generate code ?");
assert(seq.out != nullptr and "no output IR sequence");
auto& frame = *seq.frame;
auto& atom = frame.atom;
if (not atom.isFunction())
return;
bool generateCode = seq.canGenerateCode();
uint32_t count = atom.parameters.size();
atom.parameters.each([&](uint32_t i, const AnyString& name, const Vardef& vardef)
{
// lvid for the given parameter
uint32_t lvid = i + 1 + 1; // 1: return type, 2: first parameter
assert(lvid < frame.lvids.size());
// Obviously, the parameters are not synthetic objects
// but real variables
frame.lvids[lvid].synthetic = false;
// Parameters Deep copy (if required)
auto& cdef = seq.cdeftable.classdef(vardef.clid);
if (name[0] != '^')
{
// normal input parameter (not captured - does not start with '^')
// clone it if necessary (only non-ref parameters)
if (not cdef.qualifiers.ref)
{
if (debugmode and generateCode)
seq.out->emitComment(String{"----- deep copy parameter "} << i << " aka " << name);
// a register has already been reserved for cloning parameters
uint32_t clone = 2 + count + i; // 1: return type, 2: first parameter
assert(clone < frame.lvids.size());
// the new value is not synthetic
frame.lvids[clone].synthetic = false;
bool r = seq.instanciateAssignment(frame, clone, lvid, false, false, true);
if (unlikely(not r))
frame.invalidate(clone);
if (seq.canBeAcquired(lvid))
{
frame.lvids[lvid].autorelease = true;
frame.lvids[clone].autorelease = false;
}
if (generateCode)
{
seq.out->emitStore(lvid, clone); // register swap
if (debugmode)
seq.out->emitComment("--\n");
}
}
}
if (not cdef.isBuiltinOrVoid())
{
auto* paramatom = seq.cdeftable.findClassdefAtom(cdef);
if (unlikely(!paramatom))
{
frame.invalidate(lvid);
ice() << "invalid parameter type " << i << " for " << atom.caption(seq.cdeftable);
}
}
});
// generating some code on the fly
if (atom.isSpecial() /*ctor, operators...*/ and generateCode)
{
// variables initialization (for a ctor)
if (seq.generateClassVarsAutoInit)
{
seq.generateClassVarsAutoInit = false;
seq.generateMemberVarDefaultInitialization();
}
// variables destruction (for dtor)
if (seq.generateClassVarsAutoRelease)
{
seq.generateClassVarsAutoRelease = false;
seq.generateMemberVarDefaultDispose();
}
// variables cloning (copy a ctor)
if (seq.generateClassVarsAutoClone)
{
seq.generateClassVarsAutoClone = false;
seq.generateMemberVarDefaultClone();
}
}
}
void pragmaCodegen(SequenceBuilder& seq, bool onoff)
{
auto& refcount = seq.codeGenerationLock;
if (onoff)
{
if (refcount > 0) // re-enable code generation
--refcount;
}
else
++refcount;
}
void pragmaBlueprintSize(SequenceBuilder& seq, uint32_t opcodeCount)
{
if (0 == seq.layerDepthLimit)
{
// ignore the current blueprint
//*cursor += operands.value.blueprintsize;
assert(seq.frame != nullptr);
assert(seq.frame->offsetOpcodeBlueprint != (uint32_t) -1);
auto startOffset = seq.frame->offsetOpcodeBlueprint;
if (unlikely(opcodeCount < 3))
return (void) (ice() << "invalid blueprint size when instanciating atom");
// goto the end of the blueprint
// -2: the final 'end' opcode must be interpreted
*seq.cursor = &seq.currentSequence.at(startOffset + opcodeCount - 1 - 1);
}
}
void pragmaShortcircuitMutateToBool(SequenceBuilder& seq, const IR::ISA::Operand<IR::ISA::Op::pragma>& operands)
{
uint32_t lvid = operands.value.shortcircuitMutate.lvid;
uint32_t source = operands.value.shortcircuitMutate.source;
seq.frame->lvids[lvid].synthetic = false;
if (true)
{
auto& instr = *(*seq.cursor - 1);
assert(instr.opcodes[0] == static_cast<uint32_t>(IR::ISA::Op::stackalloc));
uint32_t sizeoflvid = instr.to<IR::ISA::Op::stackalloc>().lvid;
// sizeof
auto& atombool = *(seq.cdeftable.atoms().core.object[nyt_bool]);
seq.out->emitSizeof(sizeoflvid, atombool.atomid);
auto& opc = seq.cdeftable.substitute(lvid);
opc.mutateToAtom(&atombool);
opc.qualifiers.ref = true;
// ALLOC: memory allocation of the new temporary object
seq.out->emitMemalloc(lvid, sizeoflvid);
seq.out->emitRef(lvid);
seq.frame->lvids[lvid].autorelease = true;
// reset the internal value of the object
seq.out->emitFieldset(source, /*self*/lvid, 0); // builtin
}
else
seq.out->emitStore(lvid, source);
}
} // anonymous namespace
void SequenceBuilder::visit(const IR::ISA::Operand<IR::ISA::Op::pragma>& operands)
{
assert(static_cast<uint32_t>(operands.pragma) < IR::ISA::PragmaCount);
auto pragma = static_cast<IR::ISA::Pragma>(operands.pragma);
switch (pragma)
{
case IR::ISA::Pragma::codegen:
{
pragmaCodegen(*this, operands.value.codegen != 0);
break;
}
case IR::ISA::Pragma::bodystart:
{
// In 'signature only' mode, we only care about the
// parameter user types. Everything from this point in unrelevant
if (signatureOnly)
currentSequence.invalidateCursor(*cursor);
else
pragmaBodyStart(*this); // params deep copy, implicit var auto-init...
break;
}
case IR::ISA::Pragma::blueprintsize:
{
pragmaBlueprintSize(*this, operands.value.blueprintsize);
break;
}
case IR::ISA::Pragma::visibility:
{
assert(frame != nullptr);
break;
}
case IR::ISA::Pragma::shortcircuitOpNopOffset:
{
shortcircuit.label = operands.value.shortcircuitMetadata.label;
break;
}
case IR::ISA::Pragma::shortcircuitMutateToBool:
{
pragmaShortcircuitMutateToBool(*this, operands);
break;
}
case IR::ISA::Pragma::synthetic:
{
uint32_t lvid = operands.value.synthetic.lvid;
bool onoff = (operands.value.synthetic.onoff != 0);
frame->lvids[lvid].synthetic = onoff;
break;
}
case IR::ISA::Pragma::suggest:
case IR::ISA::Pragma::builtinalias:
case IR::ISA::Pragma::shortcircuit:
case IR::ISA::Pragma::unknown:
break;
}
}
} // namespace Instanciate
} // namespace Pass
} // namespace ny
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2013, Ford Motor Company
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following
disclaimer in the documentation and/or other materials provided with the
distribution.
Neither the name of the Ford Motor Company nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include <vector>
#include <string>
#include <stdio.h>
#include "application_manager/commands/mobile/system_request.h"
#include "application_manager/application_manager_impl.h"
#include "application_manager/application_impl.h"
#include "interfaces/MOBILE_API.h"
#include "config_profile/profile.h"
#include "utils/file_system.h"
#include "formatters/CFormatterJsonBase.hpp"
#include "json/json.h"
namespace application_manager {
namespace commands {
uint32_t SystemRequest::index = 0;
SystemRequest::SystemRequest(const MessageSharedPtr& message)
: CommandRequestImpl(message) {
}
SystemRequest::~SystemRequest() {
}
void SystemRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
ApplicationSharedPtr application =
ApplicationManagerImpl::instance()->application(connection_key());
if (!(application.valid())) {
LOG4CXX_ERROR(logger_, "NULL pointer");
SendResponse(false, mobile_apis::Result::APPLICATION_NOT_REGISTERED);
return;
}
const mobile_apis::RequestType::eType request_type =
static_cast<mobile_apis::RequestType::eType>(
(*message_)[strings::msg_params][strings::request_type].asInt());
if (!(*message_)[strings::params].keyExists(strings::binary_data) &&
(mobile_apis::RequestType::PROPRIETARY == request_type ||
mobile_apis::RequestType::QUERY_APPS == request_type)) {
LOG4CXX_ERROR(logger_, "Binary data empty");
SendResponse(false, mobile_apis::Result::INVALID_DATA);
return;
}
std::vector<uint8_t> binary_data;
if ((*message_)[strings::params].keyExists(strings::binary_data)) {
binary_data = (*message_)[strings::params][strings::binary_data].asBinary();
}
if (mobile_apis::RequestType::QUERY_APPS == request_type) {
using namespace NsSmartDeviceLink::NsJSONHandler::Formatters;
const std::string json(binary_data.begin(), binary_data.end());
Json::Value value;
Json::Reader reader;
if (!reader.parse(json.c_str(), value)) {
LOG4CXX_ERROR(logger_, "Can't parse json received from QueryApps.");
return;
}
smart_objects::SmartObject sm_object;
CFormatterJsonBase::jsonValueToObj(value, sm_object);
if (!ValidateQueryAppData(sm_object)) {
SendResponse(false, mobile_apis::Result::INVALID_DATA);
return;
}
ApplicationManagerImpl::instance()->ProcessQueryApp(sm_object,
connection_key());
SendResponse(true, mobile_apis::Result::SUCCESS);
return;
}
std::string file_path = profile::Profile::instance()->system_files_path();
if (!file_system::CreateDirectoryRecursively(file_path)) {
LOG4CXX_ERROR(logger_, "Cann't create folder.");
SendResponse(false, mobile_apis::Result::GENERIC_ERROR);
return;
}
std::string file_name = "SYNC";
if ((*message_)[strings::msg_params].keyExists(strings::file_name)) {
file_name = (*message_)[strings::msg_params][strings::file_name].asString();
}
// to avoid override existing file
const uint8_t max_size = 255;
char buf[max_size] = {'\0'};
snprintf(buf, sizeof(buf)/sizeof(buf[0]), "%d%s", index++, file_name.c_str());
file_name = buf;
std::string full_file_path = file_path + "/" + file_name;
if (binary_data.size()) {
if (mobile_apis::Result::SUCCESS !=
(ApplicationManagerImpl::instance()->SaveBinary(
binary_data, file_path, file_name, 0))) {
SendResponse(false, mobile_apis::Result::GENERIC_ERROR);
return;
}
} else {
if (!(file_system::CreateFile(full_file_path))) {
SendResponse(false, mobile_apis::Result::GENERIC_ERROR);
return;
}
}
smart_objects::SmartObject msg_params = smart_objects::SmartObject(
smart_objects::SmartType_Map);
if (std::string::npos != file_name.find("IVSU")) {
msg_params[strings::file_name] = file_name.c_str();
} else {
msg_params[strings::file_name] = full_file_path;
}
if (mobile_apis::RequestType::PROPRIETARY != request_type) {
msg_params[strings::app_id] = (application->mobile_app_id());
}
msg_params[strings::request_type] =
(*message_)[strings::msg_params][strings::request_type];
SendHMIRequest(hmi_apis::FunctionID::BasicCommunication_SystemRequest,
&msg_params, true);
}
void SystemRequest::on_event(const event_engine::Event& event) {
LOG4CXX_INFO(logger_, "AddSubMenuRequest::on_event");
const smart_objects::SmartObject& message = event.smart_object();
switch (event.id()) {
case hmi_apis::FunctionID::BasicCommunication_SystemRequest: {
mobile_apis::Result::eType result_code =
GetMobileResultCode(static_cast<hmi_apis::Common_Result::eType>(
message[strings::params][hmi_response::code].asUInt()));
bool result = mobile_apis::Result::SUCCESS == result_code;
ApplicationSharedPtr application =
ApplicationManagerImpl::instance()->application(connection_key());
if (!(application.valid())) {
LOG4CXX_ERROR(logger_, "NULL pointer");
return;
}
SendResponse(result, result_code, NULL, &(message[strings::msg_params]));
break;
}
default: {
LOG4CXX_ERROR(logger_, "Received unknown event" << event.id());
return;
}
}
}
bool SystemRequest::ValidateQueryAppData(
const smart_objects::SmartObject& data) const {
if (!data.isValid()) {
LOG4CXX_ERROR(logger_, "QueryApps response is not valid.");
return false;
}
if (!data.keyExists(json::response)) {
LOG4CXX_ERROR(logger_,
"QueryApps response does not contain '"
<< json::response << "' parameter.");
return false;
}
smart_objects::SmartArray* obj_array = data[json::response].asArray();
if (NULL == obj_array) {
return false;
}
const std::size_t arr_size(obj_array->size());
for (std::size_t idx = 0; idx < arr_size; ++idx) {
const smart_objects::SmartObject& app_data = (*obj_array)[idx];
if (!app_data.isValid()) {
LOG4CXX_ERROR(logger_, "Wrong application data in json file.");
continue;
}
std::string os_type;
if (app_data.keyExists(json::ios)) {
os_type = json::ios;
if (!app_data[os_type].keyExists(json::urlScheme)) {
LOG4CXX_ERROR(logger_, "Can't find URL scheme in json file.");
continue;
}
} else if (app_data.keyExists(json::android)) {
os_type = json::android;
if (!app_data[os_type].keyExists(json::packageName)) {
LOG4CXX_ERROR(logger_, "Can't find package name in json file.");
continue;
}
}
if (os_type.empty()) {
LOG4CXX_ERROR(logger_, "Can't find mobile OS type in json file.");
continue;
}
if (!app_data.keyExists(json::appId)) {
LOG4CXX_ERROR(logger_, "Can't find app ID in json file.");
continue;
}
if (!app_data.keyExists(json::name)) {
LOG4CXX_ERROR(logger_, "Can't find app name in json file.");
continue;
}
return true;
}
return true;
}
} // namespace commands
} // namespace application_manager
<commit_msg>APPLINK-11451 Fix validation of query_app json<commit_after>/*
Copyright (c) 2013, Ford Motor Company
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following
disclaimer in the documentation and/or other materials provided with the
distribution.
Neither the name of the Ford Motor Company nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include <vector>
#include <string>
#include <stdio.h>
#include "application_manager/commands/mobile/system_request.h"
#include "application_manager/application_manager_impl.h"
#include "application_manager/application_impl.h"
#include "interfaces/MOBILE_API.h"
#include "config_profile/profile.h"
#include "utils/file_system.h"
#include "formatters/CFormatterJsonBase.hpp"
#include "json/json.h"
namespace application_manager {
namespace commands {
uint32_t SystemRequest::index = 0;
SystemRequest::SystemRequest(const MessageSharedPtr& message)
: CommandRequestImpl(message) {
}
SystemRequest::~SystemRequest() {
}
void SystemRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
ApplicationSharedPtr application =
ApplicationManagerImpl::instance()->application(connection_key());
if (!(application.valid())) {
LOG4CXX_ERROR(logger_, "NULL pointer");
SendResponse(false, mobile_apis::Result::APPLICATION_NOT_REGISTERED);
return;
}
const mobile_apis::RequestType::eType request_type =
static_cast<mobile_apis::RequestType::eType>(
(*message_)[strings::msg_params][strings::request_type].asInt());
if (!(*message_)[strings::params].keyExists(strings::binary_data) &&
(mobile_apis::RequestType::PROPRIETARY == request_type ||
mobile_apis::RequestType::QUERY_APPS == request_type)) {
LOG4CXX_ERROR(logger_, "Binary data empty");
SendResponse(false, mobile_apis::Result::INVALID_DATA);
return;
}
std::vector<uint8_t> binary_data;
if ((*message_)[strings::params].keyExists(strings::binary_data)) {
binary_data = (*message_)[strings::params][strings::binary_data].asBinary();
}
if (mobile_apis::RequestType::QUERY_APPS == request_type) {
using namespace NsSmartDeviceLink::NsJSONHandler::Formatters;
const std::string json(binary_data.begin(), binary_data.end());
Json::Value value;
Json::Reader reader;
if (!reader.parse(json.c_str(), value)) {
LOG4CXX_ERROR(logger_, "Can't parse json received from QueryApps.");
return;
}
smart_objects::SmartObject sm_object;
CFormatterJsonBase::jsonValueToObj(value, sm_object);
if (!ValidateQueryAppData(sm_object)) {
SendResponse(false, mobile_apis::Result::INVALID_DATA);
return;
}
ApplicationManagerImpl::instance()->ProcessQueryApp(sm_object,
connection_key());
SendResponse(true, mobile_apis::Result::SUCCESS);
return;
}
std::string file_path = profile::Profile::instance()->system_files_path();
if (!file_system::CreateDirectoryRecursively(file_path)) {
LOG4CXX_ERROR(logger_, "Cann't create folder.");
SendResponse(false, mobile_apis::Result::GENERIC_ERROR);
return;
}
std::string file_name = "SYNC";
if ((*message_)[strings::msg_params].keyExists(strings::file_name)) {
file_name = (*message_)[strings::msg_params][strings::file_name].asString();
}
// to avoid override existing file
const uint8_t max_size = 255;
char buf[max_size] = {'\0'};
snprintf(buf, sizeof(buf)/sizeof(buf[0]), "%d%s", index++, file_name.c_str());
file_name = buf;
std::string full_file_path = file_path + "/" + file_name;
if (binary_data.size()) {
if (mobile_apis::Result::SUCCESS !=
(ApplicationManagerImpl::instance()->SaveBinary(
binary_data, file_path, file_name, 0))) {
SendResponse(false, mobile_apis::Result::GENERIC_ERROR);
return;
}
} else {
if (!(file_system::CreateFile(full_file_path))) {
SendResponse(false, mobile_apis::Result::GENERIC_ERROR);
return;
}
}
smart_objects::SmartObject msg_params = smart_objects::SmartObject(
smart_objects::SmartType_Map);
if (std::string::npos != file_name.find("IVSU")) {
msg_params[strings::file_name] = file_name.c_str();
} else {
msg_params[strings::file_name] = full_file_path;
}
if (mobile_apis::RequestType::PROPRIETARY != request_type) {
msg_params[strings::app_id] = (application->mobile_app_id());
}
msg_params[strings::request_type] =
(*message_)[strings::msg_params][strings::request_type];
SendHMIRequest(hmi_apis::FunctionID::BasicCommunication_SystemRequest,
&msg_params, true);
}
void SystemRequest::on_event(const event_engine::Event& event) {
LOG4CXX_INFO(logger_, "AddSubMenuRequest::on_event");
const smart_objects::SmartObject& message = event.smart_object();
switch (event.id()) {
case hmi_apis::FunctionID::BasicCommunication_SystemRequest: {
mobile_apis::Result::eType result_code =
GetMobileResultCode(static_cast<hmi_apis::Common_Result::eType>(
message[strings::params][hmi_response::code].asUInt()));
bool result = mobile_apis::Result::SUCCESS == result_code;
ApplicationSharedPtr application =
ApplicationManagerImpl::instance()->application(connection_key());
if (!(application.valid())) {
LOG4CXX_ERROR(logger_, "NULL pointer");
return;
}
SendResponse(result, result_code, NULL, &(message[strings::msg_params]));
break;
}
default: {
LOG4CXX_ERROR(logger_, "Received unknown event" << event.id());
return;
}
}
}
bool SystemRequest::ValidateQueryAppData(
const smart_objects::SmartObject& data) const {
if (!data.isValid()) {
LOG4CXX_ERROR(logger_, "QueryApps response is not valid.");
return false;
}
if (!data.keyExists(json::response)) {
LOG4CXX_ERROR(logger_,
"QueryApps response does not contain '"
<< json::response << "' parameter.");
return false;
}
smart_objects::SmartArray* obj_array = data[json::response].asArray();
if (NULL == obj_array) {
return false;
}
const std::size_t arr_size(obj_array->size());
for (std::size_t idx = 0; idx < arr_size; ++idx) {
const smart_objects::SmartObject& app_data = (*obj_array)[idx];
if (!app_data.isValid()) {
LOG4CXX_ERROR(logger_, "Wrong application data in json file.");
continue;
}
std::string os_type;
if (app_data.keyExists(json::ios)) {
os_type = json::ios;
if (!app_data[os_type].keyExists(json::urlScheme)) {
LOG4CXX_ERROR(logger_, "Can't find URL scheme in json file.");
continue;
}
} else if (app_data.keyExists(json::android)) {
os_type = json::android;
if (!app_data[os_type].keyExists(json::packageName)) {
LOG4CXX_ERROR(logger_, "Can't find package name in json file.");
continue;
}
}
if (os_type.empty()) {
LOG4CXX_ERROR(logger_, "Can't find mobile OS type in json file.");
continue;
}
if (!app_data.keyExists(json::appId)) {
LOG4CXX_ERROR(logger_, "Can't find app ID in json file.");
continue;
}
if (!app_data.keyExists(json::name)) {
LOG4CXX_ERROR(logger_, "Can't find app name in json file.");
continue;
}
return true;
}
return false;
}
} // namespace commands
} // namespace application_manager
<|endoftext|>
|
<commit_before>/*
kopeteballoon.cpp - Nice Balloon
Copyright (c) 2002 by Duncan Mac-Vicar Prett <duncan@kde.org>
Kopete (c) 2002 by the Kopete developers <kopete-devel@kde.org>
Portions of this code based on Kim Applet code
Copyright (c) 2000-2002 by Malte Starostik <malte@kde.org>
*************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
*************************************************************************
*/
#include <qpointarray.h>
#include <qpushbutton.h>
#include <qtooltip.h>
#include <qlabel.h>
#include <qlayout.h>
#include <kdeversion.h>
#if KDE_VERSION > 0x030100
#include <kglobalsettings.h>
#endif
#include <kapplication.h>
#include <klocale.h>
#include <kstandarddirs.h>
#include "kopeteballoon.h"
#include "systemtray.h"
KopeteBalloon::KopeteBalloon( const QString &text, const QString &pix )
: QWidget( 0L, "KopeteBalloon", WStyle_StaysOnTop | WStyle_Customize |
WStyle_NoBorder | WStyle_Tool | WX11BypassWM )
{
resize( 139, 104 );
setCaption( trUtf8( "" ) );
QVBoxLayout *BalloonLayout = new QVBoxLayout( this, 24, 6, "BalloonLayout");
QHBoxLayout *Layout1 = new QHBoxLayout( 0, 0, 6, "Layout1");
m_image = new QLabel( this, "m_image" );
m_image->setScaledContents( FALSE );
Layout1->addWidget( m_image );
m_caption = new QLabel( this, "m_caption" );
m_caption->setText( trUtf8( "" ) );
Layout1->addWidget( m_caption );
BalloonLayout->addLayout( Layout1 );
QHBoxLayout *Layout2 = new QHBoxLayout( 0, 0, 6, "Layout2");
QSpacerItem* spacer = new QSpacerItem( 20, 20, QSizePolicy::Expanding, QSizePolicy::Minimum );
Layout2->addItem( spacer );
QPushButton *viewButton = new QPushButton( this, "m_reject" );
viewButton->setText( i18n( "View" ) );
QPushButton *ignoreButton = new QPushButton( this );
ignoreButton->setText( i18n( "Ignore" ) );
Layout2->addWidget( viewButton );
Layout2->addWidget( ignoreButton );
QSpacerItem* spacer_2 = new QSpacerItem( 20, 20, QSizePolicy::Expanding, QSizePolicy::Minimum );
Layout2->addItem( spacer_2 );
BalloonLayout->addLayout( Layout2 );
setPalette(QToolTip::palette());
setAutoMask(true);
m_image->setPixmap(locate("data", pix));
m_caption->setText(text);
connect( viewButton, SIGNAL( clicked() ), SIGNAL( signalButtonClicked() ) );
connect( ignoreButton, SIGNAL( clicked() ), SIGNAL( signalIgnoreButtonClicked() ) );
connect( viewButton, SIGNAL( clicked() ), SLOT( deleteLater() ) );
connect( ignoreButton, SIGNAL( clicked() ), SLOT( deleteLater() ) );
}
void KopeteBalloon::setAnchor( const QPoint &anchor)
{
m_anchor = anchor;
updateMask();
}
KopeteBalloon::~KopeteBalloon()
{
}
void KopeteBalloon::updateMask()
{
QRegion mask(10, 10, width() - 20, height() - 20);
QPoint corners[8] = {
QPoint(width() - 50, 10),
QPoint(10, 10),
QPoint(10, height() - 50),
QPoint(width() - 50, height() - 50),
QPoint(width() - 10, 10),
QPoint(10, 10),
QPoint(10, height() - 10),
QPoint(width() - 10, height() - 10)
};
for (int i = 0; i < 4; ++i)
{
QPointArray corner;
corner.makeArc(corners[i].x(), corners[i].y(), 40, 40, i * 16 * 90, 16 * 90);
corner.resize(corner.size() + 1);
corner.setPoint(corner.size() - 1, corners[i + 4]);
mask -= corner;
}
// get screen-geometry for screen our anchor is on
// (geometry can differ from screen to screen!
#if KDE_VERSION > 0x030100
QRect deskRect = KGlobalSettings::desktopGeometry(m_anchor);
#else
QDesktopWidget* tmp = QApplication::desktop();
QRect deskRect = tmp->screenGeometry(tmp->screenNumber(m_anchor));
#endif
bool bottom = (m_anchor.y() + height()) > (deskRect.height() - 48);
bool right = (m_anchor.x() + width()) > (deskRect.width() - 48);
QPointArray arrow(4);
arrow.setPoint(0, QPoint(right ? width() : 0, bottom ? height() : 0));
arrow.setPoint(1, QPoint(right ? width() - 10 : 10, bottom ? height() - 30 : 30));
arrow.setPoint(2, QPoint(right ? width() - 30 : 30, bottom ? height() - 10 : 10));
arrow.setPoint(3, arrow[0]);
mask += arrow;
setMask(mask);
move(right ? m_anchor.x() - width() : m_anchor.x(),
bottom ? m_anchor.y() - height() : m_anchor.y());
}
#include "kopeteballoon.moc"
// vim: set noet ts=4 sts=4 sw=4:
<commit_msg>that #if was wrong :)<commit_after>/*
kopeteballoon.cpp - Nice Balloon
Copyright (c) 2002 by Duncan Mac-Vicar Prett <duncan@kde.org>
Kopete (c) 2002 by the Kopete developers <kopete-devel@kde.org>
Portions of this code based on Kim Applet code
Copyright (c) 2000-2002 by Malte Starostik <malte@kde.org>
*************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
*************************************************************************
*/
#include <qpointarray.h>
#include <qpushbutton.h>
#include <qtooltip.h>
#include <qlabel.h>
#include <qlayout.h>
#include <kdeversion.h>
#if KDE_VERSION > 0x030190
#include <kglobalsettings.h>
#endif
#include <kapplication.h>
#include <klocale.h>
#include <kstandarddirs.h>
#include "kopeteballoon.h"
#include "systemtray.h"
KopeteBalloon::KopeteBalloon( const QString &text, const QString &pix )
: QWidget( 0L, "KopeteBalloon", WStyle_StaysOnTop | WStyle_Customize |
WStyle_NoBorder | WStyle_Tool | WX11BypassWM )
{
resize( 139, 104 );
setCaption( trUtf8( "" ) );
QVBoxLayout *BalloonLayout = new QVBoxLayout( this, 24, 6, "BalloonLayout");
QHBoxLayout *Layout1 = new QHBoxLayout( 0, 0, 6, "Layout1");
m_image = new QLabel( this, "m_image" );
m_image->setScaledContents( FALSE );
Layout1->addWidget( m_image );
m_caption = new QLabel( this, "m_caption" );
m_caption->setText( trUtf8( "" ) );
Layout1->addWidget( m_caption );
BalloonLayout->addLayout( Layout1 );
QHBoxLayout *Layout2 = new QHBoxLayout( 0, 0, 6, "Layout2");
QSpacerItem* spacer = new QSpacerItem( 20, 20, QSizePolicy::Expanding, QSizePolicy::Minimum );
Layout2->addItem( spacer );
QPushButton *viewButton = new QPushButton( this, "m_reject" );
viewButton->setText( i18n( "View" ) );
QPushButton *ignoreButton = new QPushButton( this );
ignoreButton->setText( i18n( "Ignore" ) );
Layout2->addWidget( viewButton );
Layout2->addWidget( ignoreButton );
QSpacerItem* spacer_2 = new QSpacerItem( 20, 20, QSizePolicy::Expanding, QSizePolicy::Minimum );
Layout2->addItem( spacer_2 );
BalloonLayout->addLayout( Layout2 );
setPalette(QToolTip::palette());
setAutoMask(true);
m_image->setPixmap(locate("data", pix));
m_caption->setText(text);
connect( viewButton, SIGNAL( clicked() ), SIGNAL( signalButtonClicked() ) );
connect( ignoreButton, SIGNAL( clicked() ), SIGNAL( signalIgnoreButtonClicked() ) );
connect( viewButton, SIGNAL( clicked() ), SLOT( deleteLater() ) );
connect( ignoreButton, SIGNAL( clicked() ), SLOT( deleteLater() ) );
}
void KopeteBalloon::setAnchor( const QPoint &anchor)
{
m_anchor = anchor;
updateMask();
}
KopeteBalloon::~KopeteBalloon()
{
}
void KopeteBalloon::updateMask()
{
QRegion mask(10, 10, width() - 20, height() - 20);
QPoint corners[8] = {
QPoint(width() - 50, 10),
QPoint(10, 10),
QPoint(10, height() - 50),
QPoint(width() - 50, height() - 50),
QPoint(width() - 10, 10),
QPoint(10, 10),
QPoint(10, height() - 10),
QPoint(width() - 10, height() - 10)
};
for (int i = 0; i < 4; ++i)
{
QPointArray corner;
corner.makeArc(corners[i].x(), corners[i].y(), 40, 40, i * 16 * 90, 16 * 90);
corner.resize(corner.size() + 1);
corner.setPoint(corner.size() - 1, corners[i + 4]);
mask -= corner;
}
// get screen-geometry for screen our anchor is on
// (geometry can differ from screen to screen!
#if KDE_VERSION > 0x030190
QRect deskRect = KGlobalSettings::desktopGeometry(m_anchor);
#else
QDesktopWidget* tmp = QApplication::desktop();
QRect deskRect = tmp->screenGeometry(tmp->screenNumber(m_anchor));
#endif
bool bottom = (m_anchor.y() + height()) > (deskRect.height() - 48);
bool right = (m_anchor.x() + width()) > (deskRect.width() - 48);
QPointArray arrow(4);
arrow.setPoint(0, QPoint(right ? width() : 0, bottom ? height() : 0));
arrow.setPoint(1, QPoint(right ? width() - 10 : 10, bottom ? height() - 30 : 30));
arrow.setPoint(2, QPoint(right ? width() - 30 : 30, bottom ? height() - 10 : 10));
arrow.setPoint(3, arrow[0]);
mask += arrow;
setMask(mask);
move(right ? m_anchor.x() - width() : m_anchor.x(),
bottom ? m_anchor.y() - height() : m_anchor.y());
}
#include "kopeteballoon.moc"
// vim: set noet ts=4 sts=4 sw=4:
<|endoftext|>
|
<commit_before>//===- StandardTypes.cpp - MLIR Standard Type Classes ---------------------===//
//
// Copyright 2019 The MLIR 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.
// =============================================================================
#include "mlir/IR/StandardTypes.h"
#include "TypeDetail.h"
#include "mlir/IR/AffineMap.h"
#include "mlir/IR/Diagnostics.h"
#include "mlir/Support/STLExtras.h"
#include "llvm/ADT/APFloat.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Support/raw_ostream.h"
using namespace mlir;
using namespace mlir::detail;
//===----------------------------------------------------------------------===//
// Integer Type
//===----------------------------------------------------------------------===//
/// Verify the construction of an integer type.
LogicalResult IntegerType::verifyConstructionInvariants(
llvm::Optional<Location> loc, MLIRContext *context, unsigned width) {
if (width > IntegerType::kMaxWidth) {
if (loc)
context->emitError(*loc) << "integer bitwidth is limited to "
<< IntegerType::kMaxWidth << " bits";
return failure();
}
return success();
}
IntegerType IntegerType::get(unsigned width, MLIRContext *context) {
return Base::get(context, StandardTypes::Integer, width);
}
IntegerType IntegerType::getChecked(unsigned width, MLIRContext *context,
Location location) {
return Base::getChecked(location, context, StandardTypes::Integer, width);
}
unsigned IntegerType::getWidth() const { return getImpl()->width; }
//===----------------------------------------------------------------------===//
// Float Type
//===----------------------------------------------------------------------===//
unsigned FloatType::getWidth() const {
switch (getKind()) {
case StandardTypes::BF16:
case StandardTypes::F16:
return 16;
case StandardTypes::F32:
return 32;
case StandardTypes::F64:
return 64;
default:
llvm_unreachable("unexpected type");
}
}
/// Returns the floating semantics for the given type.
const llvm::fltSemantics &FloatType::getFloatSemantics() const {
if (isBF16())
// Treat BF16 like a double. This is unfortunate but BF16 fltSemantics is
// not defined in LLVM.
// TODO(jpienaar): add BF16 to LLVM? fltSemantics are internal to APFloat.cc
// else one could add it.
// static const fltSemantics semBF16 = {127, -126, 8, 16};
return APFloat::IEEEdouble();
if (isF16())
return APFloat::IEEEhalf();
if (isF32())
return APFloat::IEEEsingle();
if (isF64())
return APFloat::IEEEdouble();
llvm_unreachable("non-floating point type used");
}
unsigned Type::getIntOrFloatBitWidth() const {
assert(isIntOrFloat() && "only ints and floats have a bitwidth");
if (auto intType = dyn_cast<IntegerType>()) {
return intType.getWidth();
}
auto floatType = cast<FloatType>();
return floatType.getWidth();
}
//===----------------------------------------------------------------------===//
// VectorOrTensorType
//===----------------------------------------------------------------------===//
Type VectorOrTensorType::getElementType() const {
return static_cast<ImplType *>(type)->elementType;
}
unsigned VectorOrTensorType::getElementTypeBitWidth() const {
return getElementType().getIntOrFloatBitWidth();
}
unsigned VectorOrTensorType::getNumElements() const {
switch (getKind()) {
case StandardTypes::Vector:
case StandardTypes::RankedTensor: {
assert(hasStaticShape() && "expected type to have static shape");
auto shape = getShape();
unsigned num = 1;
for (auto dim : shape)
num *= dim;
return num;
}
default:
llvm_unreachable("not a VectorOrTensorType or not ranked");
}
}
/// If this is ranked tensor or vector type, return the rank. If it is an
/// unranked tensor, return -1.
int64_t VectorOrTensorType::getRank() const {
switch (getKind()) {
case StandardTypes::Vector:
case StandardTypes::RankedTensor:
return getShape().size();
case StandardTypes::UnrankedTensor:
return -1;
default:
llvm_unreachable("not a VectorOrTensorType");
}
}
int64_t VectorOrTensorType::getDimSize(unsigned i) const {
switch (getKind()) {
case StandardTypes::Vector:
case StandardTypes::RankedTensor:
return getShape()[i];
default:
llvm_unreachable("not a VectorOrTensorType or not ranked");
}
}
// Get the number of number of bits require to store a value of the given vector
// or tensor types. Compute the value recursively since tensors are allowed to
// have vectors as elements.
int64_t VectorOrTensorType::getSizeInBits() const {
assert(hasStaticShape() &&
"cannot get the bit size of an aggregate with a dynamic shape");
auto elementType = getElementType();
if (elementType.isIntOrFloat())
return elementType.getIntOrFloatBitWidth() * getNumElements();
// Tensors can have vectors and other tensors as elements, vectors cannot.
assert(!isa<VectorType>() && "unsupported vector element type");
auto elementVectorOrTensorType = elementType.dyn_cast<VectorOrTensorType>();
assert(elementVectorOrTensorType && "unsupported tensor element type");
return getNumElements() * elementVectorOrTensorType.getSizeInBits();
}
ArrayRef<int64_t> VectorOrTensorType::getShape() const {
switch (getKind()) {
case StandardTypes::Vector:
return cast<VectorType>().getShape();
case StandardTypes::RankedTensor:
return cast<RankedTensorType>().getShape();
default:
llvm_unreachable("not a VectorOrTensorType or not ranked");
}
}
bool VectorOrTensorType::hasStaticShape() const {
if (isa<UnrankedTensorType>())
return false;
return llvm::none_of(getShape(), [](int64_t i) { return i < 0; });
}
//===----------------------------------------------------------------------===//
// VectorType
//===----------------------------------------------------------------------===//
VectorType VectorType::get(ArrayRef<int64_t> shape, Type elementType) {
return Base::get(elementType.getContext(), StandardTypes::Vector, shape,
elementType);
}
VectorType VectorType::getChecked(ArrayRef<int64_t> shape, Type elementType,
Location location) {
return Base::getChecked(location, elementType.getContext(),
StandardTypes::Vector, shape, elementType);
}
LogicalResult VectorType::verifyConstructionInvariants(
llvm::Optional<Location> loc, MLIRContext *context, ArrayRef<int64_t> shape,
Type elementType) {
if (shape.empty()) {
if (loc)
context->emitError(*loc, "vector types must have at least one dimension");
return failure();
}
if (!isValidElementType(elementType)) {
if (loc)
context->emitError(*loc, "vector elements must be int or float type");
return failure();
}
if (any_of(shape, [](int64_t i) { return i <= 0; })) {
if (loc)
context->emitError(*loc,
"vector types must have positive constant sizes");
return failure();
}
return success();
}
ArrayRef<int64_t> VectorType::getShape() const { return getImpl()->getShape(); }
//===----------------------------------------------------------------------===//
// TensorType
//===----------------------------------------------------------------------===//
// Check if "elementType" can be an element type of a tensor. Emit errors if
// location is not nullptr. Returns failure if check failed.
static inline LogicalResult checkTensorElementType(Optional<Location> location,
MLIRContext *context,
Type elementType) {
if (!TensorType::isValidElementType(elementType)) {
if (location)
context->emitError(*location, "invalid tensor element type");
return failure();
}
return success();
}
//===----------------------------------------------------------------------===//
// RankedTensorType
//===----------------------------------------------------------------------===//
RankedTensorType RankedTensorType::get(ArrayRef<int64_t> shape,
Type elementType) {
return Base::get(elementType.getContext(), StandardTypes::RankedTensor, shape,
elementType);
}
RankedTensorType RankedTensorType::getChecked(ArrayRef<int64_t> shape,
Type elementType,
Location location) {
return Base::getChecked(location, elementType.getContext(),
StandardTypes::RankedTensor, shape, elementType);
}
LogicalResult RankedTensorType::verifyConstructionInvariants(
llvm::Optional<Location> loc, MLIRContext *context, ArrayRef<int64_t> shape,
Type elementType) {
for (int64_t s : shape) {
if (s < -1) {
if (loc)
context->emitError(*loc, "invalid tensor dimension size");
return failure();
}
}
return checkTensorElementType(loc, context, elementType);
}
ArrayRef<int64_t> RankedTensorType::getShape() const {
return getImpl()->getShape();
}
//===----------------------------------------------------------------------===//
// UnrankedTensorType
//===----------------------------------------------------------------------===//
UnrankedTensorType UnrankedTensorType::get(Type elementType) {
return Base::get(elementType.getContext(), StandardTypes::UnrankedTensor,
elementType);
}
UnrankedTensorType UnrankedTensorType::getChecked(Type elementType,
Location location) {
return Base::getChecked(location, elementType.getContext(),
StandardTypes::UnrankedTensor, elementType);
}
LogicalResult UnrankedTensorType::verifyConstructionInvariants(
llvm::Optional<Location> loc, MLIRContext *context, Type elementType) {
return checkTensorElementType(loc, context, elementType);
}
//===----------------------------------------------------------------------===//
// MemRefType
//===----------------------------------------------------------------------===//
/// Get or create a new MemRefType defined by the arguments. If the resulting
/// type would be ill-formed, return nullptr. If the location is provided,
/// emit detailed error messages. To emit errors when the location is unknown,
/// pass in an instance of UnknownLoc.
MemRefType MemRefType::getImpl(ArrayRef<int64_t> shape, Type elementType,
ArrayRef<AffineMap> affineMapComposition,
unsigned memorySpace,
Optional<Location> location) {
auto *context = elementType.getContext();
for (int64_t s : shape) {
// Negative sizes are not allowed except for `-1` that means dynamic size.
if (s < -1) {
if (location)
context->emitError(*location, "invalid memref size");
return {};
}
}
// Check that the structure of the composition is valid, i.e. that each
// subsequent affine map has as many inputs as the previous map has results.
// Take the dimensionality of the MemRef for the first map.
auto dim = shape.size();
unsigned i = 0;
for (const auto &affineMap : affineMapComposition) {
if (affineMap.getNumDims() != dim) {
if (location)
context->emitError(
*location,
"memref affine map dimension mismatch between " +
(i == 0 ? Twine("memref rank") : "affine map " + Twine(i)) +
" and affine map" + Twine(i + 1) + ": " + Twine(dim) +
" != " + Twine(affineMap.getNumDims()));
return nullptr;
}
dim = affineMap.getNumResults();
++i;
}
// Drop the unbounded identity maps from the composition.
// This may lead to the composition becoming empty, which is interpreted as an
// implicit identity.
llvm::SmallVector<AffineMap, 2> cleanedAffineMapComposition;
for (const auto &map : affineMapComposition) {
if (map.isIdentity() && !map.isBounded())
continue;
cleanedAffineMapComposition.push_back(map);
}
return Base::get(context, StandardTypes::MemRef, shape, elementType,
cleanedAffineMapComposition, memorySpace);
}
ArrayRef<int64_t> MemRefType::getShape() const {
return static_cast<ImplType *>(type)->getShape();
}
Type MemRefType::getElementType() const {
return static_cast<ImplType *>(type)->elementType;
}
ArrayRef<AffineMap> MemRefType::getAffineMaps() const {
return static_cast<ImplType *>(type)->getAffineMaps();
}
unsigned MemRefType::getMemorySpace() const {
return static_cast<ImplType *>(type)->memorySpace;
}
unsigned MemRefType::getNumDynamicDims() const {
return llvm::count_if(getShape(), [](int64_t i) { return i < 0; });
}
//===----------------------------------------------------------------------===//
/// ComplexType
//===----------------------------------------------------------------------===//
ComplexType ComplexType::get(Type elementType) {
return Base::get(elementType.getContext(), StandardTypes::Complex,
elementType);
}
ComplexType ComplexType::getChecked(Type elementType, Location location) {
return Base::getChecked(location, elementType.getContext(),
StandardTypes::Complex, elementType);
}
/// Verify the construction of an integer type.
LogicalResult ComplexType::verifyConstructionInvariants(
llvm::Optional<Location> loc, MLIRContext *context, Type elementType) {
if (!elementType.isa<FloatType>() && !elementType.isa<IntegerType>()) {
if (loc)
context->emitError(*loc, "invalid element type for complex");
return failure();
}
return success();
}
Type ComplexType::getElementType() { return getImpl()->elementType; }
//===----------------------------------------------------------------------===//
/// TupleType
//===----------------------------------------------------------------------===//
/// Get or create a new TupleType with the provided element types. Assumes the
/// arguments define a well-formed type.
TupleType TupleType::get(ArrayRef<Type> elementTypes, MLIRContext *context) {
return Base::get(context, StandardTypes::Tuple, elementTypes);
}
/// Return the elements types for this tuple.
ArrayRef<Type> TupleType::getTypes() const { return getImpl()->getTypes(); }
/// Return the number of element types.
unsigned TupleType::size() const { return getImpl()->size(); }
<commit_msg> Fix MacOS build: static constexpr must be defined<commit_after>//===- StandardTypes.cpp - MLIR Standard Type Classes ---------------------===//
//
// Copyright 2019 The MLIR 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.
// =============================================================================
#include "mlir/IR/StandardTypes.h"
#include "TypeDetail.h"
#include "mlir/IR/AffineMap.h"
#include "mlir/IR/Diagnostics.h"
#include "mlir/Support/STLExtras.h"
#include "llvm/ADT/APFloat.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Support/raw_ostream.h"
using namespace mlir;
using namespace mlir::detail;
//===----------------------------------------------------------------------===//
// Integer Type
//===----------------------------------------------------------------------===//
// static constexpr must have a definition (until in C++17 and inline variable).
constexpr unsigned IntegerType::kMaxWidth;
/// Verify the construction of an integer type.
LogicalResult IntegerType::verifyConstructionInvariants(
llvm::Optional<Location> loc, MLIRContext *context, unsigned width) {
if (width > IntegerType::kMaxWidth) {
if (loc)
context->emitError(*loc) << "integer bitwidth is limited to "
<< IntegerType::kMaxWidth << " bits";
return failure();
}
return success();
}
IntegerType IntegerType::get(unsigned width, MLIRContext *context) {
return Base::get(context, StandardTypes::Integer, width);
}
IntegerType IntegerType::getChecked(unsigned width, MLIRContext *context,
Location location) {
return Base::getChecked(location, context, StandardTypes::Integer, width);
}
unsigned IntegerType::getWidth() const { return getImpl()->width; }
//===----------------------------------------------------------------------===//
// Float Type
//===----------------------------------------------------------------------===//
unsigned FloatType::getWidth() const {
switch (getKind()) {
case StandardTypes::BF16:
case StandardTypes::F16:
return 16;
case StandardTypes::F32:
return 32;
case StandardTypes::F64:
return 64;
default:
llvm_unreachable("unexpected type");
}
}
/// Returns the floating semantics for the given type.
const llvm::fltSemantics &FloatType::getFloatSemantics() const {
if (isBF16())
// Treat BF16 like a double. This is unfortunate but BF16 fltSemantics is
// not defined in LLVM.
// TODO(jpienaar): add BF16 to LLVM? fltSemantics are internal to APFloat.cc
// else one could add it.
// static const fltSemantics semBF16 = {127, -126, 8, 16};
return APFloat::IEEEdouble();
if (isF16())
return APFloat::IEEEhalf();
if (isF32())
return APFloat::IEEEsingle();
if (isF64())
return APFloat::IEEEdouble();
llvm_unreachable("non-floating point type used");
}
unsigned Type::getIntOrFloatBitWidth() const {
assert(isIntOrFloat() && "only ints and floats have a bitwidth");
if (auto intType = dyn_cast<IntegerType>()) {
return intType.getWidth();
}
auto floatType = cast<FloatType>();
return floatType.getWidth();
}
//===----------------------------------------------------------------------===//
// VectorOrTensorType
//===----------------------------------------------------------------------===//
Type VectorOrTensorType::getElementType() const {
return static_cast<ImplType *>(type)->elementType;
}
unsigned VectorOrTensorType::getElementTypeBitWidth() const {
return getElementType().getIntOrFloatBitWidth();
}
unsigned VectorOrTensorType::getNumElements() const {
switch (getKind()) {
case StandardTypes::Vector:
case StandardTypes::RankedTensor: {
assert(hasStaticShape() && "expected type to have static shape");
auto shape = getShape();
unsigned num = 1;
for (auto dim : shape)
num *= dim;
return num;
}
default:
llvm_unreachable("not a VectorOrTensorType or not ranked");
}
}
/// If this is ranked tensor or vector type, return the rank. If it is an
/// unranked tensor, return -1.
int64_t VectorOrTensorType::getRank() const {
switch (getKind()) {
case StandardTypes::Vector:
case StandardTypes::RankedTensor:
return getShape().size();
case StandardTypes::UnrankedTensor:
return -1;
default:
llvm_unreachable("not a VectorOrTensorType");
}
}
int64_t VectorOrTensorType::getDimSize(unsigned i) const {
switch (getKind()) {
case StandardTypes::Vector:
case StandardTypes::RankedTensor:
return getShape()[i];
default:
llvm_unreachable("not a VectorOrTensorType or not ranked");
}
}
// Get the number of number of bits require to store a value of the given vector
// or tensor types. Compute the value recursively since tensors are allowed to
// have vectors as elements.
int64_t VectorOrTensorType::getSizeInBits() const {
assert(hasStaticShape() &&
"cannot get the bit size of an aggregate with a dynamic shape");
auto elementType = getElementType();
if (elementType.isIntOrFloat())
return elementType.getIntOrFloatBitWidth() * getNumElements();
// Tensors can have vectors and other tensors as elements, vectors cannot.
assert(!isa<VectorType>() && "unsupported vector element type");
auto elementVectorOrTensorType = elementType.dyn_cast<VectorOrTensorType>();
assert(elementVectorOrTensorType && "unsupported tensor element type");
return getNumElements() * elementVectorOrTensorType.getSizeInBits();
}
ArrayRef<int64_t> VectorOrTensorType::getShape() const {
switch (getKind()) {
case StandardTypes::Vector:
return cast<VectorType>().getShape();
case StandardTypes::RankedTensor:
return cast<RankedTensorType>().getShape();
default:
llvm_unreachable("not a VectorOrTensorType or not ranked");
}
}
bool VectorOrTensorType::hasStaticShape() const {
if (isa<UnrankedTensorType>())
return false;
return llvm::none_of(getShape(), [](int64_t i) { return i < 0; });
}
//===----------------------------------------------------------------------===//
// VectorType
//===----------------------------------------------------------------------===//
VectorType VectorType::get(ArrayRef<int64_t> shape, Type elementType) {
return Base::get(elementType.getContext(), StandardTypes::Vector, shape,
elementType);
}
VectorType VectorType::getChecked(ArrayRef<int64_t> shape, Type elementType,
Location location) {
return Base::getChecked(location, elementType.getContext(),
StandardTypes::Vector, shape, elementType);
}
LogicalResult VectorType::verifyConstructionInvariants(
llvm::Optional<Location> loc, MLIRContext *context, ArrayRef<int64_t> shape,
Type elementType) {
if (shape.empty()) {
if (loc)
context->emitError(*loc, "vector types must have at least one dimension");
return failure();
}
if (!isValidElementType(elementType)) {
if (loc)
context->emitError(*loc, "vector elements must be int or float type");
return failure();
}
if (any_of(shape, [](int64_t i) { return i <= 0; })) {
if (loc)
context->emitError(*loc,
"vector types must have positive constant sizes");
return failure();
}
return success();
}
ArrayRef<int64_t> VectorType::getShape() const { return getImpl()->getShape(); }
//===----------------------------------------------------------------------===//
// TensorType
//===----------------------------------------------------------------------===//
// Check if "elementType" can be an element type of a tensor. Emit errors if
// location is not nullptr. Returns failure if check failed.
static inline LogicalResult checkTensorElementType(Optional<Location> location,
MLIRContext *context,
Type elementType) {
if (!TensorType::isValidElementType(elementType)) {
if (location)
context->emitError(*location, "invalid tensor element type");
return failure();
}
return success();
}
//===----------------------------------------------------------------------===//
// RankedTensorType
//===----------------------------------------------------------------------===//
RankedTensorType RankedTensorType::get(ArrayRef<int64_t> shape,
Type elementType) {
return Base::get(elementType.getContext(), StandardTypes::RankedTensor, shape,
elementType);
}
RankedTensorType RankedTensorType::getChecked(ArrayRef<int64_t> shape,
Type elementType,
Location location) {
return Base::getChecked(location, elementType.getContext(),
StandardTypes::RankedTensor, shape, elementType);
}
LogicalResult RankedTensorType::verifyConstructionInvariants(
llvm::Optional<Location> loc, MLIRContext *context, ArrayRef<int64_t> shape,
Type elementType) {
for (int64_t s : shape) {
if (s < -1) {
if (loc)
context->emitError(*loc, "invalid tensor dimension size");
return failure();
}
}
return checkTensorElementType(loc, context, elementType);
}
ArrayRef<int64_t> RankedTensorType::getShape() const {
return getImpl()->getShape();
}
//===----------------------------------------------------------------------===//
// UnrankedTensorType
//===----------------------------------------------------------------------===//
UnrankedTensorType UnrankedTensorType::get(Type elementType) {
return Base::get(elementType.getContext(), StandardTypes::UnrankedTensor,
elementType);
}
UnrankedTensorType UnrankedTensorType::getChecked(Type elementType,
Location location) {
return Base::getChecked(location, elementType.getContext(),
StandardTypes::UnrankedTensor, elementType);
}
LogicalResult UnrankedTensorType::verifyConstructionInvariants(
llvm::Optional<Location> loc, MLIRContext *context, Type elementType) {
return checkTensorElementType(loc, context, elementType);
}
//===----------------------------------------------------------------------===//
// MemRefType
//===----------------------------------------------------------------------===//
/// Get or create a new MemRefType defined by the arguments. If the resulting
/// type would be ill-formed, return nullptr. If the location is provided,
/// emit detailed error messages. To emit errors when the location is unknown,
/// pass in an instance of UnknownLoc.
MemRefType MemRefType::getImpl(ArrayRef<int64_t> shape, Type elementType,
ArrayRef<AffineMap> affineMapComposition,
unsigned memorySpace,
Optional<Location> location) {
auto *context = elementType.getContext();
for (int64_t s : shape) {
// Negative sizes are not allowed except for `-1` that means dynamic size.
if (s < -1) {
if (location)
context->emitError(*location, "invalid memref size");
return {};
}
}
// Check that the structure of the composition is valid, i.e. that each
// subsequent affine map has as many inputs as the previous map has results.
// Take the dimensionality of the MemRef for the first map.
auto dim = shape.size();
unsigned i = 0;
for (const auto &affineMap : affineMapComposition) {
if (affineMap.getNumDims() != dim) {
if (location)
context->emitError(
*location,
"memref affine map dimension mismatch between " +
(i == 0 ? Twine("memref rank") : "affine map " + Twine(i)) +
" and affine map" + Twine(i + 1) + ": " + Twine(dim) +
" != " + Twine(affineMap.getNumDims()));
return nullptr;
}
dim = affineMap.getNumResults();
++i;
}
// Drop the unbounded identity maps from the composition.
// This may lead to the composition becoming empty, which is interpreted as an
// implicit identity.
llvm::SmallVector<AffineMap, 2> cleanedAffineMapComposition;
for (const auto &map : affineMapComposition) {
if (map.isIdentity() && !map.isBounded())
continue;
cleanedAffineMapComposition.push_back(map);
}
return Base::get(context, StandardTypes::MemRef, shape, elementType,
cleanedAffineMapComposition, memorySpace);
}
ArrayRef<int64_t> MemRefType::getShape() const {
return static_cast<ImplType *>(type)->getShape();
}
Type MemRefType::getElementType() const {
return static_cast<ImplType *>(type)->elementType;
}
ArrayRef<AffineMap> MemRefType::getAffineMaps() const {
return static_cast<ImplType *>(type)->getAffineMaps();
}
unsigned MemRefType::getMemorySpace() const {
return static_cast<ImplType *>(type)->memorySpace;
}
unsigned MemRefType::getNumDynamicDims() const {
return llvm::count_if(getShape(), [](int64_t i) { return i < 0; });
}
//===----------------------------------------------------------------------===//
/// ComplexType
//===----------------------------------------------------------------------===//
ComplexType ComplexType::get(Type elementType) {
return Base::get(elementType.getContext(), StandardTypes::Complex,
elementType);
}
ComplexType ComplexType::getChecked(Type elementType, Location location) {
return Base::getChecked(location, elementType.getContext(),
StandardTypes::Complex, elementType);
}
/// Verify the construction of an integer type.
LogicalResult ComplexType::verifyConstructionInvariants(
llvm::Optional<Location> loc, MLIRContext *context, Type elementType) {
if (!elementType.isa<FloatType>() && !elementType.isa<IntegerType>()) {
if (loc)
context->emitError(*loc, "invalid element type for complex");
return failure();
}
return success();
}
Type ComplexType::getElementType() { return getImpl()->elementType; }
//===----------------------------------------------------------------------===//
/// TupleType
//===----------------------------------------------------------------------===//
/// Get or create a new TupleType with the provided element types. Assumes the
/// arguments define a well-formed type.
TupleType TupleType::get(ArrayRef<Type> elementTypes, MLIRContext *context) {
return Base::get(context, StandardTypes::Tuple, elementTypes);
}
/// Return the elements types for this tuple.
ArrayRef<Type> TupleType::getTypes() const { return getImpl()->getTypes(); }
/// Return the number of element types.
unsigned TupleType::size() const { return getImpl()->size(); }
<|endoftext|>
|
<commit_before>///////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Achim Brandt
////////////////////////////////////////////////////////////////////////////////
#include "VppResponse.h"
#include <velocypack/Builder.h>
#include <velocypack/Dumper.h>
#include <velocypack/Options.h>
#include <velocypack/velocypack-aliases.h>
#include "Basics/Exceptions.h"
#include "Basics/StringBuffer.h"
#include "Basics/StringUtils.h"
#include "Basics/VPackStringBufferAdapter.h"
#include "Basics/VelocyPackDumper.h"
#include "Basics/tri-strings.h"
#include "Rest/VppRequest.h"
using namespace arangodb;
using namespace arangodb::basics;
bool VppResponse::HIDE_PRODUCT_HEADER = false;
VppResponse::VppResponse(ResponseCode code, uint64_t id)
: GeneralResponse(code),
_connectionType(CONNECTION_KEEP_ALIVE),
_contentType(ContentType::VPACK),
_header(nullptr),
_payload(),
_messageID(id) {}
void VppResponse::reset(ResponseCode code) {
_responseCode = code;
_headers.clear();
_connectionType = CONNECTION_KEEP_ALIVE;
_contentType = ContentType::TEXT;
}
void VppResponse::setPayload(ContentType contentType,
arangodb::velocypack::Slice const& slice,
bool generateBody, VPackOptions const& options) {
if (generateBody) {
// addPayload(slice);
if (slice.isEmptyObject()) {
throw std::logic_error("payload should be empty!!");
}
_payload.append(slice.startAs<char>(),
std::distance(slice.begin(), slice.end()));
}
};
VPackMessageNoOwnBuffer VppResponse::prepareForNetwork() {
VPackBuilder builder;
builder.openObject();
for (auto const& item : _headers) {
builder.add(item.first, VPackValue(item.second));
}
builder.close();
_header = builder.steal();
return VPackMessageNoOwnBuffer(VPackSlice(_header->data()),
VPackSlice(_payload.data()), _messageID);
}
// void VppResponse::writeHeader(basics::StringBuffer*) {}
<commit_msg>fix header<commit_after>///////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Achim Brandt
////////////////////////////////////////////////////////////////////////////////
#include "VppResponse.h"
#include <velocypack/Builder.h>
#include <velocypack/Dumper.h>
#include <velocypack/Options.h>
#include <velocypack/velocypack-aliases.h>
#include "Basics/Exceptions.h"
#include "Basics/StringBuffer.h"
#include "Basics/StringUtils.h"
#include "Basics/VPackStringBufferAdapter.h"
#include "Basics/VelocyPackDumper.h"
#include "Basics/tri-strings.h"
#include "Meta/conversion.h"
#include "Rest/VppRequest.h"
using namespace arangodb;
using namespace arangodb::basics;
bool VppResponse::HIDE_PRODUCT_HEADER = false;
VppResponse::VppResponse(ResponseCode code, uint64_t id)
: GeneralResponse(code),
_connectionType(CONNECTION_KEEP_ALIVE),
_contentType(ContentType::VPACK),
_header(nullptr),
_payload(),
_messageID(id) {}
void VppResponse::reset(ResponseCode code) {
_responseCode = code;
_headers.clear();
_connectionType = CONNECTION_KEEP_ALIVE;
_contentType = ContentType::TEXT;
}
void VppResponse::setPayload(ContentType contentType,
arangodb::velocypack::Slice const& slice,
bool generateBody, VPackOptions const& options) {
if (generateBody) {
// addPayload(slice);
if (slice.isEmptyObject()) {
throw std::logic_error("payload should be empty!!");
}
_payload.append(slice.startAs<char>(),
std::distance(slice.begin(), slice.end()));
}
};
VPackMessageNoOwnBuffer VppResponse::prepareForNetwork() {
VPackBuilder builder;
builder.openObject();
builder.add("version", VPackValue(int(1)));
builder.add("type", VPackValue(int(1))); // 2 == response
builder.add(
"responseCode",
VPackValue(static_cast<int>(meta::underlyingValue(_responseCode))));
// for (auto const& item : _headers) {
// builder.add(item.first, VPackValue(item.second));
//}
builder.close();
_header = builder.steal();
return VPackMessageNoOwnBuffer(VPackSlice(_header->data()),
VPackSlice(_payload.data()), _messageID);
}
// void VppResponse::writeHeader(basics::StringBuffer*) {}
<|endoftext|>
|
<commit_before>#include "THClKernels.h"
#include "EasyCL.h"
#include "THClTensor.h"
#include <stdexcept>
#include "THClReduceApplyUtils.h"
#include "CLKernel_structs.h"
using namespace std;
// Constructor
THClKernels::THClKernels(THClState *state, CLKernel *kernel) :
state(state),
kernel(kernel) {
}
THClKernels::~THClKernels() {
for( int i = 0; i < (int)tensorInfoCls.size(); i++ ) {
delete tensorInfoCls[i];
}
}
// CLTensors =====================
THClKernels *THClKernels::in(THClTensor *tensor) {
try {
kernel->in(THClTensor_wrapper(state, tensor));
kernel->in((int)THClTensor_storageOffset(state, tensor));
} catch( runtime_error &e ) {
THError(e.what());
}
return this;
}
THClKernels *THClKernels::inout(THClTensor *tensor) {
try {
kernel->inout(THClTensor_wrapper(state, tensor));
kernel->in((int)THClTensor_storageOffset(state, tensor));
} catch( runtime_error &e ) {
THError(e.what());
}
return this;
}
THClKernels *THClKernels::out(THClTensor *tensor) {
try {
kernel->out(THClTensor_wrapper(state, tensor));
kernel->in((int)THClTensor_storageOffset(state, tensor));
} catch( runtime_error &e ) {
THError(e.what());
}
return this;
}
// scalars ==================
THClKernels *THClKernels::in(int value) {
try {
kernel->in(value);
} catch( runtime_error &e ) {
THError(e.what());
}
return this;
}
THClKernels *THClKernels::in(float value) {
try {
kernel->in(value);
} catch( runtime_error &e ) {
THError(e.what());
}
return this;
}
// CLTensorInfos ================
template< typename IndexType >
THClKernels *THClKernels::in(TensorInfo<IndexType>tensorInfo) {
TensorInfoCl *tensorInfoCl = new TensorInfoCl(tensorInfo);
kernel->in(1, tensorInfoCl);
kernel->in(tensorInfo.wrapper);
tensorInfoCls.push_back(tensorInfoCl);
return this;
}
template< typename IndexType >
THClKernels *THClKernels::inout(TensorInfo<IndexType>tensorInfo) {
TensorInfoCl *tensorInfoCl = new TensorInfoCl(tensorInfo);
kernel->in(1, tensorInfoCl);
kernel->inout(tensorInfo.wrapper);
tensorInfoCls.push_back(tensorInfoCl);
return this;
}
template< typename IndexType >
THClKernels *THClKernels::out(TensorInfo<IndexType>tensorInfo) {
TensorInfoCl *tensorInfoCl = new TensorInfoCl(tensorInfo);
if( !tensorInfo.wrapper->isOnDevice() ) {
tensorInfo.wrapper->createOnDevice();
}
kernel->in(1, tensorInfoCl);
kernel->out(tensorInfo.wrapper);
tensorInfoCls.push_back(tensorInfoCl);
return this;
}
// CLWrapper ===============
THClKernels *THClKernels::in(CLWrapper *wrapper) {
try {
kernel->in(wrapper);
} catch( runtime_error &e ) {
THError(e.what());
}
return this;
}
THClKernels *THClKernels::inout(CLWrapper *wrapper) {
try {
kernel->inout(wrapper);
} catch( runtime_error &e ) {
THError(e.what());
}
return this;
}
THClKernels *THClKernels::out(CLWrapper *wrapper) {
try {
if( !wrapper->isOnDevice() ) {
wrapper->createOnDevice();
}
kernel->out(wrapper);
} catch( runtime_error &e ) {
THError(e.what());
}
return this;
}
void THClKernels::run(dim3 grid, dim3 block) {
dim3 global_ws;
for( int i = 0; i < 3; i++ ) {
global_ws.vec[i] = grid.vec[i] * block.vec[i];
}
try {
kernel->run(3, global_ws.as_size_t(), block.as_size_t());
} catch( runtime_error &e ) {
THError(e.what());
}
}
// locals ==================
THClKernels *THClKernels::localFloats(int count) {
try {
kernel->localFloats(count);
} catch( runtime_error &e ) {
THError(e.what());
}
}
// template instantiations ====================
#define DECLARE_THCLKERNELS(IndexType) \
template \
THClKernels *THClKernels::in<IndexType>(TensorInfo<IndexType>tensorInfo); \
template \
THClKernels *THClKernels::inout<IndexType>(TensorInfo<IndexType>tensorInfo); \
template \
THClKernels *THClKernels::out<IndexType>(TensorInfo<IndexType>tensorInfo);
DECLARE_THCLKERNELS(unsigned int);
DECLARE_THCLKERNELS(unsigned long);
template CLKernel *CLKernel::in<>(int N, const TensorInfoCl *data);
template CLKernel *CLKernel::inout<>(int N, const TensorInfoCl *data);
template CLKernel *CLKernel::out<>(int N, const TensorInfoCl *data);
<commit_msg>more diag output if kernel crash<commit_after>#include "THClKernels.h"
#include "EasyCL.h"
#include "THClTensor.h"
#include <stdexcept>
#include "THClReduceApplyUtils.h"
#include "CLKernel_structs.h"
#include <iostream>
using namespace std;
// Constructor
THClKernels::THClKernels(THClState *state, CLKernel *kernel) :
state(state),
kernel(kernel) {
}
THClKernels::~THClKernels() {
for( int i = 0; i < (int)tensorInfoCls.size(); i++ ) {
delete tensorInfoCls[i];
}
}
// CLTensors =====================
THClKernels *THClKernels::in(THClTensor *tensor) {
try {
kernel->in(THClTensor_wrapper(state, tensor));
kernel->in((int)THClTensor_storageOffset(state, tensor));
} catch( runtime_error &e ) {
THError(e.what());
}
return this;
}
THClKernels *THClKernels::inout(THClTensor *tensor) {
try {
kernel->inout(THClTensor_wrapper(state, tensor));
kernel->in((int)THClTensor_storageOffset(state, tensor));
} catch( runtime_error &e ) {
THError(e.what());
}
return this;
}
THClKernels *THClKernels::out(THClTensor *tensor) {
try {
kernel->out(THClTensor_wrapper(state, tensor));
kernel->in((int)THClTensor_storageOffset(state, tensor));
} catch( runtime_error &e ) {
THError(e.what());
}
return this;
}
// scalars ==================
THClKernels *THClKernels::in(int value) {
try {
kernel->in(value);
} catch( runtime_error &e ) {
THError(e.what());
}
return this;
}
THClKernels *THClKernels::in(float value) {
try {
kernel->in(value);
} catch( runtime_error &e ) {
THError(e.what());
}
return this;
}
// CLTensorInfos ================
template< typename IndexType >
THClKernels *THClKernels::in(TensorInfo<IndexType>tensorInfo) {
TensorInfoCl *tensorInfoCl = new TensorInfoCl(tensorInfo);
kernel->in(1, tensorInfoCl);
kernel->in(tensorInfo.wrapper);
tensorInfoCls.push_back(tensorInfoCl);
return this;
}
template< typename IndexType >
THClKernels *THClKernels::inout(TensorInfo<IndexType>tensorInfo) {
TensorInfoCl *tensorInfoCl = new TensorInfoCl(tensorInfo);
kernel->in(1, tensorInfoCl);
kernel->inout(tensorInfo.wrapper);
tensorInfoCls.push_back(tensorInfoCl);
return this;
}
template< typename IndexType >
THClKernels *THClKernels::out(TensorInfo<IndexType>tensorInfo) {
TensorInfoCl *tensorInfoCl = new TensorInfoCl(tensorInfo);
if( !tensorInfo.wrapper->isOnDevice() ) {
tensorInfo.wrapper->createOnDevice();
}
kernel->in(1, tensorInfoCl);
kernel->out(tensorInfo.wrapper);
tensorInfoCls.push_back(tensorInfoCl);
return this;
}
// CLWrapper ===============
THClKernels *THClKernels::in(CLWrapper *wrapper) {
try {
kernel->in(wrapper);
} catch( runtime_error &e ) {
THError(e.what());
}
return this;
}
THClKernels *THClKernels::inout(CLWrapper *wrapper) {
try {
kernel->inout(wrapper);
} catch( runtime_error &e ) {
THError(e.what());
}
return this;
}
THClKernels *THClKernels::out(CLWrapper *wrapper) {
try {
if( !wrapper->isOnDevice() ) {
wrapper->createOnDevice();
}
kernel->out(wrapper);
} catch( runtime_error &e ) {
THError(e.what());
}
return this;
}
void THClKernels::run(dim3 grid, dim3 block) {
dim3 global_ws;
for( int i = 0; i < 3; i++ ) {
global_ws.vec[i] = grid.vec[i] * block.vec[i];
}
try {
kernel->run(3, global_ws.as_size_t(), block.as_size_t());
} catch( runtime_error &e ) {
cout << e.what() << endl;
THError(e.what());
}
}
// locals ==================
THClKernels *THClKernels::localFloats(int count) {
try {
kernel->localFloats(count);
} catch( runtime_error &e ) {
THError(e.what());
}
}
// template instantiations ====================
#define DECLARE_THCLKERNELS(IndexType) \
template \
THClKernels *THClKernels::in<IndexType>(TensorInfo<IndexType>tensorInfo); \
template \
THClKernels *THClKernels::inout<IndexType>(TensorInfo<IndexType>tensorInfo); \
template \
THClKernels *THClKernels::out<IndexType>(TensorInfo<IndexType>tensorInfo);
DECLARE_THCLKERNELS(unsigned int);
DECLARE_THCLKERNELS(unsigned long);
template CLKernel *CLKernel::in<>(int N, const TensorInfoCl *data);
template CLKernel *CLKernel::inout<>(int N, const TensorInfoCl *data);
template CLKernel *CLKernel::out<>(int N, const TensorInfoCl *data);
<|endoftext|>
|
<commit_before>//===- Pattern.cpp - Pattern wrapper class --------------------------------===//
//
// Copyright 2019 The MLIR 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.
// =============================================================================
//
// Pattern wrapper class to simplify using TableGen Record defining a MLIR
// Pattern.
//
//===----------------------------------------------------------------------===//
#include "mlir/TableGen/Pattern.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Support/FormatVariadic.h"
#include "llvm/TableGen/Error.h"
#include "llvm/TableGen/Record.h"
using namespace mlir;
using llvm::formatv;
using mlir::tblgen::Operator;
//===----------------------------------------------------------------------===//
// DagLeaf
//===----------------------------------------------------------------------===//
bool tblgen::DagLeaf::isUnspecified() const {
return dyn_cast_or_null<llvm::UnsetInit>(def);
}
bool tblgen::DagLeaf::isOperandMatcher() const {
// Operand matchers specify a type constraint.
return isSubClassOf("TypeConstraint");
}
bool tblgen::DagLeaf::isAttrMatcher() const {
// Attribute matchers specify an attribute constraint.
return isSubClassOf("AttrConstraint");
}
bool tblgen::DagLeaf::isNativeCodeCall() const {
return isSubClassOf("NativeCodeCall");
}
bool tblgen::DagLeaf::isConstantAttr() const {
return isSubClassOf("ConstantAttr");
}
bool tblgen::DagLeaf::isEnumAttrCase() const {
return isSubClassOf("EnumAttrCaseInfo");
}
tblgen::Constraint tblgen::DagLeaf::getAsConstraint() const {
assert((isOperandMatcher() || isAttrMatcher()) &&
"the DAG leaf must be operand or attribute");
return Constraint(cast<llvm::DefInit>(def)->getDef());
}
tblgen::ConstantAttr tblgen::DagLeaf::getAsConstantAttr() const {
assert(isConstantAttr() && "the DAG leaf must be constant attribute");
return ConstantAttr(cast<llvm::DefInit>(def));
}
tblgen::EnumAttrCase tblgen::DagLeaf::getAsEnumAttrCase() const {
assert(isEnumAttrCase() && "the DAG leaf must be an enum attribute case");
return EnumAttrCase(cast<llvm::DefInit>(def));
}
std::string tblgen::DagLeaf::getConditionTemplate() const {
return getAsConstraint().getConditionTemplate();
}
llvm::StringRef tblgen::DagLeaf::getNativeCodeTemplate() const {
assert(isNativeCodeCall() && "the DAG leaf must be NativeCodeCall");
return cast<llvm::DefInit>(def)->getDef()->getValueAsString("expression");
}
bool tblgen::DagLeaf::isSubClassOf(StringRef superclass) const {
if (auto *defInit = dyn_cast_or_null<llvm::DefInit>(def))
return defInit->getDef()->isSubClassOf(superclass);
return false;
}
//===----------------------------------------------------------------------===//
// DagNode
//===----------------------------------------------------------------------===//
bool tblgen::DagNode::isNativeCodeCall() const {
if (auto *defInit = dyn_cast_or_null<llvm::DefInit>(node->getOperator()))
return defInit->getDef()->isSubClassOf("NativeCodeCall");
return false;
}
bool tblgen::DagNode::isOperation() const {
return !(isNativeCodeCall() || isReplaceWithValue());
}
llvm::StringRef tblgen::DagNode::getNativeCodeTemplate() const {
assert(isNativeCodeCall() && "the DAG leaf must be NativeCodeCall");
return cast<llvm::DefInit>(node->getOperator())
->getDef()
->getValueAsString("expression");
}
llvm::StringRef tblgen::DagNode::getSymbol() const {
return node->getNameStr();
}
Operator &tblgen::DagNode::getDialectOp(RecordOperatorMap *mapper) const {
llvm::Record *opDef = cast<llvm::DefInit>(node->getOperator())->getDef();
auto it = mapper->find(opDef);
if (it != mapper->end())
return *it->second;
return *mapper->try_emplace(opDef, llvm::make_unique<Operator>(opDef))
.first->second;
}
int tblgen::DagNode::getNumOps() const {
int count = isReplaceWithValue() ? 0 : 1;
for (int i = 0, e = getNumArgs(); i != e; ++i) {
if (auto child = getArgAsNestedDag(i))
count += child.getNumOps();
}
return count;
}
int tblgen::DagNode::getNumArgs() const { return node->getNumArgs(); }
bool tblgen::DagNode::isNestedDagArg(unsigned index) const {
return isa<llvm::DagInit>(node->getArg(index));
}
tblgen::DagNode tblgen::DagNode::getArgAsNestedDag(unsigned index) const {
return DagNode(dyn_cast_or_null<llvm::DagInit>(node->getArg(index)));
}
tblgen::DagLeaf tblgen::DagNode::getArgAsLeaf(unsigned index) const {
assert(!isNestedDagArg(index));
return DagLeaf(node->getArg(index));
}
StringRef tblgen::DagNode::getArgName(unsigned index) const {
return node->getArgNameStr(index);
}
bool tblgen::DagNode::isReplaceWithValue() const {
auto *dagOpDef = cast<llvm::DefInit>(node->getOperator())->getDef();
return dagOpDef->getName() == "replaceWithValue";
}
//===----------------------------------------------------------------------===//
// SymbolInfoMap
//===----------------------------------------------------------------------===//
StringRef tblgen::SymbolInfoMap::getValuePackName(StringRef symbol,
int *index) {
StringRef name, indexStr;
int idx = -1;
std::tie(name, indexStr) = symbol.rsplit("__");
if (indexStr.consumeInteger(10, idx)) {
// The second part is not an index; we return the whole symbol as-is.
return symbol;
}
if (index) {
*index = idx;
}
return name;
}
tblgen::SymbolInfoMap::SymbolInfo::SymbolInfo(const Operator *op,
SymbolInfo::Kind kind,
Optional<int> index)
: op(op), kind(kind), argIndex(index) {}
int tblgen::SymbolInfoMap::SymbolInfo::getStaticValueCount() const {
switch (kind) {
case Kind::Attr:
case Kind::Operand:
case Kind::Value:
return 1;
case Kind::Result:
return op->getNumResults();
}
}
std::string
tblgen::SymbolInfoMap::SymbolInfo::getVarDecl(StringRef name) const {
switch (kind) {
case Kind::Attr: {
auto type =
op->getArg(*argIndex).get<NamedAttribute *>()->attr.getStorageType();
return formatv("{0} {1};\n", type, name);
}
case Kind::Operand:
case Kind::Value: {
return formatv("Value *{0};\n", name);
}
case Kind::Result: {
// Use the op itself for the results.
return formatv("{0} {1};\n", op->getQualCppClassName(), name);
}
}
}
std::string
tblgen::SymbolInfoMap::SymbolInfo::getValueAndRangeUse(StringRef name,
int index) const {
switch (kind) {
case Kind::Attr:
case Kind::Operand: {
assert(index < 0 && "only allowed for symbol bound to result");
return name;
}
case Kind::Result: {
// TODO(b/133341698): The following is incorrect for variadic results. We
// should use getODSResults().
if (index >= 0) {
return formatv("{0}.getOperation()->getResult({1})", name, index);
}
// If referencing multiple results, compose a comma-separated list.
SmallVector<std::string, 4> values;
for (int i = 0, e = op->getNumResults(); i < e; ++i) {
values.push_back(formatv("{0}.getOperation()->getResult({1})", name, i));
}
return llvm::join(values, ", ");
}
case Kind::Value: {
assert(index < 0 && "only allowed for symbol bound to result");
assert(op == nullptr);
return name;
}
}
}
bool tblgen::SymbolInfoMap::bindOpArgument(StringRef symbol, const Operator &op,
int argIndex) {
StringRef name = getValuePackName(symbol);
if (name != symbol) {
auto error = formatv(
"symbol '{0}' with trailing index cannot bind to op argument", symbol);
PrintFatalError(loc, error);
}
auto symInfo = op.getArg(argIndex).is<NamedAttribute *>()
? SymbolInfo::getAttr(&op, argIndex)
: SymbolInfo::getOperand(&op, argIndex);
return symbolInfoMap.insert({symbol, symInfo}).second;
}
bool tblgen::SymbolInfoMap::bindOpResult(StringRef symbol, const Operator &op) {
StringRef name = getValuePackName(symbol);
return symbolInfoMap.insert({name, SymbolInfo::getResult(&op)}).second;
}
bool tblgen::SymbolInfoMap::bindValue(StringRef symbol) {
return symbolInfoMap.insert({symbol, SymbolInfo::getValue()}).second;
}
bool tblgen::SymbolInfoMap::contains(StringRef symbol) const {
return find(symbol) != symbolInfoMap.end();
}
tblgen::SymbolInfoMap::const_iterator
tblgen::SymbolInfoMap::find(StringRef key) const {
StringRef name = getValuePackName(key);
return symbolInfoMap.find(name);
}
int tblgen::SymbolInfoMap::getStaticValueCount(StringRef symbol) const {
StringRef name = getValuePackName(symbol);
if (name != symbol) {
// If there is a trailing index inside symbol, it references just one
// static value.
return 1;
}
// Otherwise, find how many it represents by querying the symbol's info.
return find(name)->getValue().getStaticValueCount();
}
std::string tblgen::SymbolInfoMap::getValueAndRangeUse(StringRef symbol) const {
int index = -1;
StringRef name = getValuePackName(symbol, &index);
auto it = symbolInfoMap.find(name);
if (it == symbolInfoMap.end()) {
auto error = formatv("referencing unbound symbol '{0}'", symbol);
PrintFatalError(loc, error);
}
return it->getValue().getValueAndRangeUse(name, index);
}
//===----------------------------------------------------------------------===//
// Pattern
//==----------------------------------------------------------------------===//
tblgen::Pattern::Pattern(const llvm::Record *def, RecordOperatorMap *mapper)
: def(*def), recordOpMap(mapper) {}
tblgen::DagNode tblgen::Pattern::getSourcePattern() const {
return tblgen::DagNode(def.getValueAsDag("sourcePattern"));
}
int tblgen::Pattern::getNumResultPatterns() const {
auto *results = def.getValueAsListInit("resultPatterns");
return results->size();
}
tblgen::DagNode tblgen::Pattern::getResultPattern(unsigned index) const {
auto *results = def.getValueAsListInit("resultPatterns");
return tblgen::DagNode(cast<llvm::DagInit>(results->getElement(index)));
}
void tblgen::Pattern::collectSourcePatternBoundSymbols(
tblgen::SymbolInfoMap &infoMap) {
collectBoundSymbols(getSourcePattern(), infoMap, /*isSrcPattern=*/true);
}
void tblgen::Pattern::collectResultPatternBoundSymbols(
tblgen::SymbolInfoMap &infoMap) {
for (int i = 0, e = getNumResultPatterns(); i < e; ++i) {
auto pattern = getResultPattern(i);
collectBoundSymbols(pattern, infoMap, /*isSrcPattern=*/false);
}
}
const tblgen::Operator &tblgen::Pattern::getSourceRootOp() {
return getSourcePattern().getDialectOp(recordOpMap);
}
tblgen::Operator &tblgen::Pattern::getDialectOp(DagNode node) {
return node.getDialectOp(recordOpMap);
}
std::vector<tblgen::AppliedConstraint> tblgen::Pattern::getConstraints() const {
auto *listInit = def.getValueAsListInit("constraints");
std::vector<tblgen::AppliedConstraint> ret;
ret.reserve(listInit->size());
for (auto it : *listInit) {
auto *dagInit = dyn_cast<llvm::DagInit>(it);
if (!dagInit)
PrintFatalError(def.getLoc(), "all elemements in Pattern multi-entity "
"constraints should be DAG nodes");
std::vector<std::string> entities;
entities.reserve(dagInit->arg_size());
for (auto *argName : dagInit->getArgNames())
entities.push_back(argName->getValue());
ret.emplace_back(cast<llvm::DefInit>(dagInit->getOperator())->getDef(),
dagInit->getNameStr(), std::move(entities));
}
return ret;
}
int tblgen::Pattern::getBenefit() const {
// The initial benefit value is a heuristic with number of ops in the source
// pattern.
int initBenefit = getSourcePattern().getNumOps();
llvm::DagInit *delta = def.getValueAsDag("benefitDelta");
if (delta->getNumArgs() != 1 || !isa<llvm::IntInit>(delta->getArg(0))) {
PrintFatalError(def.getLoc(),
"The 'addBenefit' takes and only takes one integer value");
}
return initBenefit + dyn_cast<llvm::IntInit>(delta->getArg(0))->getValue();
}
std::vector<tblgen::Pattern::IdentifierLine>
tblgen::Pattern::getLocation() const {
std::vector<std::pair<StringRef, unsigned>> result;
result.reserve(def.getLoc().size());
for (auto loc : def.getLoc()) {
unsigned buf = llvm::SrcMgr.FindBufferContainingLoc(loc);
assert(buf && "invalid source location");
result.emplace_back(
llvm::SrcMgr.getBufferInfo(buf).Buffer->getBufferIdentifier(),
llvm::SrcMgr.getLineAndColumn(loc, buf).first);
}
return result;
}
void tblgen::Pattern::collectBoundSymbols(DagNode tree, SymbolInfoMap &infoMap,
bool isSrcPattern) {
auto treeName = tree.getSymbol();
if (!tree.isOperation()) {
if (!treeName.empty()) {
PrintFatalError(
def.getLoc(),
formatv("binding symbol '{0}' to non-operation unsupported right now",
treeName));
}
return;
}
auto &op = getDialectOp(tree);
auto numOpArgs = op.getNumArgs();
auto numTreeArgs = tree.getNumArgs();
if (numOpArgs != numTreeArgs) {
auto err = formatv("op '{0}' argument number mismatch: "
"{1} in pattern vs. {2} in definition",
op.getOperationName(), numTreeArgs, numOpArgs);
PrintFatalError(def.getLoc(), err);
}
// The name attached to the DAG node's operator is for representing the
// results generated from this op. It should be remembered as bound results.
if (!treeName.empty()) {
if (!infoMap.bindOpResult(treeName, op))
PrintFatalError(def.getLoc(),
formatv("symbol '{0}' bound more than once", treeName));
}
for (int i = 0; i != numTreeArgs; ++i) {
if (auto treeArg = tree.getArgAsNestedDag(i)) {
// This DAG node argument is a DAG node itself. Go inside recursively.
collectBoundSymbols(treeArg, infoMap, isSrcPattern);
} else if (isSrcPattern) {
// We can only bind symbols to op arguments in source pattern. Those
// symbols are referenced in result patterns.
auto treeArgName = tree.getArgName(i);
if (!treeArgName.empty()) {
if (!infoMap.bindOpArgument(treeArgName, op, i)) {
auto err = formatv("symbol '{0}' bound more than once", treeArgName);
PrintFatalError(def.getLoc(), err);
}
}
}
}
}
<commit_msg>Add unreachable to avoid GCC -Wreturn-type warning<commit_after>//===- Pattern.cpp - Pattern wrapper class --------------------------------===//
//
// Copyright 2019 The MLIR 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.
// =============================================================================
//
// Pattern wrapper class to simplify using TableGen Record defining a MLIR
// Pattern.
//
//===----------------------------------------------------------------------===//
#include "mlir/TableGen/Pattern.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Support/FormatVariadic.h"
#include "llvm/TableGen/Error.h"
#include "llvm/TableGen/Record.h"
using namespace mlir;
using llvm::formatv;
using mlir::tblgen::Operator;
//===----------------------------------------------------------------------===//
// DagLeaf
//===----------------------------------------------------------------------===//
bool tblgen::DagLeaf::isUnspecified() const {
return dyn_cast_or_null<llvm::UnsetInit>(def);
}
bool tblgen::DagLeaf::isOperandMatcher() const {
// Operand matchers specify a type constraint.
return isSubClassOf("TypeConstraint");
}
bool tblgen::DagLeaf::isAttrMatcher() const {
// Attribute matchers specify an attribute constraint.
return isSubClassOf("AttrConstraint");
}
bool tblgen::DagLeaf::isNativeCodeCall() const {
return isSubClassOf("NativeCodeCall");
}
bool tblgen::DagLeaf::isConstantAttr() const {
return isSubClassOf("ConstantAttr");
}
bool tblgen::DagLeaf::isEnumAttrCase() const {
return isSubClassOf("EnumAttrCaseInfo");
}
tblgen::Constraint tblgen::DagLeaf::getAsConstraint() const {
assert((isOperandMatcher() || isAttrMatcher()) &&
"the DAG leaf must be operand or attribute");
return Constraint(cast<llvm::DefInit>(def)->getDef());
}
tblgen::ConstantAttr tblgen::DagLeaf::getAsConstantAttr() const {
assert(isConstantAttr() && "the DAG leaf must be constant attribute");
return ConstantAttr(cast<llvm::DefInit>(def));
}
tblgen::EnumAttrCase tblgen::DagLeaf::getAsEnumAttrCase() const {
assert(isEnumAttrCase() && "the DAG leaf must be an enum attribute case");
return EnumAttrCase(cast<llvm::DefInit>(def));
}
std::string tblgen::DagLeaf::getConditionTemplate() const {
return getAsConstraint().getConditionTemplate();
}
llvm::StringRef tblgen::DagLeaf::getNativeCodeTemplate() const {
assert(isNativeCodeCall() && "the DAG leaf must be NativeCodeCall");
return cast<llvm::DefInit>(def)->getDef()->getValueAsString("expression");
}
bool tblgen::DagLeaf::isSubClassOf(StringRef superclass) const {
if (auto *defInit = dyn_cast_or_null<llvm::DefInit>(def))
return defInit->getDef()->isSubClassOf(superclass);
return false;
}
//===----------------------------------------------------------------------===//
// DagNode
//===----------------------------------------------------------------------===//
bool tblgen::DagNode::isNativeCodeCall() const {
if (auto *defInit = dyn_cast_or_null<llvm::DefInit>(node->getOperator()))
return defInit->getDef()->isSubClassOf("NativeCodeCall");
return false;
}
bool tblgen::DagNode::isOperation() const {
return !(isNativeCodeCall() || isReplaceWithValue());
}
llvm::StringRef tblgen::DagNode::getNativeCodeTemplate() const {
assert(isNativeCodeCall() && "the DAG leaf must be NativeCodeCall");
return cast<llvm::DefInit>(node->getOperator())
->getDef()
->getValueAsString("expression");
}
llvm::StringRef tblgen::DagNode::getSymbol() const {
return node->getNameStr();
}
Operator &tblgen::DagNode::getDialectOp(RecordOperatorMap *mapper) const {
llvm::Record *opDef = cast<llvm::DefInit>(node->getOperator())->getDef();
auto it = mapper->find(opDef);
if (it != mapper->end())
return *it->second;
return *mapper->try_emplace(opDef, llvm::make_unique<Operator>(opDef))
.first->second;
}
int tblgen::DagNode::getNumOps() const {
int count = isReplaceWithValue() ? 0 : 1;
for (int i = 0, e = getNumArgs(); i != e; ++i) {
if (auto child = getArgAsNestedDag(i))
count += child.getNumOps();
}
return count;
}
int tblgen::DagNode::getNumArgs() const { return node->getNumArgs(); }
bool tblgen::DagNode::isNestedDagArg(unsigned index) const {
return isa<llvm::DagInit>(node->getArg(index));
}
tblgen::DagNode tblgen::DagNode::getArgAsNestedDag(unsigned index) const {
return DagNode(dyn_cast_or_null<llvm::DagInit>(node->getArg(index)));
}
tblgen::DagLeaf tblgen::DagNode::getArgAsLeaf(unsigned index) const {
assert(!isNestedDagArg(index));
return DagLeaf(node->getArg(index));
}
StringRef tblgen::DagNode::getArgName(unsigned index) const {
return node->getArgNameStr(index);
}
bool tblgen::DagNode::isReplaceWithValue() const {
auto *dagOpDef = cast<llvm::DefInit>(node->getOperator())->getDef();
return dagOpDef->getName() == "replaceWithValue";
}
//===----------------------------------------------------------------------===//
// SymbolInfoMap
//===----------------------------------------------------------------------===//
StringRef tblgen::SymbolInfoMap::getValuePackName(StringRef symbol,
int *index) {
StringRef name, indexStr;
int idx = -1;
std::tie(name, indexStr) = symbol.rsplit("__");
if (indexStr.consumeInteger(10, idx)) {
// The second part is not an index; we return the whole symbol as-is.
return symbol;
}
if (index) {
*index = idx;
}
return name;
}
tblgen::SymbolInfoMap::SymbolInfo::SymbolInfo(const Operator *op,
SymbolInfo::Kind kind,
Optional<int> index)
: op(op), kind(kind), argIndex(index) {}
int tblgen::SymbolInfoMap::SymbolInfo::getStaticValueCount() const {
switch (kind) {
case Kind::Attr:
case Kind::Operand:
case Kind::Value:
return 1;
case Kind::Result:
return op->getNumResults();
}
llvm_unreachable("unknown kind");
}
std::string
tblgen::SymbolInfoMap::SymbolInfo::getVarDecl(StringRef name) const {
switch (kind) {
case Kind::Attr: {
auto type =
op->getArg(*argIndex).get<NamedAttribute *>()->attr.getStorageType();
return formatv("{0} {1};\n", type, name);
}
case Kind::Operand:
case Kind::Value: {
return formatv("Value *{0};\n", name);
}
case Kind::Result: {
// Use the op itself for the results.
return formatv("{0} {1};\n", op->getQualCppClassName(), name);
}
}
llvm_unreachable("unknown kind");
}
std::string
tblgen::SymbolInfoMap::SymbolInfo::getValueAndRangeUse(StringRef name,
int index) const {
switch (kind) {
case Kind::Attr:
case Kind::Operand: {
assert(index < 0 && "only allowed for symbol bound to result");
return name;
}
case Kind::Result: {
// TODO(b/133341698): The following is incorrect for variadic results. We
// should use getODSResults().
if (index >= 0) {
return formatv("{0}.getOperation()->getResult({1})", name, index);
}
// If referencing multiple results, compose a comma-separated list.
SmallVector<std::string, 4> values;
for (int i = 0, e = op->getNumResults(); i < e; ++i) {
values.push_back(formatv("{0}.getOperation()->getResult({1})", name, i));
}
return llvm::join(values, ", ");
}
case Kind::Value: {
assert(index < 0 && "only allowed for symbol bound to result");
assert(op == nullptr);
return name;
}
}
llvm_unreachable("unknown kind");
}
bool tblgen::SymbolInfoMap::bindOpArgument(StringRef symbol, const Operator &op,
int argIndex) {
StringRef name = getValuePackName(symbol);
if (name != symbol) {
auto error = formatv(
"symbol '{0}' with trailing index cannot bind to op argument", symbol);
PrintFatalError(loc, error);
}
auto symInfo = op.getArg(argIndex).is<NamedAttribute *>()
? SymbolInfo::getAttr(&op, argIndex)
: SymbolInfo::getOperand(&op, argIndex);
return symbolInfoMap.insert({symbol, symInfo}).second;
}
bool tblgen::SymbolInfoMap::bindOpResult(StringRef symbol, const Operator &op) {
StringRef name = getValuePackName(symbol);
return symbolInfoMap.insert({name, SymbolInfo::getResult(&op)}).second;
}
bool tblgen::SymbolInfoMap::bindValue(StringRef symbol) {
return symbolInfoMap.insert({symbol, SymbolInfo::getValue()}).second;
}
bool tblgen::SymbolInfoMap::contains(StringRef symbol) const {
return find(symbol) != symbolInfoMap.end();
}
tblgen::SymbolInfoMap::const_iterator
tblgen::SymbolInfoMap::find(StringRef key) const {
StringRef name = getValuePackName(key);
return symbolInfoMap.find(name);
}
int tblgen::SymbolInfoMap::getStaticValueCount(StringRef symbol) const {
StringRef name = getValuePackName(symbol);
if (name != symbol) {
// If there is a trailing index inside symbol, it references just one
// static value.
return 1;
}
// Otherwise, find how many it represents by querying the symbol's info.
return find(name)->getValue().getStaticValueCount();
}
std::string tblgen::SymbolInfoMap::getValueAndRangeUse(StringRef symbol) const {
int index = -1;
StringRef name = getValuePackName(symbol, &index);
auto it = symbolInfoMap.find(name);
if (it == symbolInfoMap.end()) {
auto error = formatv("referencing unbound symbol '{0}'", symbol);
PrintFatalError(loc, error);
}
return it->getValue().getValueAndRangeUse(name, index);
}
//===----------------------------------------------------------------------===//
// Pattern
//==----------------------------------------------------------------------===//
tblgen::Pattern::Pattern(const llvm::Record *def, RecordOperatorMap *mapper)
: def(*def), recordOpMap(mapper) {}
tblgen::DagNode tblgen::Pattern::getSourcePattern() const {
return tblgen::DagNode(def.getValueAsDag("sourcePattern"));
}
int tblgen::Pattern::getNumResultPatterns() const {
auto *results = def.getValueAsListInit("resultPatterns");
return results->size();
}
tblgen::DagNode tblgen::Pattern::getResultPattern(unsigned index) const {
auto *results = def.getValueAsListInit("resultPatterns");
return tblgen::DagNode(cast<llvm::DagInit>(results->getElement(index)));
}
void tblgen::Pattern::collectSourcePatternBoundSymbols(
tblgen::SymbolInfoMap &infoMap) {
collectBoundSymbols(getSourcePattern(), infoMap, /*isSrcPattern=*/true);
}
void tblgen::Pattern::collectResultPatternBoundSymbols(
tblgen::SymbolInfoMap &infoMap) {
for (int i = 0, e = getNumResultPatterns(); i < e; ++i) {
auto pattern = getResultPattern(i);
collectBoundSymbols(pattern, infoMap, /*isSrcPattern=*/false);
}
}
const tblgen::Operator &tblgen::Pattern::getSourceRootOp() {
return getSourcePattern().getDialectOp(recordOpMap);
}
tblgen::Operator &tblgen::Pattern::getDialectOp(DagNode node) {
return node.getDialectOp(recordOpMap);
}
std::vector<tblgen::AppliedConstraint> tblgen::Pattern::getConstraints() const {
auto *listInit = def.getValueAsListInit("constraints");
std::vector<tblgen::AppliedConstraint> ret;
ret.reserve(listInit->size());
for (auto it : *listInit) {
auto *dagInit = dyn_cast<llvm::DagInit>(it);
if (!dagInit)
PrintFatalError(def.getLoc(), "all elemements in Pattern multi-entity "
"constraints should be DAG nodes");
std::vector<std::string> entities;
entities.reserve(dagInit->arg_size());
for (auto *argName : dagInit->getArgNames())
entities.push_back(argName->getValue());
ret.emplace_back(cast<llvm::DefInit>(dagInit->getOperator())->getDef(),
dagInit->getNameStr(), std::move(entities));
}
return ret;
}
int tblgen::Pattern::getBenefit() const {
// The initial benefit value is a heuristic with number of ops in the source
// pattern.
int initBenefit = getSourcePattern().getNumOps();
llvm::DagInit *delta = def.getValueAsDag("benefitDelta");
if (delta->getNumArgs() != 1 || !isa<llvm::IntInit>(delta->getArg(0))) {
PrintFatalError(def.getLoc(),
"The 'addBenefit' takes and only takes one integer value");
}
return initBenefit + dyn_cast<llvm::IntInit>(delta->getArg(0))->getValue();
}
std::vector<tblgen::Pattern::IdentifierLine>
tblgen::Pattern::getLocation() const {
std::vector<std::pair<StringRef, unsigned>> result;
result.reserve(def.getLoc().size());
for (auto loc : def.getLoc()) {
unsigned buf = llvm::SrcMgr.FindBufferContainingLoc(loc);
assert(buf && "invalid source location");
result.emplace_back(
llvm::SrcMgr.getBufferInfo(buf).Buffer->getBufferIdentifier(),
llvm::SrcMgr.getLineAndColumn(loc, buf).first);
}
return result;
}
void tblgen::Pattern::collectBoundSymbols(DagNode tree, SymbolInfoMap &infoMap,
bool isSrcPattern) {
auto treeName = tree.getSymbol();
if (!tree.isOperation()) {
if (!treeName.empty()) {
PrintFatalError(
def.getLoc(),
formatv("binding symbol '{0}' to non-operation unsupported right now",
treeName));
}
return;
}
auto &op = getDialectOp(tree);
auto numOpArgs = op.getNumArgs();
auto numTreeArgs = tree.getNumArgs();
if (numOpArgs != numTreeArgs) {
auto err = formatv("op '{0}' argument number mismatch: "
"{1} in pattern vs. {2} in definition",
op.getOperationName(), numTreeArgs, numOpArgs);
PrintFatalError(def.getLoc(), err);
}
// The name attached to the DAG node's operator is for representing the
// results generated from this op. It should be remembered as bound results.
if (!treeName.empty()) {
if (!infoMap.bindOpResult(treeName, op))
PrintFatalError(def.getLoc(),
formatv("symbol '{0}' bound more than once", treeName));
}
for (int i = 0; i != numTreeArgs; ++i) {
if (auto treeArg = tree.getArgAsNestedDag(i)) {
// This DAG node argument is a DAG node itself. Go inside recursively.
collectBoundSymbols(treeArg, infoMap, isSrcPattern);
} else if (isSrcPattern) {
// We can only bind symbols to op arguments in source pattern. Those
// symbols are referenced in result patterns.
auto treeArgName = tree.getArgName(i);
if (!treeArgName.empty()) {
if (!infoMap.bindOpArgument(treeArgName, op, i)) {
auto err = formatv("symbol '{0}' bound more than once", treeArgName);
PrintFatalError(def.getLoc(), err);
}
}
}
}
}
<|endoftext|>
|
<commit_before><commit_msg>Use the positions of the root bone in world space, contrarily to the other bones that are in bone space. This does not seem to be defined in the BVH specifications, but seems more commonly used by the different mocap systems.<commit_after><|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.