text
stringlengths 54
60.6k
|
|---|
<commit_before>// For conditions of distribution and use, see copyright notice in LICENSE
#include "StableHeaders.h"
#include "OgreSkeletonAsset.h"
#include "LoggingFunctions.h"
#include "Framework.h"
#include "AssetAPI.h"
#include "UrhoRenderer.h"
#include "OgreMeshDefines.h"
#include "Math/float3.h"
#include "Math/Quat.h"
#include <Urho3D/Core/Profiler.h>
#include <Urho3D/Core/StringUtils.h>
#include <Urho3D/IO/MemoryBuffer.h>
#include <Urho3D/Graphics/Animation.h>
#include <stdexcept>
namespace Tundra
{
using namespace Ogre;
static uint currentLength;
static const unsigned short HEADER_CHUNK_ID = 0x1000;
static const uint MSTREAM_OVERHEAD_SIZE = sizeof(u16) + sizeof(uint);
static const uint MSTREAM_BONE_SIZE_WITHOUT_SCALE = MSTREAM_OVERHEAD_SIZE + sizeof(u16) + (sizeof(float) * 7);
static const uint MSTREAM_KEYFRAME_SIZE_WITHOUT_SCALE = MSTREAM_OVERHEAD_SIZE + (sizeof(float) * 8);
enum SkeletonChunkId
{
SKELETON_HEADER = 0x1000,
// char* version : Version number check
SKELETON_BLENDMODE = 0x1010, // optional
// unsigned short blendmode : SkeletonAnimationBlendMode
SKELETON_BONE = 0x2000,
// Repeating section defining each bone in the system.
// Bones are assigned indexes automatically based on their order of declaration
// starting with 0.
// char* name : name of the bone
// unsigned short handle : handle of the bone, should be contiguous & start at 0
// Vector3 position : position of this bone relative to parent
// Quaternion orientation : orientation of this bone relative to parent
// Vector3 scale : scale of this bone relative to parent
SKELETON_BONE_PARENT = 0x3000,
// Record of the parent of a single bone, used to build the node tree
// Repeating section, listed in Bone Index order, one per Bone
// unsigned short handle : child bone
// unsigned short parentHandle : parent bone
SKELETON_ANIMATION = 0x4000,
// A single animation for this skeleton
// char* name : Name of the animation
// float length : Length of the animation in seconds
SKELETON_ANIMATION_BASEINFO = 0x4010,
// [Optional] base keyframe information
// char* baseAnimationName (blank for self)
// float baseKeyFrameTime
SKELETON_ANIMATION_TRACK = 0x4100,
// A single animation track (relates to a single bone)
// Repeating section (within SKELETON_ANIMATION)
// unsigned short boneIndex : Index of bone to apply to
SKELETON_ANIMATION_TRACK_KEYFRAME = 0x4110,
// A single keyframe within the track
// Repeating section
// float time : The time position (seconds)
// Quaternion rotate : Rotation to apply at this keyframe
// Vector3 translate : Translation to apply at this keyframe
// Vector3 scale : Scale to apply at this keyframe
SKELETON_ANIMATION_LINK = 0x5000
// Link to another skeleton, to re-use its animations
// char* skeletonName : name of skeleton to get animations from
// float scale : scale to apply to trans/scale keys
};
static String ReadLine(Urho3D::Deserializer& stream)
{
String str;
while(!stream.IsEof())
{
char c = stream.ReadByte();
if (c == '\n')
break;
str += c;
}
return str;
}
static u16 ReadHeader(Urho3D::Deserializer& stream, bool readLength = true)
{
u16 id = stream.ReadUShort();
if (readLength)
currentLength = stream.ReadUInt();
return id;
}
static Quat ReadQuat(Urho3D::Deserializer& stream)
{
Quat result;
stream.Read(&result.x, sizeof result);
return result;
}
static void RollbackHeader(Urho3D::Deserializer& stream)
{
stream.Seek(stream.GetPosition() - MSTREAM_OVERHEAD_SIZE);
}
static void SkipBytes(Urho3D::Deserializer& stream, uint numBytes)
{
stream.Seek(stream.GetPosition() + numBytes);
}
static void ReadSkeleton(Urho3D::Deserializer& stream, Skeleton *skeleton);
static void ReadBone(Urho3D::Deserializer& stream, Skeleton *skeleton);
static void ReadBoneParent(Urho3D::Deserializer& stream, Skeleton *skeleton);
static void ReadSkeletonAnimation(Urho3D::Deserializer& stream, Skeleton *skeleton);
static void ReadSkeletonAnimationTrack(Urho3D::Deserializer& stream, Skeleton *skeleton, Animation *dest);
static void ReadSkeletonAnimationKeyFrame(Urho3D::Deserializer& stream, VertexAnimationTrack *dest);
static void ReadSkeletonAnimationLink(Urho3D::Deserializer& stream, Skeleton *skeleton);
static void ReadSkeleton(Urho3D::Deserializer& stream, Skeleton *skeleton)
{
u16 id = ReadHeader(stream, false);
if (id != HEADER_CHUNK_ID) {
throw std::runtime_error("Invalid Ogre Skeleton file header.");
}
// This deserialization supports both versions of the skeleton spec
String version = ReadLine(stream);
/*
if (version != SKELETON_VERSION_1_8 && version != SKELETON_VERSION_1_1)
{
throw std::runtime_error(Formatter::format() << "Skeleton version " << version << " not supported by this importer."
<< " Supported versions: " << SKELETON_VERSION_1_8 << " and " << SKELETON_VERSION_1_1);
}
*/
while (!stream.IsEof())
{
id = ReadHeader(stream);
switch(id)
{
case SKELETON_BLENDMODE:
{
skeleton->blendMode = static_cast<Skeleton::BlendMode>(stream.ReadUShort());
break;
}
case SKELETON_BONE:
{
ReadBone(stream, skeleton);
break;
}
case SKELETON_BONE_PARENT:
{
ReadBoneParent(stream, skeleton);
break;
}
case SKELETON_ANIMATION:
{
ReadSkeletonAnimation(stream, skeleton);
break;
}
case SKELETON_ANIMATION_LINK:
{
ReadSkeletonAnimationLink(stream, skeleton);
break;
}
}
}
// Calculate bone matrices for root bones. Recursively calculates their children.
for (uint i=0, len=skeleton->bones.Size(); i<len; ++i)
{
Bone *bone = skeleton->bones[i];
if (!bone->IsParented())
bone->CalculateWorldMatrixAndDefaultPose(skeleton);
}
}
static void ReadBone(Urho3D::Deserializer& stream, Skeleton *skeleton)
{
Bone *bone = new Bone();
bone->name = ReadLine(stream);
bone->id = stream.ReadUShort();
// Pos and rot
bone->position = stream.ReadVector3();
bone->rotation = ReadQuat(stream);
// Scale (optional)
if (currentLength > MSTREAM_BONE_SIZE_WITHOUT_SCALE)
bone->scale = stream.ReadVector3();
// Bone indexes need to start from 0 and be contiguous
if (bone->id != skeleton->bones.Size()) {
throw std::runtime_error("Ogre Skeleton bone indexes not contiguous.");
}
skeleton->bones.Push(bone);
}
static void ReadBoneParent(Urho3D::Deserializer& stream, Skeleton *skeleton)
{
u16 childId = stream.ReadUShort();
u16 parentId = stream.ReadUShort();
Bone *child = skeleton->BoneById(childId);
Bone *parent = skeleton->BoneById(parentId);
if (child && parent)
parent->AddChild(child);
else
LogWarning("Failed to find bones for parenting: Child id " + String(childId) + " for parent id " + String(parentId));
}
static void ReadSkeletonAnimation(Urho3D::Deserializer& stream, Skeleton *skeleton)
{
Animation *anim = new Animation(skeleton);
anim->name = ReadLine(stream);
anim->length = stream.ReadFloat();
if (!stream.IsEof())
{
u16 id = ReadHeader(stream);
if (id == SKELETON_ANIMATION_BASEINFO)
{
anim->baseName = ReadLine(stream);
anim->baseTime = stream.ReadFloat();
// Advance to first track
id = ReadHeader(stream);
}
while (!stream.IsEof() && id == SKELETON_ANIMATION_TRACK)
{
ReadSkeletonAnimationTrack(stream, skeleton, anim);
if (!stream.IsEof())
id = ReadHeader(stream);
}
if (!stream.IsEof())
RollbackHeader(stream);
}
skeleton->animations.Push(anim);
}
static void ReadSkeletonAnimationTrack(Urho3D::Deserializer& stream, Skeleton * /*skeleton*/, Animation *dest)
{
u16 boneId = stream.ReadUShort();
Bone *bone = dest->parentSkeleton->BoneById(boneId);
if (!bone) {
throw std::runtime_error("Cannot read animation track, target bone not in target Skeleton");
}
VertexAnimationTrack track;
track.type = VertexAnimationTrack::VAT_TRANSFORM;
track.boneName = bone->name;
u16 id = ReadHeader(stream);
while (!stream.IsEof() && id == SKELETON_ANIMATION_TRACK_KEYFRAME)
{
ReadSkeletonAnimationKeyFrame(stream, &track);
if (!stream.IsEof())
id = ReadHeader(stream);
}
if (!stream.IsEof())
RollbackHeader(stream);
dest->tracks.Push(track);
}
static void ReadSkeletonAnimationKeyFrame(Urho3D::Deserializer& stream, VertexAnimationTrack *dest)
{
TransformKeyFrame keyframe;
keyframe.timePos = stream.ReadFloat();
// Rot and pos
keyframe.rotation = ReadQuat(stream);
keyframe.position = stream.ReadVector3();
// Scale (optional)
if (currentLength > MSTREAM_KEYFRAME_SIZE_WITHOUT_SCALE)
keyframe.scale = stream.ReadVector3();
// Note: transforms are now in Ogre's offset transform format. The bone's transform needs to be applied when converting to Urho animation
dest->transformKeyFrames.Push(keyframe);
}
static void ReadSkeletonAnimationLink(Urho3D::Deserializer& stream, Skeleton * /*skeleton*/)
{
// Skip bounds, not compatible with Assimp.
ReadLine(stream); // skeleton name
SkipBytes(stream, sizeof(float) * 3); // scale
}
OgreSkeletonAsset::OgreSkeletonAsset(AssetAPI *owner, const String &type_, const String &name_) :
IAsset(owner, type_, name_)
{
}
OgreSkeletonAsset::~OgreSkeletonAsset()
{
}
bool OgreSkeletonAsset::DeserializeFromData(const u8 *data_, uint numBytes, bool /*allowAsynchronous*/)
{
URHO3D_PROFILE(OgreSkeletonAsset_LoadFromFileInMemory);
/// Force an unload of previous data first.
Unload();
Urho3D::MemoryBuffer buffer(data_, numBytes);
SharedPtr<Ogre::Skeleton> ogreSkel(new Ogre::Skeleton());
try
{
ReadSkeleton(buffer, ogreSkel);
}
catch (std::exception& e)
{
LogError("OgreSkeletonAsset::DeserializeFromData: " + String(e.what()));
return false;
}
// Fill Urho bone structure
Vector<Urho3D::Bone>& bones = skeleton.GetModifiableBones();
bones.Resize(ogreSkel->bones.Size());
for (uint i = 0; i < ogreSkel->bones.Size(); ++i)
{
bones[i].name_ = ogreSkel->bones[i]->name;
bones[i].nameHash_ = StringHash(bones[i].name_);
if (ogreSkel->bones[i]->IsParented())
bones[i].parentIndex_ = ogreSkel->bones[i]->parentId;
else
{
bones[i].parentIndex_ = i;
skeleton.SetRootBoneIndex(i);
}
Urho3D::Matrix4 pose = ogreSkel->bones[i]->defaultPose;
Urho3D::Vector3 pos, scale;
Urho3D::Quaternion rot;
pose.Decompose(pos, rot, scale);
bones[i].animated_ = true;
bones[i].initialPosition_ = pos;
bones[i].initialRotation_ = rot;
bones[i].initialScale_ = scale;
bones[i].offsetMatrix_ = Urho3D::Matrix3x4(ogreSkel->bones[i]->worldMatrix).Inverse();
// The skeleton can not know the vertex information necessary to calculate bone bounding boxes. Therefore that data
// must be combined later from the mesh's data
}
// Create animations
for (uint i = 0; i < ogreSkel->animations.Size(); ++i)
{
Ogre::Animation* ogreAnim = ogreSkel->animations[i];
if (!ogreAnim)
continue;
String animName = ogreAnim->name;
if (animName.Empty())
continue;
SharedPtr<Urho3D::Animation> urhoAnim(new Urho3D::Animation(context_));
urhoAnim->SetLength(ogreAnim->length);
// Set both animation & resource name, same for now
urhoAnim->SetAnimationName(animName);
urhoAnim->SetName(animName);
for (uint j = 0; j < ogreAnim->tracks.Size(); ++j)
{
const Ogre::VertexAnimationTrack& ogreTrack = ogreAnim->tracks[j];
if (ogreTrack.type != Ogre::VertexAnimationTrack::VAT_TRANSFORM)
continue;
Urho3D::AnimationTrack* urhoTrack = urhoAnim->CreateTrack(ogreTrack.boneName);
urhoTrack->channelMask_ = Urho3D::CHANNEL_POSITION | Urho3D::CHANNEL_ROTATION;
Urho3D::Bone* urhoBone = 0;
for (uint k = 0; k < bones.Size(); ++k)
{
if (bones[k].name_ == urhoTrack->name_)
{
urhoBone = &bones[k];
break;
}
}
if (!urhoBone)
{
LogWarning("OgreSkeletonAsset::DeserializeFromData: found animation track referring to a non-existent bone " + urhoTrack->name_ + ", skipping");
continue;
}
for (uint k = 0; k < ogreTrack.transformKeyFrames.Size(); ++k)
{
const Ogre::TransformKeyFrame& ogreKeyframe = ogreTrack.transformKeyFrames[k];
Urho3D::AnimationKeyFrame urhoKeyframe;
urhoKeyframe.time_ = ogreKeyframe.timePos;
// Urho uses absolute bone poses in animation, while Ogre uses additive. Convert to absolute now.
urhoKeyframe.position_ = urhoBone->initialPosition_ + urhoBone->initialRotation_ * ogreKeyframe.position;
urhoKeyframe.rotation_ = urhoBone->initialRotation_ * ogreKeyframe.rotation;
urhoKeyframe.scale_ = ogreKeyframe.scale;
if (!ogreKeyframe.scale.Equals(float3(1.0f, 1.0f, 1.0f)))
urhoTrack->channelMask_ |= Urho3D::CHANNEL_SCALE;
urhoTrack->keyFrames_.Push(urhoKeyframe);
}
}
animations[animName] = urhoAnim;
}
// Inform load has finished.
assetAPI->AssetLoadCompleted(Name());
return true;
}
void OgreSkeletonAsset::DoUnload()
{
skeleton = Urho3D::Skeleton();
animations.Clear();
}
bool OgreSkeletonAsset::IsLoaded() const
{
return skeleton.GetNumBones() > 0;
}
Urho3D::Animation* OgreSkeletonAsset::AnimationByName(const String& name) const
{
HashMap<String, SharedPtr<Urho3D::Animation> >::ConstIterator i = animations.Find(name);
return i != animations.End() ? i->second_.Get() : nullptr;
}
}
<commit_msg>Simplify and fix Ogre -> Urho skeleton & animation conversion.<commit_after>// For conditions of distribution and use, see copyright notice in LICENSE
#include "StableHeaders.h"
#include "OgreSkeletonAsset.h"
#include "LoggingFunctions.h"
#include "Framework.h"
#include "AssetAPI.h"
#include "UrhoRenderer.h"
#include "OgreMeshDefines.h"
#include "Math/float3.h"
#include "Math/Quat.h"
#include <Urho3D/Core/Profiler.h>
#include <Urho3D/Core/StringUtils.h>
#include <Urho3D/IO/MemoryBuffer.h>
#include <Urho3D/Graphics/Animation.h>
#include <stdexcept>
namespace Tundra
{
using namespace Ogre;
static uint currentLength;
static const unsigned short HEADER_CHUNK_ID = 0x1000;
static const uint MSTREAM_OVERHEAD_SIZE = sizeof(u16) + sizeof(uint);
static const uint MSTREAM_BONE_SIZE_WITHOUT_SCALE = MSTREAM_OVERHEAD_SIZE + sizeof(u16) + (sizeof(float) * 7);
static const uint MSTREAM_KEYFRAME_SIZE_WITHOUT_SCALE = MSTREAM_OVERHEAD_SIZE + (sizeof(float) * 8);
enum SkeletonChunkId
{
SKELETON_HEADER = 0x1000,
// char* version : Version number check
SKELETON_BLENDMODE = 0x1010, // optional
// unsigned short blendmode : SkeletonAnimationBlendMode
SKELETON_BONE = 0x2000,
// Repeating section defining each bone in the system.
// Bones are assigned indexes automatically based on their order of declaration
// starting with 0.
// char* name : name of the bone
// unsigned short handle : handle of the bone, should be contiguous & start at 0
// Vector3 position : position of this bone relative to parent
// Quaternion orientation : orientation of this bone relative to parent
// Vector3 scale : scale of this bone relative to parent
SKELETON_BONE_PARENT = 0x3000,
// Record of the parent of a single bone, used to build the node tree
// Repeating section, listed in Bone Index order, one per Bone
// unsigned short handle : child bone
// unsigned short parentHandle : parent bone
SKELETON_ANIMATION = 0x4000,
// A single animation for this skeleton
// char* name : Name of the animation
// float length : Length of the animation in seconds
SKELETON_ANIMATION_BASEINFO = 0x4010,
// [Optional] base keyframe information
// char* baseAnimationName (blank for self)
// float baseKeyFrameTime
SKELETON_ANIMATION_TRACK = 0x4100,
// A single animation track (relates to a single bone)
// Repeating section (within SKELETON_ANIMATION)
// unsigned short boneIndex : Index of bone to apply to
SKELETON_ANIMATION_TRACK_KEYFRAME = 0x4110,
// A single keyframe within the track
// Repeating section
// float time : The time position (seconds)
// Quaternion rotate : Rotation to apply at this keyframe
// Vector3 translate : Translation to apply at this keyframe
// Vector3 scale : Scale to apply at this keyframe
SKELETON_ANIMATION_LINK = 0x5000
// Link to another skeleton, to re-use its animations
// char* skeletonName : name of skeleton to get animations from
// float scale : scale to apply to trans/scale keys
};
static String ReadLine(Urho3D::Deserializer& stream)
{
String str;
while(!stream.IsEof())
{
char c = stream.ReadByte();
if (c == '\n')
break;
str += c;
}
return str;
}
static u16 ReadHeader(Urho3D::Deserializer& stream, bool readLength = true)
{
u16 id = stream.ReadUShort();
if (readLength)
currentLength = stream.ReadUInt();
return id;
}
static Quat ReadQuat(Urho3D::Deserializer& stream)
{
Quat result;
stream.Read(&result.x, sizeof result);
return result;
}
static void RollbackHeader(Urho3D::Deserializer& stream)
{
stream.Seek(stream.GetPosition() - MSTREAM_OVERHEAD_SIZE);
}
static void SkipBytes(Urho3D::Deserializer& stream, uint numBytes)
{
stream.Seek(stream.GetPosition() + numBytes);
}
static void ReadSkeleton(Urho3D::Deserializer& stream, Skeleton *skeleton);
static void ReadBone(Urho3D::Deserializer& stream, Skeleton *skeleton);
static void ReadBoneParent(Urho3D::Deserializer& stream, Skeleton *skeleton);
static void ReadSkeletonAnimation(Urho3D::Deserializer& stream, Skeleton *skeleton);
static void ReadSkeletonAnimationTrack(Urho3D::Deserializer& stream, Skeleton *skeleton, Animation *dest);
static void ReadSkeletonAnimationKeyFrame(Urho3D::Deserializer& stream, VertexAnimationTrack *dest);
static void ReadSkeletonAnimationLink(Urho3D::Deserializer& stream, Skeleton *skeleton);
static void ReadSkeleton(Urho3D::Deserializer& stream, Skeleton *skeleton)
{
u16 id = ReadHeader(stream, false);
if (id != HEADER_CHUNK_ID) {
throw std::runtime_error("Invalid Ogre Skeleton file header.");
}
// This deserialization supports both versions of the skeleton spec
String version = ReadLine(stream);
/*
if (version != SKELETON_VERSION_1_8 && version != SKELETON_VERSION_1_1)
{
throw std::runtime_error(Formatter::format() << "Skeleton version " << version << " not supported by this importer."
<< " Supported versions: " << SKELETON_VERSION_1_8 << " and " << SKELETON_VERSION_1_1);
}
*/
while (!stream.IsEof())
{
id = ReadHeader(stream);
switch(id)
{
case SKELETON_BLENDMODE:
{
skeleton->blendMode = static_cast<Skeleton::BlendMode>(stream.ReadUShort());
break;
}
case SKELETON_BONE:
{
ReadBone(stream, skeleton);
break;
}
case SKELETON_BONE_PARENT:
{
ReadBoneParent(stream, skeleton);
break;
}
case SKELETON_ANIMATION:
{
ReadSkeletonAnimation(stream, skeleton);
break;
}
case SKELETON_ANIMATION_LINK:
{
ReadSkeletonAnimationLink(stream, skeleton);
break;
}
}
}
// Calculate bone matrices for root bones. Recursively calculates their children.
for (uint i=0, len=skeleton->bones.Size(); i<len; ++i)
{
Bone *bone = skeleton->bones[i];
if (!bone->IsParented())
bone->CalculateWorldMatrixAndDefaultPose(skeleton);
}
}
static void ReadBone(Urho3D::Deserializer& stream, Skeleton *skeleton)
{
Bone *bone = new Bone();
bone->name = ReadLine(stream);
bone->id = stream.ReadUShort();
// Pos and rot
bone->position = stream.ReadVector3();
bone->rotation = ReadQuat(stream);
// Scale (optional)
if (currentLength > MSTREAM_BONE_SIZE_WITHOUT_SCALE)
bone->scale = stream.ReadVector3();
// Bone indexes need to start from 0 and be contiguous
if (bone->id != skeleton->bones.Size()) {
throw std::runtime_error("Ogre Skeleton bone indexes not contiguous.");
}
skeleton->bones.Push(bone);
}
static void ReadBoneParent(Urho3D::Deserializer& stream, Skeleton *skeleton)
{
u16 childId = stream.ReadUShort();
u16 parentId = stream.ReadUShort();
Bone *child = skeleton->BoneById(childId);
Bone *parent = skeleton->BoneById(parentId);
if (child && parent)
parent->AddChild(child);
else
LogWarning("Failed to find bones for parenting: Child id " + String(childId) + " for parent id " + String(parentId));
}
static void ReadSkeletonAnimation(Urho3D::Deserializer& stream, Skeleton *skeleton)
{
Animation *anim = new Animation(skeleton);
anim->name = ReadLine(stream);
anim->length = stream.ReadFloat();
if (!stream.IsEof())
{
u16 id = ReadHeader(stream);
if (id == SKELETON_ANIMATION_BASEINFO)
{
anim->baseName = ReadLine(stream);
anim->baseTime = stream.ReadFloat();
// Advance to first track
id = ReadHeader(stream);
}
while (!stream.IsEof() && id == SKELETON_ANIMATION_TRACK)
{
ReadSkeletonAnimationTrack(stream, skeleton, anim);
if (!stream.IsEof())
id = ReadHeader(stream);
}
if (!stream.IsEof())
RollbackHeader(stream);
}
skeleton->animations.Push(anim);
}
static void ReadSkeletonAnimationTrack(Urho3D::Deserializer& stream, Skeleton * /*skeleton*/, Animation *dest)
{
u16 boneId = stream.ReadUShort();
Bone *bone = dest->parentSkeleton->BoneById(boneId);
if (!bone) {
throw std::runtime_error("Cannot read animation track, target bone not in target Skeleton");
}
VertexAnimationTrack track;
track.type = VertexAnimationTrack::VAT_TRANSFORM;
track.boneName = bone->name;
u16 id = ReadHeader(stream);
while (!stream.IsEof() && id == SKELETON_ANIMATION_TRACK_KEYFRAME)
{
ReadSkeletonAnimationKeyFrame(stream, &track);
if (!stream.IsEof())
id = ReadHeader(stream);
}
if (!stream.IsEof())
RollbackHeader(stream);
dest->tracks.Push(track);
}
static void ReadSkeletonAnimationKeyFrame(Urho3D::Deserializer& stream, VertexAnimationTrack *dest)
{
TransformKeyFrame keyframe;
keyframe.timePos = stream.ReadFloat();
// Rot and pos
keyframe.rotation = ReadQuat(stream);
keyframe.position = stream.ReadVector3();
// Scale (optional)
if (currentLength > MSTREAM_KEYFRAME_SIZE_WITHOUT_SCALE)
keyframe.scale = stream.ReadVector3();
// Note: transforms are now in Ogre's offset transform format. The bone's transform needs to be applied when converting to Urho animation
dest->transformKeyFrames.Push(keyframe);
}
static void ReadSkeletonAnimationLink(Urho3D::Deserializer& stream, Skeleton * /*skeleton*/)
{
// Skip bounds, not compatible with Assimp.
ReadLine(stream); // skeleton name
SkipBytes(stream, sizeof(float) * 3); // scale
}
OgreSkeletonAsset::OgreSkeletonAsset(AssetAPI *owner, const String &type_, const String &name_) :
IAsset(owner, type_, name_)
{
}
OgreSkeletonAsset::~OgreSkeletonAsset()
{
}
bool OgreSkeletonAsset::DeserializeFromData(const u8 *data_, uint numBytes, bool /*allowAsynchronous*/)
{
URHO3D_PROFILE(OgreSkeletonAsset_LoadFromFileInMemory);
/// Force an unload of previous data first.
Unload();
Urho3D::MemoryBuffer buffer(data_, numBytes);
SharedPtr<Ogre::Skeleton> ogreSkel(new Ogre::Skeleton());
try
{
ReadSkeleton(buffer, ogreSkel);
}
catch (std::exception& e)
{
LogError("OgreSkeletonAsset::DeserializeFromData: " + String(e.what()));
return false;
}
// Fill Urho bone structure
Vector<Urho3D::Bone>& bones = skeleton.GetModifiableBones();
bones.Resize(ogreSkel->bones.Size());
for (uint i = 0; i < ogreSkel->bones.Size(); ++i)
{
Ogre::Bone* ogreBone = ogreSkel->bones[i];
bones[i].name_ = ogreBone->name;
bones[i].nameHash_ = StringHash(bones[i].name_);
if (ogreBone->IsParented())
bones[i].parentIndex_ = ogreBone->parentId;
else
{
bones[i].parentIndex_ = i;
skeleton.SetRootBoneIndex(i);
}
bones[i].animated_ = true;
bones[i].initialPosition_ = ogreBone->position;
bones[i].initialRotation_ = ogreBone->rotation;
bones[i].initialScale_ = ogreBone->scale;
bones[i].offsetMatrix_ = Urho3D::Matrix3x4(ogreSkel->bones[i]->worldMatrix).Inverse();
// The skeleton can not know the vertex information necessary to calculate bone bounding boxes. Therefore that data
// must be combined later from the mesh's data
}
// Create animations
for (uint i = 0; i < ogreSkel->animations.Size(); ++i)
{
Ogre::Animation* ogreAnim = ogreSkel->animations[i];
if (!ogreAnim)
continue;
String animName = ogreAnim->name;
if (animName.Empty())
continue;
SharedPtr<Urho3D::Animation> urhoAnim(new Urho3D::Animation(context_));
urhoAnim->SetLength(ogreAnim->length);
// Set both animation & resource name, same for now
urhoAnim->SetAnimationName(animName);
urhoAnim->SetName(animName);
for (uint j = 0; j < ogreAnim->tracks.Size(); ++j)
{
const Ogre::VertexAnimationTrack& ogreTrack = ogreAnim->tracks[j];
if (ogreTrack.type != Ogre::VertexAnimationTrack::VAT_TRANSFORM)
continue;
Urho3D::AnimationTrack* urhoTrack = urhoAnim->CreateTrack(ogreTrack.boneName);
urhoTrack->channelMask_ = Urho3D::CHANNEL_POSITION | Urho3D::CHANNEL_ROTATION;
Urho3D::Bone* urhoBone = 0;
for (uint k = 0; k < bones.Size(); ++k)
{
if (bones[k].name_ == urhoTrack->name_)
{
urhoBone = &bones[k];
break;
}
}
if (!urhoBone)
{
LogWarning("OgreSkeletonAsset::DeserializeFromData: found animation track referring to a non-existent bone " + urhoTrack->name_ + ", skipping");
continue;
}
for (uint k = 0; k < ogreTrack.transformKeyFrames.Size(); ++k)
{
const Ogre::TransformKeyFrame& ogreKeyframe = ogreTrack.transformKeyFrames[k];
Urho3D::AnimationKeyFrame urhoKeyframe;
urhoKeyframe.time_ = ogreKeyframe.timePos;
// Urho uses absolute bone poses in animation, while Ogre uses additive. Convert to absolute now.
urhoKeyframe.position_ = urhoBone->initialPosition_ + ogreKeyframe.position;
urhoKeyframe.rotation_ = urhoBone->initialRotation_ * ogreKeyframe.rotation;
urhoKeyframe.scale_ = ogreKeyframe.scale;
if (!ogreKeyframe.scale.Equals(float3(1.0f, 1.0f, 1.0f)))
urhoTrack->channelMask_ |= Urho3D::CHANNEL_SCALE;
urhoTrack->keyFrames_.Push(urhoKeyframe);
}
}
animations[animName] = urhoAnim;
}
// Inform load has finished.
assetAPI->AssetLoadCompleted(Name());
return true;
}
void OgreSkeletonAsset::DoUnload()
{
skeleton = Urho3D::Skeleton();
animations.Clear();
}
bool OgreSkeletonAsset::IsLoaded() const
{
return skeleton.GetNumBones() > 0;
}
Urho3D::Animation* OgreSkeletonAsset::AnimationByName(const String& name) const
{
HashMap<String, SharedPtr<Urho3D::Animation> >::ConstIterator i = animations.Find(name);
return i != animations.End() ? i->second_.Get() : nullptr;
}
}
<|endoftext|>
|
<commit_before>#include "Utility/String.h"
#include <string>
#include <vector>
#include <stdexcept>
namespace String
{
namespace
{
const auto whitespace = " \t\n";
}
}
std::vector<std::string> String::split(std::string s, std::string delim, size_t count)
{
if(delim.empty())
{
s = remove_extra_whitespace(s);
delim = " ";
}
std::vector<std::string> result;
size_t start_index = 0;
size_t end_index = 0;
size_t split_count = 0;
while(end_index < s.size() && split_count < count)
{
end_index = s.find(delim, start_index);
result.push_back(s.substr(start_index, end_index-start_index));
start_index = std::max(end_index, end_index + delim.size());
++split_count;
}
if(start_index < s.size())
{
result.push_back(s.substr(start_index));
}
else if(end_index < s.size())
{
result.push_back({}); // Original string ended with delimiter
}
return result;
}
bool String::starts_with(const std::string& s, const std::string& beginning)
{
return (beginning.size() <= s.size()) && std::equal(beginning.begin(), beginning.end(), s.begin());
}
bool String::ends_with(const std::string& s, const std::string& ending)
{
return (ending.size() <= s.size()) && std::equal(ending.rbegin(), ending.rend(), s.rbegin());
}
std::string String::trim_outer_whitespace(const std::string& s)
{
auto text_start = s.find_first_not_of(whitespace);
if(text_start == std::string::npos)
{
return {};
}
auto text_end = s.find_last_not_of(whitespace);
return s.substr(text_start, text_end - text_start + 1);
}
std::string String::remove_extra_whitespace(const std::string& s)
{
std::string result;
for(auto c : trim_outer_whitespace(s))
{
if(contains(whitespace, c))
{
if(result.back() != ' ')
{
result.push_back(' ');
}
}
else
{
result.push_back(c);
}
}
return result;
}
std::string String::strip_comments(const std::string& str, const std::string& comment)
{
return trim_outer_whitespace(str.substr(0, str.find(comment)));
}
std::string String::strip_block_comment(const std::string& str, const std::string& start, const std::string& end)
{
auto start_comment_index = str.find(start);
auto end_comment_index = str.find(end);
if(start_comment_index == std::string::npos && end_comment_index == std::string::npos)
{
return trim_outer_whitespace(str);
}
if(start_comment_index == std::string::npos || end_comment_index == std::string::npos)
{
throw std::runtime_error("\"" + str + "\" is missing a comment delimiter: " + std::string{start} + std::string{end});
}
if(start_comment_index >= end_comment_index)
{
throw std::runtime_error("\"" + str + "\" contains bad comment delimiters: " + std::string{start} + std::string{end});
}
auto first_part = str.substr(0, start_comment_index);
auto last_part = str.substr(end_comment_index + end.size());
return strip_block_comment(trim_outer_whitespace(first_part) + " " + trim_outer_whitespace(last_part), start, end);
}
std::string String::lowercase(std::string s)
{
for(auto& c : s){ c = std::tolower(c); }
return s;
}
<commit_msg>Add #includes for Windows compilation<commit_after>#include "Utility/String.h"
#include <string>
#include <vector>
#include <stdexcept>
#include <algorithm>
#include <cctype>
namespace String
{
namespace
{
const auto whitespace = " \t\n";
}
}
std::vector<std::string> String::split(std::string s, std::string delim, size_t count)
{
if(delim.empty())
{
s = remove_extra_whitespace(s);
delim = " ";
}
std::vector<std::string> result;
size_t start_index = 0;
size_t end_index = 0;
size_t split_count = 0;
while(end_index < s.size() && split_count < count)
{
end_index = s.find(delim, start_index);
result.push_back(s.substr(start_index, end_index-start_index));
start_index = std::max(end_index, end_index + delim.size());
++split_count;
}
if(start_index < s.size())
{
result.push_back(s.substr(start_index));
}
else if(end_index < s.size())
{
result.push_back({}); // Original string ended with delimiter
}
return result;
}
bool String::starts_with(const std::string& s, const std::string& beginning)
{
return (beginning.size() <= s.size()) && std::equal(beginning.begin(), beginning.end(), s.begin());
}
bool String::ends_with(const std::string& s, const std::string& ending)
{
return (ending.size() <= s.size()) && std::equal(ending.rbegin(), ending.rend(), s.rbegin());
}
std::string String::trim_outer_whitespace(const std::string& s)
{
auto text_start = s.find_first_not_of(whitespace);
if(text_start == std::string::npos)
{
return {};
}
auto text_end = s.find_last_not_of(whitespace);
return s.substr(text_start, text_end - text_start + 1);
}
std::string String::remove_extra_whitespace(const std::string& s)
{
std::string result;
for(auto c : trim_outer_whitespace(s))
{
if(contains(whitespace, c))
{
if(result.back() != ' ')
{
result.push_back(' ');
}
}
else
{
result.push_back(c);
}
}
return result;
}
std::string String::strip_comments(const std::string& str, const std::string& comment)
{
return trim_outer_whitespace(str.substr(0, str.find(comment)));
}
std::string String::strip_block_comment(const std::string& str, const std::string& start, const std::string& end)
{
auto start_comment_index = str.find(start);
auto end_comment_index = str.find(end);
if(start_comment_index == std::string::npos && end_comment_index == std::string::npos)
{
return trim_outer_whitespace(str);
}
if(start_comment_index == std::string::npos || end_comment_index == std::string::npos)
{
throw std::runtime_error("\"" + str + "\" is missing a comment delimiter: " + std::string{start} + std::string{end});
}
if(start_comment_index >= end_comment_index)
{
throw std::runtime_error("\"" + str + "\" contains bad comment delimiters: " + std::string{start} + std::string{end});
}
auto first_part = str.substr(0, start_comment_index);
auto last_part = str.substr(end_comment_index + end.size());
return strip_block_comment(trim_outer_whitespace(first_part) + " " + trim_outer_whitespace(last_part), start, end);
}
std::string String::lowercase(std::string s)
{
for(auto& c : s){ c = std::tolower(c); }
return s;
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <cmath>
using namespace std;
class Point3D {
double x;
double y;
double z;
public:
double getX() {
return x;
}
double getY() {
return y;
}
double getZ() {
return z;
}
void setX(double newX) {
x = newX;
}
void setY(double newY) {
y = newY;
}
void setZ(double newZ) {
z = newZ;
}
void translate(Point3D translationVector) {
setX(getX() + translationVector.getX());
setY(getY() + translationVector.getY());
setZ(getZ() + translationVector.getZ());
}
double distanceTo(Point3D other) {
return sqrt(pow(getX() - other.getX(), 2) +
pow(getY() - other.getY(), 2) +
pow(getZ() - other.getZ(), 2));
}
void print() {
cout << '(' << getX() << ", " << getY() << ", " << getZ() << ')' << '\n';
}
};
class Triangle {
Point3D aVertex;
Point3D bVertex;
Point3D cVertex;
public:
double getASide() {
return bVertex.distanceTo(cVertex);
}
double getBSide() {
return aVertex.distanceTo(cVertex);
}
double getCSide() {
return aVertex.distanceTo(bVertex);
}
double perimeter() {
return getASide() + getBSide() + getCSide();
}
double area() {
double p = perimeter() / 2;
return sqrt(p * (p - getASide()) * (p - getBSide()) * (p - getCSide()));
}
void translate(Point3D translationVector) {
aVertex.translate(translationVector);
bVertex.translate(translationVector);
cVertex.translate(translationVector);
}
};
int main() {
return 0;
}<commit_msg>Add constructor for Triangle class. Triangle constructor implementation requires to add a default constructor for the Point3D class because we initialize the vertices in the body of the constructor instead of initialize them in the initialize list of the constructor in which way the default constructor will be called.<commit_after>#include <iostream>
#include <cmath>
using namespace std;
class Point3D {
double x;
double y;
double z;
public:
Point3D(double x = 0, double y = 0, double z = 0) {
setX(x);
setY(y);
setZ(z);
}
double getX() {
return x;
}
double getY() {
return y;
}
double getZ() {
return z;
}
void setX(double newX) {
x = newX;
}
void setY(double newY) {
y = newY;
}
void setZ(double newZ) {
z = newZ;
}
void translate(Point3D translationVector) {
setX(getX() + translationVector.getX());
setY(getY() + translationVector.getY());
setZ(getZ() + translationVector.getZ());
}
double distanceTo(Point3D other) {
return sqrt(pow(getX() - other.getX(), 2) +
pow(getY() - other.getY(), 2) +
pow(getZ() - other.getZ(), 2));
}
void print() {
cout << '(' << getX() << ", " << getY() << ", " << getZ() << ')' << '\n';
}
};
class Triangle {
Point3D aVertex;
Point3D bVertex;
Point3D cVertex;
public:
Triangle(Point3D _aVertex, Point3D _bVertex, Point3D _cVertex) {
aVertex = _aVertex;
bVertex = _bVertex;
cVertex = _cVertex;
}
double getASide() {
return bVertex.distanceTo(cVertex);
}
double getBSide() {
return aVertex.distanceTo(cVertex);
}
double getCSide() {
return aVertex.distanceTo(bVertex);
}
double perimeter() {
return getASide() + getBSide() + getCSide();
}
double area() {
double p = perimeter() / 2;
return sqrt(p * (p - getASide()) * (p - getBSide()) * (p - getCSide()));
}
void translate(Point3D translationVector) {
aVertex.translate(translationVector);
bVertex.translate(translationVector);
cVertex.translate(translationVector);
}
};
int main() {
return 0;
}<|endoftext|>
|
<commit_before>#include "ValueProcessor.h"
#include <sstream>
#include <iostream>
template <class T>
inline std::string to_string (const T& t)
{
std::stringstream ss;
ss << t;
return ss.str();
}
ValueProcessor::ValueProcessor() {}
ValueProcessor::~ValueProcessor() {}
TokenList* ValueProcessor::processValue(TokenList* value) {
TokenList newvalue;
Value* v;
std::cout << *value->toString() << endl;
while (value->size() > 0) {
v = processStatement(value);
if (v != NULL) {
if (newvalue.size() > 0)
newvalue.push(new Token(" ", Token::WHITESPACE));
newvalue.push(v->getToken()->clone());
delete v;
} else if (value->size() > 0) {
if (value->front()->type == Token::ATKEYWORD &&
variables.count(value->front()->str)) {
newvalue.push(variables[value->front()->str]);
delete value->shift();
} else {
if (value->size() > 1) {
TokenList* var = processDeepVariable(value->front(), value->at(1));
if (var != NULL) {
newvalue.push(var);
delete value->shift();
delete value->shift();
} else
newvalue.push(value->shift());
} else
newvalue.push(value->shift());
}
}
}
value->push(&newvalue);
return value;
}
void ValueProcessor::putVariable(string key, TokenList* value) {
variables[key] = value;
}
Value* ValueProcessor::processStatement(TokenList* value) {
Value* op, *v = processConstant(value);
if (v != NULL) {
while ((op = processOperator(value, v)))
v = op;
return v;
} else
return NULL;
}
Value* ValueProcessor::processOperator(TokenList* value, Value* v1,
Token* lastop) {
Value* v2, *tmp;
Token* op;
string operators("+-*/");
while (value->size() > 0 &&
value->front()->type == Token::WHITESPACE) {
delete value->shift();
}
if (value->size() == 0 ||
operators.find(value->front()->str) == string::npos)
return NULL;
if (lastop != NULL &&
operators.find(lastop->str) >
operators.find(value->front()->str)) {
return v1;
}
op = value->shift();
v2 = processConstant(value);
if (v2 == NULL) {
if (value->size() > 0)
throw new ParseException(value->front()->str, "Constant or @-variable");
else
throw new ParseException("end of line", "Constant or @-variable");
}
while ((tmp = processOperator(value, v2, op)))
v2 = tmp;
if (op->str == "+")
v1->add(v2);
else if (op->str == "-")
v1->substract(v2);
else if (op->str == "*")
v1->multiply(v2);
else if (op->str == "/")
v1->divide(v2);
delete v2;
return v1;
}
Value* ValueProcessor::processConstant(TokenList* value) {
Token* token;
Value* ret;
vector<Value*> arguments;
while (value->size() > 0 &&
value->front()->type == Token::WHITESPACE) {
delete value->shift();
}
if (value->size() == 0)
return NULL;
token = value->front();
switch(token->type) {
case Token::HASH:
// generate color from hex value
return new Color(value->shift());
case Token::NUMBER:
case Token::PERCENTAGE:
case Token::DIMENSION:
return new Value(value->shift());
case Token::FUNCTION:
value->shift();
if (value->front()->type != Token::PAREN_CLOSED)
arguments.push_back(processConstant(value));
while (value->front()->str == ",") {
delete value->shift();
arguments.push_back(processConstant(value));
}
if (value->front()->type == Token::PAREN_CLOSED)
delete value->shift();
return processFunction(token, arguments);
case Token::ATKEYWORD:
if (variables.count(token->str)) {
ret = processConstant(variables[token->str]);
delete value->shift();
return ret;
} else
return NULL;
case Token::PAREN_OPEN:
delete value->shift();
ret = processStatement(value);
if (value->front()->type == Token::PAREN_CLOSED)
delete value->shift();
return ret;
default:
if (value->size() > 1) {
TokenList* var = processDeepVariable(token, value->at(1));
if (var != NULL) {
ret = processStatement(var);
if (ret != NULL) {
delete value->shift();
delete value->shift();
return ret;
}
}
}
return NULL;
}
}
TokenList* ValueProcessor::processDeepVariable (Token* token, Token* nexttoken) {
TokenList* var;
string key("@");
if (token->type != Token::OTHER ||
token->str != "@" ||
nexttoken->type != Token::ATKEYWORD ||
!variables.count(nexttoken->str))
return NULL;
var = variables[nexttoken->str];
if (var->size() > 1 || var->front()->type != Token::STRING)
return NULL;
// generate key with '@' + var without quotes
key.append(var->front()->
str.substr(1, var->front()->str.size() - 2));
if (!variables.count(key))
return NULL;
return variables[key];
}
Value* ValueProcessor::processFunction(Token* function,
vector<Value*> arguments) {
Color* color;
string percentage;
if(function->str == "rgb(") {
if (arguments.size() == 3 &&
arguments[0]->type == Value::NUMBER &&
arguments[1]->type == Value::NUMBER &&
arguments[2]->type == Value::NUMBER) {
return new Color(0,0,0);
}
// Color rgb(@red: NUMBER, @green: NUMBER, @blue: NUMBER)
} else if (function->str == "lighten(") {
// Color lighten(Color, PERCENTAGE)
if (arguments.size() == 2 &&
arguments[0]->type == Value::COLOR &&
arguments[1]->type == Value::PERCENTAGE) {
static_cast<Color*>(arguments[0])->lighten(arguments[1]->getPercent());
return arguments[0];
}
} else if (function->str == "darken(") {
// Color darken(Color, PERCENTAGE)
if (arguments.size() == 2 &&
arguments[0]->type == Value::COLOR &&
arguments[1]->type == Value::PERCENTAGE) {
static_cast<Color*>(arguments[0])->darken(arguments[1]->getPercent());
return arguments[0];
}
} else if (function->str == "saturate(") {
// Color saturate(Color, PERCENTAGE)
if (arguments.size() == 2 &&
arguments[0]->type == Value::COLOR &&
arguments[1]->type == Value::PERCENTAGE) {
static_cast<Color*>(arguments[0])->saturate(arguments[1]->getPercent());
return arguments[0];
}
} else if (function->str == "desaturate(") {
// Color desaturate(Color, PERCENTAGE)
if (arguments.size() == 2 &&
arguments[0]->type == Value::COLOR &&
arguments[1]->type == Value::PERCENTAGE) {
static_cast<Color*>(arguments[0])->desaturate(arguments[1]->getPercent());
return arguments[0];
}
} else if (function->str == "fadein(") {
// Color fadein(Color, PERCENTAGE)
if (arguments.size() == 2 &&
arguments[0]->type == Value::COLOR &&
arguments[1]->type == Value::PERCENTAGE) {
static_cast<Color*>(arguments[0])->fadein(arguments[1]->getPercent());
return arguments[0];
}
} else if (function->str == "fadeout(") {
// Color fadeout(Color, PERCENTAGE)
if (arguments.size() == 2 &&
arguments[0]->type == Value::COLOR &&
arguments[1]->type == Value::PERCENTAGE) {
static_cast<Color*>(arguments[0])->fadeout(arguments[1]->getPercent());
return arguments[0];
}
} else if (function->str == "spin(") {
// Color fadein(Color, PERCENTAGE)
if (arguments.size() == 2 &&
arguments[0]->type == Value::COLOR &&
arguments[1]->type == Value::PERCENTAGE) {
static_cast<Color*>(arguments[0])->spin(arguments[1]->getPercent());
return arguments[0];
}
} else if (function->str == "hsl(") {
// Color hsl(PERCENTAGE, PERCENTAGE, PERCENTAGE)
if (arguments.size() == 3 &&
arguments[0]->type == Value::PERCENTAGE &&
arguments[1]->type == Value::PERCENTAGE &&
arguments[2]->type == Value::PERCENTAGE) {
color = new Color(0,0,0);
color->setHSL(arguments[0]->getPercent(),
arguments[1]->getPercent(),
arguments[2]->getPercent());
return color;
}
} else if (function->str == "hue(") {
// PERCENTAGE hue(Color)
if (arguments.size() == 1 &&
arguments[0]->type == Value::COLOR) {
percentage.append(to_string(static_cast<Color*>(arguments[0])->getHue()));
percentage.append("%");
return new Value(new Token(percentage, Token::PERCENTAGE));
}
} else if (function->str == "saturation(") {
// PERCENTAGE saturation(Color)
if (arguments.size() == 1 &&
arguments[0]->type == Value::COLOR) {
percentage.append(to_string(static_cast<Color*>(arguments[0])->getSaturation()));
percentage.append("%");
return new Value(new Token(percentage, Token::PERCENTAGE));
}
} else if (function->str == "lightness(") {
// PERCENTAGE lightness(Color)
if (arguments.size() == 1 &&
arguments[0]->type == Value::COLOR) {
percentage.append(to_string(static_cast<Color*>(arguments[0])->getLightness()));
percentage.append("%");
return new Value(new Token(percentage, Token::PERCENTAGE));
}
} else
return NULL;
return NULL;
}
<commit_msg>Variables from ValueProcessor::variables are cloned before sending them through processConstant so they don't get deleted.<commit_after>#include "ValueProcessor.h"
#include <sstream>
#include <iostream>
template <class T>
inline std::string to_string (const T& t)
{
std::stringstream ss;
ss << t;
return ss.str();
}
ValueProcessor::ValueProcessor() {}
ValueProcessor::~ValueProcessor() {}
TokenList* ValueProcessor::processValue(TokenList* value) {
TokenList newvalue;
Value* v;
std::cout << *value->toString() << endl;
while (value->size() > 0) {
v = processStatement(value);
if (v != NULL) {
if (newvalue.size() > 0)
newvalue.push(new Token(" ", Token::WHITESPACE));
newvalue.push(v->getToken()->clone());
delete v;
} else if (value->size() > 0) {
if (value->front()->type == Token::ATKEYWORD &&
variables.count(value->front()->str)) {
newvalue.push(variables[value->front()->str]);
delete value->shift();
} else {
if (value->size() > 1) {
TokenList* var = processDeepVariable(value->front(), value->at(1));
if (var != NULL) {
newvalue.push(var);
delete value->shift();
delete value->shift();
} else
newvalue.push(value->shift());
} else
newvalue.push(value->shift());
}
}
}
value->push(&newvalue);
return value;
}
void ValueProcessor::putVariable(string key, TokenList* value) {
variables[key] = value;
}
Value* ValueProcessor::processStatement(TokenList* value) {
Value* op, *v = processConstant(value);
if (v != NULL) {
while ((op = processOperator(value, v)))
v = op;
return v;
} else
return NULL;
}
Value* ValueProcessor::processOperator(TokenList* value, Value* v1,
Token* lastop) {
Value* v2, *tmp;
Token* op;
string operators("+-*/");
while (value->size() > 0 &&
value->front()->type == Token::WHITESPACE) {
delete value->shift();
}
if (value->size() == 0 ||
operators.find(value->front()->str) == string::npos)
return NULL;
if (lastop != NULL &&
operators.find(lastop->str) >
operators.find(value->front()->str)) {
return v1;
}
op = value->shift();
v2 = processConstant(value);
if (v2 == NULL) {
if (value->size() > 0)
throw new ParseException(value->front()->str, "Constant or @-variable");
else
throw new ParseException("end of line", "Constant or @-variable");
}
while ((tmp = processOperator(value, v2, op)))
v2 = tmp;
if (op->str == "+")
v1->add(v2);
else if (op->str == "-")
v1->substract(v2);
else if (op->str == "*")
v1->multiply(v2);
else if (op->str == "/")
v1->divide(v2);
delete v2;
return v1;
}
Value* ValueProcessor::processConstant(TokenList* value) {
Token* token;
Value* ret;
vector<Value*> arguments;
while (value->size() > 0 &&
value->front()->type == Token::WHITESPACE) {
delete value->shift();
}
if (value->size() == 0)
return NULL;
token = value->front();
switch(token->type) {
case Token::HASH:
// generate color from hex value
return new Color(value->shift());
case Token::NUMBER:
case Token::PERCENTAGE:
case Token::DIMENSION:
return new Value(value->shift());
case Token::FUNCTION:
value->shift();
if (value->front()->type != Token::PAREN_CLOSED)
arguments.push_back(processConstant(value));
while (value->front()->str == ",") {
delete value->shift();
arguments.push_back(processConstant(value));
}
if (value->front()->type == Token::PAREN_CLOSED)
delete value->shift();
return processFunction(token, arguments);
case Token::ATKEYWORD:
if (variables.count(token->str)) {
TokenList* var = variables[token->str]->clone();
ret = processConstant(var);
delete var;
delete value->shift();
return ret;
} else
return NULL;
case Token::PAREN_OPEN:
delete value->shift();
ret = processStatement(value);
if (value->front()->type == Token::PAREN_CLOSED)
delete value->shift();
return ret;
default:
if (value->size() > 1) {
TokenList* var = processDeepVariable(token, value->at(1));
if (var != NULL) {
ret = processStatement(var);
if (ret != NULL) {
delete value->shift();
delete value->shift();
return ret;
}
}
}
return NULL;
}
}
TokenList* ValueProcessor::processDeepVariable (Token* token, Token* nexttoken) {
TokenList* var;
string key("@");
if (token->type != Token::OTHER ||
token->str != "@" ||
nexttoken->type != Token::ATKEYWORD ||
!variables.count(nexttoken->str))
return NULL;
var = variables[nexttoken->str];
if (var->size() > 1 || var->front()->type != Token::STRING)
return NULL;
// generate key with '@' + var without quotes
key.append(var->front()->
str.substr(1, var->front()->str.size() - 2));
if (!variables.count(key))
return NULL;
return variables[key];
}
Value* ValueProcessor::processFunction(Token* function,
vector<Value*> arguments) {
Color* color;
string percentage;
if(function->str == "rgb(") {
if (arguments.size() == 3 &&
arguments[0]->type == Value::NUMBER &&
arguments[1]->type == Value::NUMBER &&
arguments[2]->type == Value::NUMBER) {
return new Color(0,0,0);
}
// Color rgb(@red: NUMBER, @green: NUMBER, @blue: NUMBER)
} else if (function->str == "lighten(") {
// Color lighten(Color, PERCENTAGE)
if (arguments.size() == 2 &&
arguments[0]->type == Value::COLOR &&
arguments[1]->type == Value::PERCENTAGE) {
static_cast<Color*>(arguments[0])->lighten(arguments[1]->getPercent());
return arguments[0];
}
} else if (function->str == "darken(") {
// Color darken(Color, PERCENTAGE)
if (arguments.size() == 2 &&
arguments[0]->type == Value::COLOR &&
arguments[1]->type == Value::PERCENTAGE) {
static_cast<Color*>(arguments[0])->darken(arguments[1]->getPercent());
return arguments[0];
}
} else if (function->str == "saturate(") {
// Color saturate(Color, PERCENTAGE)
if (arguments.size() == 2 &&
arguments[0]->type == Value::COLOR &&
arguments[1]->type == Value::PERCENTAGE) {
static_cast<Color*>(arguments[0])->saturate(arguments[1]->getPercent());
return arguments[0];
}
} else if (function->str == "desaturate(") {
// Color desaturate(Color, PERCENTAGE)
if (arguments.size() == 2 &&
arguments[0]->type == Value::COLOR &&
arguments[1]->type == Value::PERCENTAGE) {
static_cast<Color*>(arguments[0])->desaturate(arguments[1]->getPercent());
return arguments[0];
}
} else if (function->str == "fadein(") {
// Color fadein(Color, PERCENTAGE)
if (arguments.size() == 2 &&
arguments[0]->type == Value::COLOR &&
arguments[1]->type == Value::PERCENTAGE) {
static_cast<Color*>(arguments[0])->fadein(arguments[1]->getPercent());
return arguments[0];
}
} else if (function->str == "fadeout(") {
// Color fadeout(Color, PERCENTAGE)
if (arguments.size() == 2 &&
arguments[0]->type == Value::COLOR &&
arguments[1]->type == Value::PERCENTAGE) {
static_cast<Color*>(arguments[0])->fadeout(arguments[1]->getPercent());
return arguments[0];
}
} else if (function->str == "spin(") {
// Color fadein(Color, PERCENTAGE)
if (arguments.size() == 2 &&
arguments[0]->type == Value::COLOR &&
arguments[1]->type == Value::PERCENTAGE) {
static_cast<Color*>(arguments[0])->spin(arguments[1]->getPercent());
return arguments[0];
}
} else if (function->str == "hsl(") {
// Color hsl(PERCENTAGE, PERCENTAGE, PERCENTAGE)
if (arguments.size() == 3 &&
arguments[0]->type == Value::PERCENTAGE &&
arguments[1]->type == Value::PERCENTAGE &&
arguments[2]->type == Value::PERCENTAGE) {
color = new Color(0,0,0);
color->setHSL(arguments[0]->getPercent(),
arguments[1]->getPercent(),
arguments[2]->getPercent());
return color;
}
} else if (function->str == "hue(") {
// PERCENTAGE hue(Color)
if (arguments.size() == 1 &&
arguments[0]->type == Value::COLOR) {
percentage.append(to_string(static_cast<Color*>(arguments[0])->getHue()));
percentage.append("%");
return new Value(new Token(percentage, Token::PERCENTAGE));
}
} else if (function->str == "saturation(") {
// PERCENTAGE saturation(Color)
if (arguments.size() == 1 &&
arguments[0]->type == Value::COLOR) {
percentage.append(to_string(static_cast<Color*>(arguments[0])->getSaturation()));
percentage.append("%");
return new Value(new Token(percentage, Token::PERCENTAGE));
}
} else if (function->str == "lightness(") {
// PERCENTAGE lightness(Color)
if (arguments.size() == 1 &&
arguments[0]->type == Value::COLOR) {
percentage.append(to_string(static_cast<Color*>(arguments[0])->getLightness()));
percentage.append("%");
return new Value(new Token(percentage, Token::PERCENTAGE));
}
} else
return NULL;
return NULL;
}
<|endoftext|>
|
<commit_before>#include "VehicleGLWidget.h"
#include <QKeyEvent>
#include <cmath>
// All values are half-size.
const int VEHICLE_LENGTH = 30;
const int VEHICLE_WIDTH = 15;
const int ARENA_SIZE = 500;
const int WALL_SIZE = 10;
VehicleGLWidget::VehicleGLWidget(QWidget* const parent) :
QGLWidget(QGLFormat(QGL::SampleBuffers), parent),
timer(this)
{
setFocusPolicy(Qt::ClickFocus);
connect(&timer, SIGNAL(timeout(const float&)), this, SLOT(tick(const float&)));
connect(&timer, SIGNAL(timeout(const float&)), this, SLOT(updateGL()));
timer.startOnShow(this);
}
void VehicleGLWidget::initializeGL()
{
qglClearColor(Qt::black);
}
void VehicleGLWidget::tick(const float& elapsed)
{
float accel = 0;
if (pad.accelerator && pad.brake) {
accel = -125;
} else if (pad.accelerator) {
accel = 250;
} else if (abs(car.velocity) > 10) {
const float dir = car.velocity > 0 ? -1 : 1;
const float friction = pad.brake ? 1500 : 50;
accel = dir * friction;
} else {
car.velocity = 0;
}
if (pad.left && !pad.right) {
car.angle += M_PI * elapsed;
}
if (pad.right && !pad.left) {
car.angle -= M_PI * elapsed;
}
float x = elapsed * cos(car.angle) * (.5 * accel * elapsed + car.velocity) + car.pos.x();
float y = elapsed * sin(car.angle) * (.5 * accel * elapsed + car.velocity) + car.pos.y();
car.velocity += accel * elapsed;
car.pos.setX(x);
car.pos.setY(y);
const int range = ARENA_SIZE - VEHICLE_WIDTH;
{
const double diff = abs(x) - range;
if (diff > 0) {
car.velocity *= -1;
if (x > 0) {
// X is positive; head negative
x = range - diff;
} else {
// X is negative; head positive
x = -range + diff;
}
}
car.pos.setX(x);
}
{
const double diff = abs(y) - range;
if (diff > 0) {
car.velocity *= -1;
if (y > 0) {
// Y is positive; head negative
y = range - diff;
} else {
// Y is negative; head positive
y = -range + diff;
}
}
car.pos.setY(y);
}
}
void drawQuad(float left, float right, float bottom, float top)
{
glVertex2f(right, bottom);
glVertex2f(right, top);
glVertex2f(left, top);
glVertex2f(left, bottom);
}
void drawQuad(float width, float height)
{
drawQuad(-width, width, height, -height);
}
void VehicleGLWidget::paintGL()
{
glClear(GL_COLOR_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
// Render walls
glBegin(GL_QUADS);
glColor3ub(0xa3, 0xa5, 0x9f);
drawQuad(ARENA_SIZE+WALL_SIZE, ARENA_SIZE+WALL_SIZE);
glColor3ub(75, 54, 33);
drawQuad(ARENA_SIZE, ARENA_SIZE);
glEnd();
// Render car
glTranslatef(car.pos.x(), car.pos.y(), car.pos.z());
glRotatef(car.angle * 180 / M_PI, 0, 0, 1);
glBegin(GL_QUADS);
// Body
glColor3ub(0, 0x5b, 0xa9);
drawQuad(VEHICLE_LENGTH, VEHICLE_WIDTH);
// Windshields
glColor3ub(35, 35, 35);
drawQuad(
-VEHICLE_LENGTH + 10,
VEHICLE_LENGTH / 3,
-VEHICLE_WIDTH + 2,
VEHICLE_WIDTH - 2
);
// Front lights
glColor3f(1, 1, .2);
drawQuad(
VEHICLE_LENGTH,
VEHICLE_LENGTH - 3,
-VEHICLE_WIDTH,
VEHICLE_WIDTH
);
glColor3ub(0, 0x5b, 0xa9);
drawQuad(
VEHICLE_LENGTH,
VEHICLE_LENGTH - 3,
-VEHICLE_WIDTH + 5,
VEHICLE_WIDTH - 5
);
// Rear lights
glColor3f(.7, 0, 0);
drawQuad(
-VEHICLE_LENGTH,
-VEHICLE_LENGTH + 2,
-VEHICLE_WIDTH,
VEHICLE_WIDTH
);
glColor3ub(0, 0x5b, 0xa9);
drawQuad(
-VEHICLE_LENGTH,
-VEHICLE_LENGTH + 2,
-VEHICLE_WIDTH + 7,
VEHICLE_WIDTH - 7
);
// Top
glColor3ub(0, 0x5b, 0xa9);
drawQuad(
-VEHICLE_LENGTH / 2 + 2,
0,
-VEHICLE_WIDTH + 4,
VEHICLE_WIDTH - 4
);
glEnd();
}
void VehicleGLWidget::keyPressEvent(QKeyEvent* event)
{
switch (event->key()) {
case Qt::Key_Space:
car.pos = QVector3D(0, 0, 0);
car.velocity = 0;
car.angle = 0;
break;
case Qt::Key_W: pad.accelerator = true; break;
case Qt::Key_S: pad.brake = true; break;
case Qt::Key_A: pad.left = true; break;
case Qt::Key_D: pad.right = true; break;
default:
QGLWidget::keyPressEvent(event);
}
}
void VehicleGLWidget::keyReleaseEvent(QKeyEvent* event)
{
switch (event->key()) {
case Qt::Key_W: pad.accelerator = false; break;
case Qt::Key_S: pad.brake = false; break;
case Qt::Key_A: pad.left = false; break;
case Qt::Key_D: pad.right = false; break;
default:
QGLWidget::keyReleaseEvent(event);
}
}
void VehicleGLWidget::resizeGL(int width, int height)
{
int side = qMin(width, height);
glViewport((width - side) / 2, (height - side) / 2, side, side);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(
-ARENA_SIZE - WALL_SIZE, ARENA_SIZE + WALL_SIZE,
-ARENA_SIZE - WALL_SIZE, ARENA_SIZE + WALL_SIZE,
-100, 100);
glMatrixMode(GL_MODELVIEW);
}
<commit_msg>Brake lights now operational<commit_after>#include "VehicleGLWidget.h"
#include <QKeyEvent>
#include <cmath>
// All values are half-size.
const int VEHICLE_LENGTH = 30;
const int VEHICLE_WIDTH = 15;
const int ARENA_SIZE = 500;
const int WALL_SIZE = 10;
VehicleGLWidget::VehicleGLWidget(QWidget* const parent) :
QGLWidget(QGLFormat(QGL::SampleBuffers), parent),
timer(this)
{
setFocusPolicy(Qt::ClickFocus);
connect(&timer, SIGNAL(timeout(const float&)), this, SLOT(tick(const float&)));
connect(&timer, SIGNAL(timeout(const float&)), this, SLOT(updateGL()));
timer.startOnShow(this);
}
void VehicleGLWidget::initializeGL()
{
qglClearColor(Qt::black);
}
void VehicleGLWidget::tick(const float& elapsed)
{
float accel = 0;
if (pad.accelerator && pad.brake) {
accel = -125;
} else if (pad.accelerator) {
accel = 250;
} else if (abs(car.velocity) > 10) {
const float dir = car.velocity > 0 ? -1 : 1;
const float friction = pad.brake ? 1500 : 50;
accel = dir * friction;
} else {
car.velocity = 0;
}
if (pad.left && !pad.right) {
car.angle += M_PI * elapsed;
}
if (pad.right && !pad.left) {
car.angle -= M_PI * elapsed;
}
float x = elapsed * cos(car.angle) * (.5 * accel * elapsed + car.velocity) + car.pos.x();
float y = elapsed * sin(car.angle) * (.5 * accel * elapsed + car.velocity) + car.pos.y();
car.velocity += accel * elapsed;
car.pos.setX(x);
car.pos.setY(y);
const int range = ARENA_SIZE - VEHICLE_WIDTH;
{
const double diff = abs(x) - range;
if (diff > 0) {
car.velocity *= -1;
if (x > 0) {
// X is positive; head negative
x = range - diff;
} else {
// X is negative; head positive
x = -range + diff;
}
}
car.pos.setX(x);
}
{
const double diff = abs(y) - range;
if (diff > 0) {
car.velocity *= -1;
if (y > 0) {
// Y is positive; head negative
y = range - diff;
} else {
// Y is negative; head positive
y = -range + diff;
}
}
car.pos.setY(y);
}
}
void drawQuad(float left, float right, float bottom, float top)
{
glVertex2f(right, bottom);
glVertex2f(right, top);
glVertex2f(left, top);
glVertex2f(left, bottom);
}
void drawQuad(float width, float height)
{
drawQuad(-width, width, height, -height);
}
void VehicleGLWidget::paintGL()
{
glClear(GL_COLOR_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
// Render walls
glBegin(GL_QUADS);
glColor3ub(0xa3, 0xa5, 0x9f);
drawQuad(ARENA_SIZE+WALL_SIZE, ARENA_SIZE+WALL_SIZE);
glColor3ub(75, 54, 33);
drawQuad(ARENA_SIZE, ARENA_SIZE);
glEnd();
// Render car
glTranslatef(car.pos.x(), car.pos.y(), car.pos.z());
glRotatef(car.angle * 180 / M_PI, 0, 0, 1);
glBegin(GL_QUADS);
// Body
glColor3ub(0, 0x5b, 0xa9);
drawQuad(VEHICLE_LENGTH, VEHICLE_WIDTH);
// Windshields
glColor3ub(35, 35, 35);
drawQuad(
-VEHICLE_LENGTH + 10,
VEHICLE_LENGTH / 3,
-VEHICLE_WIDTH + 2,
VEHICLE_WIDTH - 2
);
// Front lights
glColor3f(1, 1, .2);
drawQuad(
VEHICLE_LENGTH,
VEHICLE_LENGTH - 3,
-VEHICLE_WIDTH,
VEHICLE_WIDTH
);
glColor3ub(0, 0x5b, 0xa9);
drawQuad(
VEHICLE_LENGTH,
VEHICLE_LENGTH - 3,
-VEHICLE_WIDTH + 5,
VEHICLE_WIDTH - 5
);
// Rear lights
if (pad.brake) {
glColor3f(1, .2, .2);
} else {
glColor3f(.7, 0, 0);
}
drawQuad(
-VEHICLE_LENGTH,
-VEHICLE_LENGTH + 2,
-VEHICLE_WIDTH,
VEHICLE_WIDTH
);
glColor3ub(0, 0x5b, 0xa9);
drawQuad(
-VEHICLE_LENGTH,
-VEHICLE_LENGTH + 2,
-VEHICLE_WIDTH + 7,
VEHICLE_WIDTH - 7
);
// Top
glColor3ub(0, 0x5b, 0xa9);
drawQuad(
-VEHICLE_LENGTH / 2 + 2,
0,
-VEHICLE_WIDTH + 4,
VEHICLE_WIDTH - 4
);
glEnd();
}
void VehicleGLWidget::keyPressEvent(QKeyEvent* event)
{
switch (event->key()) {
case Qt::Key_Space:
car.pos = QVector3D(0, 0, 0);
car.velocity = 0;
car.angle = 0;
break;
case Qt::Key_W: pad.accelerator = true; break;
case Qt::Key_S: pad.brake = true; break;
case Qt::Key_A: pad.left = true; break;
case Qt::Key_D: pad.right = true; break;
default:
QGLWidget::keyPressEvent(event);
}
}
void VehicleGLWidget::keyReleaseEvent(QKeyEvent* event)
{
switch (event->key()) {
case Qt::Key_W: pad.accelerator = false; break;
case Qt::Key_S: pad.brake = false; break;
case Qt::Key_A: pad.left = false; break;
case Qt::Key_D: pad.right = false; break;
default:
QGLWidget::keyReleaseEvent(event);
}
}
void VehicleGLWidget::resizeGL(int width, int height)
{
int side = qMin(width, height);
glViewport((width - side) / 2, (height - side) / 2, side, side);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(
-ARENA_SIZE - WALL_SIZE, ARENA_SIZE + WALL_SIZE,
-ARENA_SIZE - WALL_SIZE, ARENA_SIZE + WALL_SIZE,
-100, 100);
glMatrixMode(GL_MODELVIEW);
}
<|endoftext|>
|
<commit_before>// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_GDT_OPERATORS_WEIGHTED_L2_HH
#define DUNE_GDT_OPERATORS_WEIGHTED_L2_HH
#include <type_traits>
#include <dune/stuff/functions/interfaces.hh>
#include <dune/stuff/grid/layers.hh>
#include <dune/stuff/la/container.hh>
#include <dune/gdt/localevaluation/product.hh>
#include <dune/gdt/localoperator/integrals.hh>
#include <dune/gdt/operators/default.hh>
#include <dune/gdt/spaces/interface.hh>
namespace Dune {
namespace GDT {
// //////////////////////////// //
// WeightedL2LocalizableProduct //
// //////////////////////////// //
template <class WeightFunctionType, class GridView, class Range, class Source = Range,
class Field = typename Range::RangeFieldType>
class WeightedL2LocalizableProduct : public LocalizableProductDefault<GridView, Range, Source, Field>
{
typedef LocalizableProductDefault<GridView, Range, Source, Field> BaseType;
typedef LocalVolumeIntegralOperator<LocalEvaluation::Product<WeightFunctionType>> LocalWeightedL2OperatorType;
public:
template <class... Args>
WeightedL2LocalizableProduct(const WeightFunctionType& weight, Args&&... args)
: BaseType(std::forward<Args>(args)...)
, local_weighted_l2_operator_(weight)
{
this->add(local_weighted_l2_operator_);
}
template <class... Args>
WeightedL2LocalizableProduct(const size_t over_integrate, const WeightFunctionType& weight, Args&&... args)
: BaseType(std::forward<Args>(args)...)
, local_weighted_l2_operator_(over_integrate, weight)
{
this->add(local_weighted_l2_operator_);
}
private:
const LocalWeightedL2OperatorType local_weighted_l2_operator_;
}; // class WeightedL2LocalizableProduct
// //////////////////////////////////// //
// make_weighted_l2_localizable_product //
// //////////////////////////////////// //
/**
* \sa WeightedL2LocalizableProduct
*/
template <class WeightFunctionType, class GridViewType, class RangeType, class SourceType>
typename std::enable_if<Stuff::is_localizable_function<WeightFunctionType>::value
&& Stuff::Grid::is_grid_layer<GridViewType>::value
&& Stuff::is_localizable_function<RangeType>::value
&& Stuff::is_localizable_function<SourceType>::value,
std::unique_ptr<WeightedL2LocalizableProduct<WeightFunctionType, GridViewType, RangeType,
SourceType>>>::type
make_weighted_l2_localizable_product(const WeightFunctionType& weight, const GridViewType& grid_view,
const RangeType& range, const SourceType& source, const size_t over_integrate = 0)
{
return DSC::make_unique<WeightedL2LocalizableProduct<WeightFunctionType, GridViewType, RangeType, SourceType>>(
over_integrate, weight, grid_view, range, source);
}
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_OPERATORS_WEIGHTED_L2_HH
<commit_msg>[operators.weighted-l2] add WeightedL2MatrixOperator and factory<commit_after>// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_GDT_OPERATORS_WEIGHTED_L2_HH
#define DUNE_GDT_OPERATORS_WEIGHTED_L2_HH
#include <type_traits>
#include <dune/stuff/functions/interfaces.hh>
#include <dune/stuff/grid/layers.hh>
#include <dune/stuff/la/container.hh>
#include <dune/gdt/localevaluation/product.hh>
#include <dune/gdt/localoperator/integrals.hh>
#include <dune/gdt/operators/default.hh>
#include <dune/gdt/spaces/interface.hh>
namespace Dune {
namespace GDT {
// //////////////////////////// //
// WeightedL2LocalizableProduct //
// //////////////////////////// //
template <class WeightFunctionType, class GridView, class Range, class Source = Range,
class Field = typename Range::RangeFieldType>
class WeightedL2LocalizableProduct : public LocalizableProductDefault<GridView, Range, Source, Field>
{
typedef LocalizableProductDefault<GridView, Range, Source, Field> BaseType;
typedef LocalVolumeIntegralOperator<LocalEvaluation::Product<WeightFunctionType>> LocalWeightedL2OperatorType;
public:
template <class... Args>
WeightedL2LocalizableProduct(const WeightFunctionType& weight, Args&&... args)
: BaseType(std::forward<Args>(args)...)
, local_weighted_l2_operator_(weight)
{
this->add(local_weighted_l2_operator_);
}
template <class... Args>
WeightedL2LocalizableProduct(const size_t over_integrate, const WeightFunctionType& weight, Args&&... args)
: BaseType(std::forward<Args>(args)...)
, local_weighted_l2_operator_(over_integrate, weight)
{
this->add(local_weighted_l2_operator_);
}
private:
const LocalWeightedL2OperatorType local_weighted_l2_operator_;
}; // class WeightedL2LocalizableProduct
// //////////////////////////////////// //
// make_weighted_l2_localizable_product //
// //////////////////////////////////// //
/**
* \sa WeightedL2LocalizableProduct
*/
template <class WeightFunctionType, class GridViewType, class RangeType, class SourceType>
typename std::enable_if<Stuff::is_localizable_function<WeightFunctionType>::value
&& Stuff::Grid::is_grid_layer<GridViewType>::value
&& Stuff::is_localizable_function<RangeType>::value
&& Stuff::is_localizable_function<SourceType>::value,
std::unique_ptr<WeightedL2LocalizableProduct<WeightFunctionType, GridViewType, RangeType,
SourceType>>>::type
make_weighted_l2_localizable_product(const WeightFunctionType& weight, const GridViewType& grid_view,
const RangeType& range, const SourceType& source, const size_t over_integrate = 0)
{
return DSC::make_unique<WeightedL2LocalizableProduct<WeightFunctionType, GridViewType, RangeType, SourceType>>(
over_integrate, weight, grid_view, range, source);
}
// //////////////////////// //
// WeightedL2MatrixOperator //
// //////////////////////// //
template <class WeightFunctionType, class RangeSpace,
class Matrix = typename Stuff::LA::Container<typename RangeSpace::RangeFieldType>::MatrixType,
class GridView = typename RangeSpace::GridViewType, class SourceSpace = RangeSpace,
class Field = typename RangeSpace::RangeFieldType>
class WeightedL2MatrixOperator
: public MatrixOperatorDefault<Matrix, RangeSpace, GridView, SourceSpace, Field, ChoosePattern::volume>
{
typedef MatrixOperatorDefault<Matrix, RangeSpace, GridView, SourceSpace, Field, ChoosePattern::volume> BaseType;
typedef LocalVolumeIntegralOperator<LocalEvaluation::Product<WeightFunctionType>> LocalWeightedL2OperatorType;
public:
template <class... Args>
explicit WeightedL2MatrixOperator(const WeightFunctionType& weight, Args&&... args)
: BaseType(std::forward<Args>(args)...)
, local_weighted_l2_operator_(weight)
{
this->add(local_weighted_l2_operator_);
}
template <class... Args>
explicit WeightedL2MatrixOperator(const size_t over_integrate, const WeightFunctionType& weight, Args&&... args)
: BaseType(std::forward<Args>(args)...)
, local_weighted_l2_operator_(over_integrate, weight)
{
this->add(local_weighted_l2_operator_);
}
private:
const LocalWeightedL2OperatorType local_weighted_l2_operator_;
}; // class WeightedL2MatrixOperator
// //////////////////////////////// //
// make_weighted_l2_matrix_operator //
// //////////////////////////////// //
// without matrix
/**
* \brief Creates a weighted L2 matrix operator (MatrixType has to be supllied, a matrix is created automatically,
* source and range space are given by space, grid_view of the space is used).
* \note MatrixType has to be supplied, i.e., use like
\code
auto op = make_weighted_l2_matrix_operator< MatrixType >(weight, space);
\endcode
*/
template <class MatrixType, class WeightFunctionType, class SpaceType>
typename std::enable_if<Stuff::LA::is_matrix<MatrixType>::value
&& Stuff::is_localizable_function<WeightFunctionType>::value && is_space<SpaceType>::value,
std::unique_ptr<WeightedL2MatrixOperator<WeightFunctionType, SpaceType, MatrixType>>>::type
make_weighted_l2_matrix_operator(const WeightFunctionType& weight, const SpaceType& space,
const size_t over_integrate = 0)
{
return DSC::make_unique<WeightedL2MatrixOperator<WeightFunctionType, SpaceType, MatrixType>>(
over_integrate, weight, space);
}
/**
* \brief Creates a weighted L2 matrix operator (MatrixType has to be supllied, a matrix is created automatically,
* source and range space are given by space).
* \note MatrixType has to be supplied, i.e., use like
\code
auto op = make_weighted_l2_matrix_operator< MatrixType >(weight, space, grid_view);
\endcode
*/
template <class MatrixType, class WeightFunctionType, class SpaceType, class GridViewType>
typename std::
enable_if<Stuff::LA::is_matrix<MatrixType>::value && Stuff::is_localizable_function<WeightFunctionType>::value
&& is_space<SpaceType>::value && Stuff::Grid::is_grid_layer<GridViewType>::value,
std::unique_ptr<WeightedL2MatrixOperator<WeightFunctionType, SpaceType, MatrixType, GridViewType>>>::type
make_weighted_l2_matrix_operator(const WeightFunctionType& weight, const SpaceType& space,
const GridViewType& grid_view, const size_t over_integrate = 0)
{
return DSC::make_unique<WeightedL2MatrixOperator<WeightFunctionType, SpaceType, MatrixType, GridViewType>>(
over_integrate, weight, space, grid_view);
}
/**
* \brief Creates a weighted L2 matrix operator (MatrixType has to be supllied, a matrix is created automatically).
* \note MatrixType has to be supplied, i.e., use like
\code
auto op = make_weighted_l2_matrix_operator< MatrixType >(weight, range_space, source_space, grid_view);
\endcode
*/
template <class MatrixType, class WeightFunctionType, class RangeSpaceType, class SourceSpaceType, class GridViewType>
typename std::enable_if<Stuff::LA::is_matrix<MatrixType>::value
&& Stuff::is_localizable_function<WeightFunctionType>::value
&& is_space<RangeSpaceType>::value && is_space<SourceSpaceType>::value
&& Stuff::Grid::is_grid_layer<GridViewType>::value,
std::unique_ptr<WeightedL2MatrixOperator<WeightFunctionType, RangeSpaceType, MatrixType,
GridViewType, SourceSpaceType>>>::type
make_weighted_l2_matrix_operator(const WeightFunctionType& weight, const RangeSpaceType& range_space,
const SourceSpaceType& source_space, const GridViewType& grid_view,
const size_t over_integrate = 0)
{
return DSC::make_unique<WeightedL2MatrixOperator<WeightFunctionType,
RangeSpaceType,
MatrixType,
GridViewType,
SourceSpaceType>>(
over_integrate, weight, range_space, source_space, grid_view);
}
// with matrix
/**
* \brief Creates a weighted L2 matrix operator (source and range space are given by space, grid_view of the space is
* used).
*/
template <class WeightFunctionType, class MatrixType, class SpaceType>
typename std::enable_if<Stuff::is_localizable_function<WeightFunctionType>::value
&& Stuff::LA::is_matrix<MatrixType>::value && is_space<SpaceType>::value,
std::unique_ptr<WeightedL2MatrixOperator<WeightFunctionType, SpaceType, MatrixType>>>::type
make_weighted_l2_matrix_operator(const WeightFunctionType& weight, MatrixType& matrix, const SpaceType& space,
const size_t over_integrate = 0)
{
return DSC::make_unique<WeightedL2MatrixOperator<WeightFunctionType, SpaceType, MatrixType>>(
over_integrate, weight, matrix, space);
}
/**
* \brief Creates a weighted L2 matrix operator (source and range space are given by space).
*/
template <class WeightFunctionType, class MatrixType, class SpaceType, class GridViewType>
typename std::
enable_if<Stuff::is_localizable_function<WeightFunctionType>::value && Stuff::LA::is_matrix<MatrixType>::value
&& is_space<SpaceType>::value && Stuff::Grid::is_grid_layer<GridViewType>::value,
std::unique_ptr<WeightedL2MatrixOperator<WeightFunctionType, SpaceType, MatrixType, GridViewType>>>::type
make_weighted_l2_matrix_operator(const WeightFunctionType& weight, MatrixType& matrix, const SpaceType& space,
const GridViewType& grid_view, const size_t over_integrate = 0)
{
return DSC::make_unique<WeightedL2MatrixOperator<WeightFunctionType, SpaceType, MatrixType, GridViewType>>(
over_integrate, weight, matrix, space, grid_view);
}
/**
* \brief Creates a weighted L2 matrix operator.
*/
template <class WeightFunctionType, class MatrixType, class RangeSpaceType, class SourceSpaceType, class GridViewType>
typename std::enable_if<Stuff::is_localizable_function<WeightFunctionType>::value
&& Stuff::LA::is_matrix<MatrixType>::value && is_space<RangeSpaceType>::value
&& is_space<SourceSpaceType>::value && Stuff::Grid::is_grid_layer<GridViewType>::value,
std::unique_ptr<WeightedL2MatrixOperator<WeightFunctionType, RangeSpaceType, MatrixType,
GridViewType, SourceSpaceType>>>::type
make_weighted_l2_matrix_operator(const WeightFunctionType& weight, MatrixType& matrix,
const RangeSpaceType& range_space, const SourceSpaceType& source_space,
const GridViewType& grid_view, const size_t over_integrate = 0)
{
return DSC::make_unique<WeightedL2MatrixOperator<WeightFunctionType,
RangeSpaceType,
MatrixType,
GridViewType,
SourceSpaceType>>(
over_integrate, weight, matrix, range_space, source_space, grid_view);
}
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_OPERATORS_WEIGHTED_L2_HH
<|endoftext|>
|
<commit_before>#include "universe.h"
#include "core/blob.h"
#include "core/crc32.h"
#include "core/matrix.h"
#include "core/json_serializer.h"
namespace Lumix
{
static const int RESERVED_ENTITIES_COUNT = 5000;
Universe::~Universe()
{
}
Universe::Universe(IAllocator& allocator)
: m_allocator(allocator)
, m_name_to_id_map(m_allocator)
, m_id_to_name_map(m_allocator)
, m_transformations(m_allocator)
, m_component_destroyed(m_allocator)
, m_entity_created(m_allocator)
, m_entity_destroyed(m_allocator)
, m_entity_moved(m_allocator)
, m_id_map(m_allocator)
, m_first_free_slot(-1)
{
m_transformations.reserve(RESERVED_ENTITIES_COUNT);
m_id_map.reserve(RESERVED_ENTITIES_COUNT);
}
const Vec3& Universe::getPosition(Entity entity) const
{
return m_transformations[m_id_map[entity]].position;
}
const Quat& Universe::getRotation(Entity entity) const
{
return m_transformations[m_id_map[entity]].rotation;
}
void Universe::setRotation(Entity entity, const Quat& rot)
{
m_transformations[m_id_map[entity]].rotation = rot;
entityTransformed().invoke(entity);
}
void Universe::setRotation(Entity entity, float x, float y, float z, float w)
{
m_transformations[m_id_map[entity]].rotation.set(x, y, z, w);
entityTransformed().invoke(entity);
}
bool Universe::hasEntity(Entity entity) const
{
return entity >= 0 && entity < m_id_map.size() && m_id_map[entity] >= 0;
}
void Universe::setMatrix(Entity entity, const Matrix& mtx)
{
Quat rot;
mtx.getRotation(rot);
m_transformations[m_id_map[entity]].position = mtx.getTranslation();
m_transformations[m_id_map[entity]].rotation = rot;
entityTransformed().invoke(entity);
}
Matrix Universe::getPositionAndRotation(Entity entity) const
{
Matrix mtx;
auto& transform = m_transformations[m_id_map[entity]];
transform.rotation.toMatrix(mtx);
mtx.setTranslation(transform.position);
return mtx;
}
Matrix Universe::getMatrix(Entity entity) const
{
Matrix mtx;
auto& transform = m_transformations[m_id_map[entity]];
transform.rotation.toMatrix(mtx);
mtx.setTranslation(transform.position);
mtx.multiply3x3(transform.scale);
return mtx;
}
void Universe::setPosition(Entity entity, float x, float y, float z)
{
auto& transform = m_transformations[m_id_map[entity]];
transform.position.set(x, y, z);
entityTransformed().invoke(entity);
}
void Universe::setPosition(Entity entity, const Vec3& pos)
{
auto& transform = m_transformations[m_id_map[entity]];
transform.position = pos;
entityTransformed().invoke(entity);
}
void Universe::setEntityName(Entity entity, const char* name)
{
int name_index = m_id_to_name_map.find(entity);
if (name_index >= 0)
{
uint32_t hash = crc32(m_id_to_name_map.at(name_index).c_str());
m_name_to_id_map.erase(hash);
m_id_to_name_map.eraseAt(name_index);
}
if (name && name[0] != '\0')
{
m_name_to_id_map.insert(crc32(name), entity);
m_id_to_name_map.insert(entity, string(name, getAllocator()));
}
}
const char* Universe::getEntityName(Entity entity) const
{
int name_index = m_id_to_name_map.find(entity);
return name_index < 0 ? "" : m_id_to_name_map.at(name_index).c_str();
}
void Universe::createEntity(Entity entity)
{
ASSERT(entity >= 0);
int id = m_first_free_slot;
int prev_id = -1;
while (id >= 0 && id != entity)
{
prev_id = id;
id = -m_id_map[id];
}
ASSERT(id == entity);
if (prev_id == -1)
{
m_first_free_slot = -m_id_map[entity];
}
else
{
m_id_map[prev_id] = m_id_map[entity];
}
m_id_map[entity] = m_transformations.size();
Transformation& trans = m_transformations.pushEmpty();
trans.position.set(0, 0, 0);
trans.rotation.set(0, 0, 0, 1);
trans.scale = 1;
trans.id = entity;
m_entity_created.invoke(entity);
}
Entity Universe::createEntity(const Vec3& position, const Quat& rotation)
{
int global_id = 0;
if (m_first_free_slot >= 0)
{
global_id = m_first_free_slot;
m_first_free_slot = -m_id_map[m_first_free_slot];
m_id_map[global_id] = m_transformations.size();
}
else
{
global_id = m_id_map.size();
m_id_map.push(m_transformations.size());
}
Transformation& trans = m_transformations.pushEmpty();
trans.position = position;
trans.rotation = rotation;
trans.scale = 1;
trans.id = global_id;
m_entity_created.invoke(global_id);
return global_id;
}
void Universe::destroyEntity(Entity entity)
{
if (entity < 0 || m_id_map[entity] < 0) return;
int last_item_id = m_transformations.back().id;
m_id_map[last_item_id] = m_id_map[entity];
m_transformations.eraseFast(m_id_map[entity]);
m_id_map[entity] = m_first_free_slot >= 0 ? -m_first_free_slot : INT_MIN;
m_first_free_slot = entity;
m_entity_destroyed.invoke(entity);
}
Entity Universe::getEntityFromDenseIdx(int idx)
{
return m_transformations[idx].id;
}
Entity Universe::getFirstEntity()
{
for (int i = 0; i < m_id_map.size(); ++i)
{
if (m_id_map[i] >= 0)
{
return i;
}
}
return INVALID_ENTITY;
}
Entity Universe::getNextEntity(Entity entity)
{
for (int i = entity + 1; i < m_id_map.size(); ++i)
{
if (m_id_map[i] >= 0)
{
return i;
}
}
return INVALID_ENTITY;
}
void Universe::serialize(OutputBlob& serializer)
{
serializer.write((int32_t)m_transformations.size());
serializer.write(
&m_transformations[0], sizeof(m_transformations[0]) * m_transformations.size());
serializer.write((int32_t)m_id_to_name_map.size());
for (int i = 0, c = m_id_to_name_map.size(); i < c; ++i)
{
serializer.write(m_id_to_name_map.getKey(i));
serializer.writeString(m_id_to_name_map.at(i).c_str());
}
serializer.write(m_first_free_slot);
serializer.write((int32_t)m_id_map.size());
if (!m_id_map.empty())
{
serializer.write(&m_id_map[0], sizeof(m_id_map[0]) * m_id_map.size());
}
}
void Universe::deserialize(InputBlob& serializer)
{
int32_t count;
serializer.read(count);
m_transformations.resize(count);
serializer.read(&m_transformations[0], sizeof(m_transformations[0]) * m_transformations.size());
serializer.read(count);
m_id_to_name_map.clear();
m_name_to_id_map.clear();
for (int i = 0; i < count; ++i)
{
uint32_t key;
char name[50];
serializer.read(key);
serializer.readString(name, sizeof(name));
m_id_to_name_map.insert(key, string(name, m_allocator));
m_name_to_id_map.insert(crc32(name), key);
}
serializer.read(m_first_free_slot);
serializer.read(count);
m_id_map.resize(count);
if (!m_id_map.empty())
{
serializer.read(&m_id_map[0], sizeof(m_id_map[0]) * count);
}
}
void Universe::setScale(Entity entity, float scale)
{
auto& transform = m_transformations[m_id_map[entity]];
transform.scale = scale;
entityTransformed().invoke(entity);
}
float Universe::getScale(Entity entity)
{
auto& transform = m_transformations[m_id_map[entity]];
return transform.scale;
}
void Universe::destroyComponent(Entity entity, uint32_t component_type, IScene* scene, int index)
{
m_component_destroyed.invoke(ComponentUID(entity, component_type, scene, index));
}
void Universe::addComponent(Entity entity, uint32_t component_type, IScene* scene, int index)
{
ComponentUID cmp(entity, component_type, scene, index);
if (m_component_added.isValid())
{
m_component_added.invoke(cmp);
}
}
bool Universe::nameExists(const char* name) const
{
return m_name_to_id_map.find(crc32(name)) != -1;
}
} // !namespace Lumix
<commit_msg>recently created entity does not have the name of the recently deleted entity - #566<commit_after>#include "universe.h"
#include "core/blob.h"
#include "core/crc32.h"
#include "core/matrix.h"
#include "core/json_serializer.h"
namespace Lumix
{
static const int RESERVED_ENTITIES_COUNT = 5000;
Universe::~Universe()
{
}
Universe::Universe(IAllocator& allocator)
: m_allocator(allocator)
, m_name_to_id_map(m_allocator)
, m_id_to_name_map(m_allocator)
, m_transformations(m_allocator)
, m_component_destroyed(m_allocator)
, m_entity_created(m_allocator)
, m_entity_destroyed(m_allocator)
, m_entity_moved(m_allocator)
, m_id_map(m_allocator)
, m_first_free_slot(-1)
{
m_transformations.reserve(RESERVED_ENTITIES_COUNT);
m_id_map.reserve(RESERVED_ENTITIES_COUNT);
}
const Vec3& Universe::getPosition(Entity entity) const
{
return m_transformations[m_id_map[entity]].position;
}
const Quat& Universe::getRotation(Entity entity) const
{
return m_transformations[m_id_map[entity]].rotation;
}
void Universe::setRotation(Entity entity, const Quat& rot)
{
m_transformations[m_id_map[entity]].rotation = rot;
entityTransformed().invoke(entity);
}
void Universe::setRotation(Entity entity, float x, float y, float z, float w)
{
m_transformations[m_id_map[entity]].rotation.set(x, y, z, w);
entityTransformed().invoke(entity);
}
bool Universe::hasEntity(Entity entity) const
{
return entity >= 0 && entity < m_id_map.size() && m_id_map[entity] >= 0;
}
void Universe::setMatrix(Entity entity, const Matrix& mtx)
{
Quat rot;
mtx.getRotation(rot);
m_transformations[m_id_map[entity]].position = mtx.getTranslation();
m_transformations[m_id_map[entity]].rotation = rot;
entityTransformed().invoke(entity);
}
Matrix Universe::getPositionAndRotation(Entity entity) const
{
Matrix mtx;
auto& transform = m_transformations[m_id_map[entity]];
transform.rotation.toMatrix(mtx);
mtx.setTranslation(transform.position);
return mtx;
}
Matrix Universe::getMatrix(Entity entity) const
{
Matrix mtx;
auto& transform = m_transformations[m_id_map[entity]];
transform.rotation.toMatrix(mtx);
mtx.setTranslation(transform.position);
mtx.multiply3x3(transform.scale);
return mtx;
}
void Universe::setPosition(Entity entity, float x, float y, float z)
{
auto& transform = m_transformations[m_id_map[entity]];
transform.position.set(x, y, z);
entityTransformed().invoke(entity);
}
void Universe::setPosition(Entity entity, const Vec3& pos)
{
auto& transform = m_transformations[m_id_map[entity]];
transform.position = pos;
entityTransformed().invoke(entity);
}
void Universe::setEntityName(Entity entity, const char* name)
{
int name_index = m_id_to_name_map.find(entity);
if (name_index >= 0)
{
uint32_t hash = crc32(m_id_to_name_map.at(name_index).c_str());
m_name_to_id_map.erase(hash);
m_id_to_name_map.eraseAt(name_index);
}
if (name && name[0] != '\0')
{
m_name_to_id_map.insert(crc32(name), entity);
m_id_to_name_map.insert(entity, string(name, getAllocator()));
}
}
const char* Universe::getEntityName(Entity entity) const
{
int name_index = m_id_to_name_map.find(entity);
return name_index < 0 ? "" : m_id_to_name_map.at(name_index).c_str();
}
void Universe::createEntity(Entity entity)
{
ASSERT(entity >= 0);
int id = m_first_free_slot;
int prev_id = -1;
while (id >= 0 && id != entity)
{
prev_id = id;
id = -m_id_map[id];
}
ASSERT(id == entity);
if (prev_id == -1)
{
m_first_free_slot = -m_id_map[entity];
}
else
{
m_id_map[prev_id] = m_id_map[entity];
}
m_id_map[entity] = m_transformations.size();
Transformation& trans = m_transformations.pushEmpty();
trans.position.set(0, 0, 0);
trans.rotation.set(0, 0, 0, 1);
trans.scale = 1;
trans.id = entity;
m_entity_created.invoke(entity);
}
Entity Universe::createEntity(const Vec3& position, const Quat& rotation)
{
int global_id = 0;
if (m_first_free_slot >= 0)
{
global_id = m_first_free_slot;
m_first_free_slot = -m_id_map[m_first_free_slot];
m_id_map[global_id] = m_transformations.size();
}
else
{
global_id = m_id_map.size();
m_id_map.push(m_transformations.size());
}
Transformation& trans = m_transformations.pushEmpty();
trans.position = position;
trans.rotation = rotation;
trans.scale = 1;
trans.id = global_id;
m_entity_created.invoke(global_id);
return global_id;
}
void Universe::destroyEntity(Entity entity)
{
if (entity < 0 || m_id_map[entity] < 0) return;
int last_item_id = m_transformations.back().id;
m_id_map[last_item_id] = m_id_map[entity];
m_transformations.eraseFast(m_id_map[entity]);
m_id_map[entity] = m_first_free_slot >= 0 ? -m_first_free_slot : INT_MIN;
int name_index = m_id_to_name_map.find(entity);
if (name_index >= 0)
{
uint32_t name_hash = crc32(m_id_to_name_map.at(name_index).c_str());
m_name_to_id_map.erase(name_hash);
m_id_to_name_map.eraseAt(name_index);
}
m_first_free_slot = entity;
m_entity_destroyed.invoke(entity);
}
Entity Universe::getEntityFromDenseIdx(int idx)
{
return m_transformations[idx].id;
}
Entity Universe::getFirstEntity()
{
for (int i = 0; i < m_id_map.size(); ++i)
{
if (m_id_map[i] >= 0)
{
return i;
}
}
return INVALID_ENTITY;
}
Entity Universe::getNextEntity(Entity entity)
{
for (int i = entity + 1; i < m_id_map.size(); ++i)
{
if (m_id_map[i] >= 0)
{
return i;
}
}
return INVALID_ENTITY;
}
void Universe::serialize(OutputBlob& serializer)
{
serializer.write((int32_t)m_transformations.size());
serializer.write(
&m_transformations[0], sizeof(m_transformations[0]) * m_transformations.size());
serializer.write((int32_t)m_id_to_name_map.size());
for (int i = 0, c = m_id_to_name_map.size(); i < c; ++i)
{
serializer.write(m_id_to_name_map.getKey(i));
serializer.writeString(m_id_to_name_map.at(i).c_str());
}
serializer.write(m_first_free_slot);
serializer.write((int32_t)m_id_map.size());
if (!m_id_map.empty())
{
serializer.write(&m_id_map[0], sizeof(m_id_map[0]) * m_id_map.size());
}
}
void Universe::deserialize(InputBlob& serializer)
{
int32_t count;
serializer.read(count);
m_transformations.resize(count);
serializer.read(&m_transformations[0], sizeof(m_transformations[0]) * m_transformations.size());
serializer.read(count);
m_id_to_name_map.clear();
m_name_to_id_map.clear();
for (int i = 0; i < count; ++i)
{
uint32_t key;
char name[50];
serializer.read(key);
serializer.readString(name, sizeof(name));
m_id_to_name_map.insert(key, string(name, m_allocator));
m_name_to_id_map.insert(crc32(name), key);
}
serializer.read(m_first_free_slot);
serializer.read(count);
m_id_map.resize(count);
if (!m_id_map.empty())
{
serializer.read(&m_id_map[0], sizeof(m_id_map[0]) * count);
}
}
void Universe::setScale(Entity entity, float scale)
{
auto& transform = m_transformations[m_id_map[entity]];
transform.scale = scale;
entityTransformed().invoke(entity);
}
float Universe::getScale(Entity entity)
{
auto& transform = m_transformations[m_id_map[entity]];
return transform.scale;
}
void Universe::destroyComponent(Entity entity, uint32_t component_type, IScene* scene, int index)
{
m_component_destroyed.invoke(ComponentUID(entity, component_type, scene, index));
}
void Universe::addComponent(Entity entity, uint32_t component_type, IScene* scene, int index)
{
ComponentUID cmp(entity, component_type, scene, index);
if (m_component_added.isValid())
{
m_component_added.invoke(cmp);
}
}
bool Universe::nameExists(const char* name) const
{
return m_name_to_id_map.find(crc32(name)) != -1;
}
} // !namespace Lumix
<|endoftext|>
|
<commit_before>#include "common.h"
#include "eventdispatcher_libevent.h"
#include "eventdispatcher_libevent_p.h"
/**
* @class EventDispatcherLibEvent
* @brief The EventDispatcherLibEvent class provides an interface to manage Qt's event queue.
*
* An event dispatcher receives events from the window system and other
* sources. It then sends them to the QCoreApplication or QApplication
* instance for processing and delivery. EventDispatcherLibEvent provides
* fine-grained control over event delivery.
*
* For simple control of event processing use
* QCoreApplication::processEvents().
*
* For finer control of the application's event loop, call
* instance() and call functions on the QAbstractEventDispatcher
* object that is returned.
*
* To use EventDispatcherLibEvent, you must install it with
* QCoreApplication::setEventDispatcher() or QThread::setEventDispatcher()
* before a default event dispatcher has been installed.
* The main event loop is started by calling
* QCoreApplication::exec(), and stopped by calling
* QCoreApplication::exit(). Local event loops can be created using
* QEventLoop.
*
* Programs that perform long operations can call processEvents()
* with a bitwise OR combination of various QEventLoop::ProcessEventsFlag
* values to control which events should be delivered.
*/
/**
* Constructs a new event dispatcher with the given @a parent
*
* @param parent Parent
*/
EventDispatcherLibEvent::EventDispatcherLibEvent(QObject* parent)
: QAbstractEventDispatcher(parent), d_ptr(new EventDispatcherLibEventPrivate(this))
{
}
/**
* Constructs a new event dispatcher with the given configuration @a config and @a parent
*
* @param config Event dispatcher configuration
* @param parent Parent
* @see EventDispatcherLibEventConfig
*/
EventDispatcherLibEvent::EventDispatcherLibEvent(const EventDispatcherLibEventConfig& config, QObject* parent)
: QAbstractEventDispatcher(parent), d_ptr(new EventDispatcherLibEventPrivate(this, config))
{
}
/**
* Destroys the event dispatcher
*/
EventDispatcherLibEvent::~EventDispatcherLibEvent(void)
{
#if QT_VERSION < 0x040600
delete this->d_ptr;
this->d_ptr = 0;
#endif
}
/**
* Retrieve the libevent event_base for this dispatcher
* @return The event_base for this dispatcher
*/
struct event_base* EventDispatcherLibEvent::eventBase() const
{
const Q_D(EventDispatcherLibEvent);
return d->eventBase();
}
/**
* @brief Processes pending events that match @a flags until there are no more events to process
* @param flags
* @return Whether an event has been processed
* @retval true If an event has been processed;
* @retval false If no events have been processed
*
* Processes pending events that match @a flags until there are no
* more events to process. Returns true if an event was processed;
* otherwise returns false.
*
* This function is especially useful if you have a long running
* operation and want to show its progress without allowing user
* input; i.e. by using the QEventLoop::ExcludeUserInputEvents flag.
*
* If the QEventLoop::WaitForMoreEvents flag is set in @a flags, the
* behavior of this function is as follows:
*
* @list
* @li If events are available, this function returns after processing them.
* @li If no events are available, this function will wait until more
* are available and return after processing newly available events.
* @endlist
*
* If the QEventLoop::WaitForMoreEvents flag is not set in @a flags,
* and no events are available, this function will return
* immediately.
*
* @note This function does not process events continuously; it
* returns after all available events are processed.
*
* @see hasPendingEvents()
*/
bool EventDispatcherLibEvent::processEvents(QEventLoop::ProcessEventsFlags flags)
{
Q_D(EventDispatcherLibEvent);
return d->processEvents(flags);
}
/**
* Returns @c true if there is an event waiting; otherwise returns @c false
*
* @return Whether there is an event waiting
*/
bool EventDispatcherLibEvent::hasPendingEvents(void)
{
extern uint qGlobalPostedEventsCount();
return qGlobalPostedEventsCount() > 0;
}
/**
* Registers @a notifier with the event loop
*
* @param notifier Socket notifier to register
* @warning @a notifier must belong to the same thread as the event dispatcher
* @warning Socket notifiers can only be enabled from the thread they belong to
*/
void EventDispatcherLibEvent::registerSocketNotifier(QSocketNotifier* notifier)
{
#ifndef QT_NO_DEBUG
if (notifier->socket() < 0) {
qWarning("QSocketNotifier: Internal error: sockfd < 0");
return;
}
if (notifier->thread() != this->thread() || this->thread() != QThread::currentThread()) {
qWarning("QSocketNotifier: socket notifiers cannot be enabled from another thread");
return;
}
#endif
if (notifier->type() == QSocketNotifier::Exception) {
return;
}
Q_D(EventDispatcherLibEvent);
d->registerSocketNotifier(notifier);
}
/**
* Unregisters @a notifier from the event dispatcher.
*
* @param notifier Socket notifier to unregister
* @warning @a notifier must belong to the same thread as the event dispatcher
* @warning Socket notifiers can only be disabled from the thread they belong to
*/
void EventDispatcherLibEvent::unregisterSocketNotifier(QSocketNotifier* notifier)
{
#ifndef QT_NO_DEBUG
if (notifier->socket() < 0) {
qWarning("QSocketNotifier: Internal error: sockfd < 0");
return;
}
if (notifier->thread() != this->thread() || this->thread() != QThread::currentThread()) {
qWarning("QSocketNotifier: socket notifiers cannot be disabled from another thread");
return;
}
#endif
// Short circuit, we do not support QSocketNotifier::Exception
if (notifier->type() == QSocketNotifier::Exception) {
return;
}
Q_D(EventDispatcherLibEvent);
d->unregisterSocketNotifier(notifier);
}
/**
* Register a timer with the specified @a timerId, @a interval, and @a timerType
* for the given @a object.
*
* @param timerId Timer ID
* @param interval Timer interval (msec); must be greater than 0
* @param timerType Timer type (not available in Qt 4)
* @param object Object for which the timer is registered
* @warning @a object must belong to the same thread as the event dispatcher
* @warning Timers can only be started from the thread the event dispatcher lives in
*/
void EventDispatcherLibEvent::registerTimer(
int timerId,
int interval,
#if QT_VERSION >= 0x050000
Qt::TimerType timerType,
#endif
QObject* object
)
{
#ifndef QT_NO_DEBUG
if (timerId < 1 || interval < 0 || !object) {
qWarning("%s: invalid arguments", Q_FUNC_INFO);
return;
}
if (object->thread() != this->thread() && this->thread() != QThread::currentThread()) {
qWarning("%s: timers cannot be started from another thread", Q_FUNC_INFO);
return;
}
#endif
Qt::TimerType type;
#if QT_VERSION >= 0x050000
type = timerType;
#else
type = Qt::CoarseTimer;
#endif
Q_D(EventDispatcherLibEvent);
d->registerTimer(timerId, interval, type, object);
}
/**
* Unregisters the timer
*
* @param timerId ID of the timer
* @return Whether the timer has been unregistered
* @warning Timers can only be stopped from the same thread as the event dispatcher lives in
*/
bool EventDispatcherLibEvent::unregisterTimer(int timerId)
{
#ifndef QT_NO_DEBUG
if (timerId < 1) {
qWarning("%s: invalid arguments", Q_FUNC_INFO);
return false;
}
if (this->thread() != QThread::currentThread()) {
qWarning("%s: timers cannot be stopped from another thread", Q_FUNC_INFO);
return false;
}
#endif
Q_D(EventDispatcherLibEvent);
return d->unregisterTimer(timerId);
}
/**
* Unregisters all timers for the given @a object
*
* @param object Object
* @return Whether timers have been unregistered
* @warning @a object must belong to the same thread as the event dispatcher
* @warning Timers can only be started from the thread the event dispatcher lives in
*/
bool EventDispatcherLibEvent::unregisterTimers(QObject* object)
{
#ifndef QT_NO_DEBUG
if (!object) {
qWarning("%s: invalid arguments", Q_FUNC_INFO);
return false;
}
if (object->thread() != this->thread() && this->thread() != QThread::currentThread()) {
qWarning("%s: timers cannot be stopped from another thread", Q_FUNC_INFO);
return false;
}
#endif
Q_D(EventDispatcherLibEvent);
return d->unregisterTimers(object);
}
/**
* @brief Returns a list of registered timers for the given @a object.
* @param object Object
* @return List of registered timers
*/
QList<QAbstractEventDispatcher::TimerInfo> EventDispatcherLibEvent::registeredTimers(QObject* object) const
{
if (!object) {
qWarning("%s: invalid argument", Q_FUNC_INFO);
return QList<QAbstractEventDispatcher::TimerInfo>();
}
Q_D(const EventDispatcherLibEvent);
return d->registeredTimers(object);
}
#if QT_VERSION >= 0x050000
/**
* Returns the remaining time in milliseconds with the given @a timerId.
*
* @param timerId Timer ID
* @return The remaining time
* @retval -1 If the timer is inactive
* @retval 0 If the timer is overdue
*/
int EventDispatcherLibEvent::remainingTime(int timerId)
{
Q_D(const EventDispatcherLibEvent);
return d->remainingTime(timerId);
}
#endif
#if defined(Q_OS_WIN) && QT_VERSION >= 0x050000
bool EventDispatcherLibEvent::registerEventNotifier(QWinEventNotifier* notifier)
{
Q_UNUSED(notifier)
Q_UNIMPLEMENTED();
return false;
}
void EventDispatcherLibEvent::unregisterEventNotifier(QWinEventNotifier* notifier)
{
Q_UNUSED(notifier)
Q_UNIMPLEMENTED();
}
#endif
/**
* Wakes up the event loop. Thread-safe
*/
void EventDispatcherLibEvent::wakeUp(void)
{
Q_D(EventDispatcherLibEvent);
d->m_tco->wakeUp();
}
/**
* Interrupts event dispatching. The event dispatcher will return from @c processEvents()
* as soon as possible.
*/
void EventDispatcherLibEvent::interrupt(void)
{
Q_D(EventDispatcherLibEvent);
d->m_interrupt = true;
this->wakeUp();
}
/**
* @brief Does nothing
*/
void EventDispatcherLibEvent::flush(void)
{
}
/**
* @brief EventDispatcherLibEvent::EventDispatcherLibEvent
* @param dd
* @param parent
* @internal
*/
EventDispatcherLibEvent::EventDispatcherLibEvent(EventDispatcherLibEventPrivate& dd, QObject* parent)
: QAbstractEventDispatcher(parent), d_ptr(&dd)
{
}
void EventDispatcherLibEvent::reinitialize(void)
{
Q_D(EventDispatcherLibEvent);
event_reinit(d->m_base);
}
/**
* @fn void EventDispatcherLibEvent::awake()
*
* This signal is emitted after the event loop returns from a function that could block.
*
* @see wakeUp()
* @see aboutToBlock()
*/
/**
* @fn void EventDispatcherLibEvent::aboutToBlock()
*
* This signal is emitted before the event loop calls a function that could block.
*
* @see awake()
*/
<commit_msg>Update eventdispatcher_libevent.cpp<commit_after>#include "common.h"
#include "eventdispatcher_libevent.h"
#include "eventdispatcher_libevent_p.h"
/**
* @class EventDispatcherLibEvent
* @brief The EventDispatcherLibEvent class provides an interface to manage Qt's event queue.
*
* An event dispatcher receives events from the window system and other
* sources. It then sends them to the QCoreApplication or QApplication
* instance for processing and delivery. EventDispatcherLibEvent provides
* fine-grained control over event delivery.
*
* For simple control of event processing use
* QCoreApplication::processEvents().
*
* For finer control of the application's event loop, call
* instance() and call functions on the QAbstractEventDispatcher
* object that is returned.
*
* To use EventDispatcherLibEvent, you must install it with
* QCoreApplication::setEventDispatcher() or QThread::setEventDispatcher()
* before a default event dispatcher has been installed.
* The main event loop is started by calling
* QCoreApplication::exec(), and stopped by calling
* QCoreApplication::exit(). Local event loops can be created using
* QEventLoop.
*
* Programs that perform long operations can call processEvents()
* with a bitwise OR combination of various QEventLoop::ProcessEventsFlag
* values to control which events should be delivered.
*/
/**
* Constructs a new event dispatcher with the given @a parent
*
* @param parent Parent
*/
EventDispatcherLibEvent::EventDispatcherLibEvent(QObject* parent)
: QAbstractEventDispatcher(parent), d_ptr(new EventDispatcherLibEventPrivate(this))
{
}
/**
* Constructs a new event dispatcher with the given configuration @a config and @a parent
*
* @param config Event dispatcher configuration
* @param parent Parent
* @see EventDispatcherLibEventConfig
*/
EventDispatcherLibEvent::EventDispatcherLibEvent(const EventDispatcherLibEventConfig& config, QObject* parent)
: QAbstractEventDispatcher(parent), d_ptr(new EventDispatcherLibEventPrivate(this, config))
{
}
/**
* Destroys the event dispatcher
*/
EventDispatcherLibEvent::~EventDispatcherLibEvent(void)
{
#if QT_VERSION < 0x040600
delete this->d_ptr;
this->d_ptr = 0;
#endif
}
/**
* Retrieve the libevent event_base for this dispatcher
* @return The event_base for this dispatcher
*/
struct event_base* EventDispatcherLibEvent::eventBase(void) const
{
const Q_D(EventDispatcherLibEvent);
return d->eventBase();
}
/**
* @brief Processes pending events that match @a flags until there are no more events to process
* @param flags
* @return Whether an event has been processed
* @retval true If an event has been processed;
* @retval false If no events have been processed
*
* Processes pending events that match @a flags until there are no
* more events to process. Returns true if an event was processed;
* otherwise returns false.
*
* This function is especially useful if you have a long running
* operation and want to show its progress without allowing user
* input; i.e. by using the QEventLoop::ExcludeUserInputEvents flag.
*
* If the QEventLoop::WaitForMoreEvents flag is set in @a flags, the
* behavior of this function is as follows:
*
* @list
* @li If events are available, this function returns after processing them.
* @li If no events are available, this function will wait until more
* are available and return after processing newly available events.
* @endlist
*
* If the QEventLoop::WaitForMoreEvents flag is not set in @a flags,
* and no events are available, this function will return
* immediately.
*
* @note This function does not process events continuously; it
* returns after all available events are processed.
*
* @see hasPendingEvents()
*/
bool EventDispatcherLibEvent::processEvents(QEventLoop::ProcessEventsFlags flags)
{
Q_D(EventDispatcherLibEvent);
return d->processEvents(flags);
}
/**
* Returns @c true if there is an event waiting; otherwise returns @c false
*
* @return Whether there is an event waiting
*/
bool EventDispatcherLibEvent::hasPendingEvents(void)
{
extern uint qGlobalPostedEventsCount();
return qGlobalPostedEventsCount() > 0;
}
/**
* Registers @a notifier with the event loop
*
* @param notifier Socket notifier to register
* @warning @a notifier must belong to the same thread as the event dispatcher
* @warning Socket notifiers can only be enabled from the thread they belong to
*/
void EventDispatcherLibEvent::registerSocketNotifier(QSocketNotifier* notifier)
{
#ifndef QT_NO_DEBUG
if (notifier->socket() < 0) {
qWarning("QSocketNotifier: Internal error: sockfd < 0");
return;
}
if (notifier->thread() != this->thread() || this->thread() != QThread::currentThread()) {
qWarning("QSocketNotifier: socket notifiers cannot be enabled from another thread");
return;
}
#endif
if (notifier->type() == QSocketNotifier::Exception) {
return;
}
Q_D(EventDispatcherLibEvent);
d->registerSocketNotifier(notifier);
}
/**
* Unregisters @a notifier from the event dispatcher.
*
* @param notifier Socket notifier to unregister
* @warning @a notifier must belong to the same thread as the event dispatcher
* @warning Socket notifiers can only be disabled from the thread they belong to
*/
void EventDispatcherLibEvent::unregisterSocketNotifier(QSocketNotifier* notifier)
{
#ifndef QT_NO_DEBUG
if (notifier->socket() < 0) {
qWarning("QSocketNotifier: Internal error: sockfd < 0");
return;
}
if (notifier->thread() != this->thread() || this->thread() != QThread::currentThread()) {
qWarning("QSocketNotifier: socket notifiers cannot be disabled from another thread");
return;
}
#endif
// Short circuit, we do not support QSocketNotifier::Exception
if (notifier->type() == QSocketNotifier::Exception) {
return;
}
Q_D(EventDispatcherLibEvent);
d->unregisterSocketNotifier(notifier);
}
/**
* Register a timer with the specified @a timerId, @a interval, and @a timerType
* for the given @a object.
*
* @param timerId Timer ID
* @param interval Timer interval (msec); must be greater than 0
* @param timerType Timer type (not available in Qt 4)
* @param object Object for which the timer is registered
* @warning @a object must belong to the same thread as the event dispatcher
* @warning Timers can only be started from the thread the event dispatcher lives in
*/
void EventDispatcherLibEvent::registerTimer(
int timerId,
int interval,
#if QT_VERSION >= 0x050000
Qt::TimerType timerType,
#endif
QObject* object
)
{
#ifndef QT_NO_DEBUG
if (timerId < 1 || interval < 0 || !object) {
qWarning("%s: invalid arguments", Q_FUNC_INFO);
return;
}
if (object->thread() != this->thread() && this->thread() != QThread::currentThread()) {
qWarning("%s: timers cannot be started from another thread", Q_FUNC_INFO);
return;
}
#endif
Qt::TimerType type;
#if QT_VERSION >= 0x050000
type = timerType;
#else
type = Qt::CoarseTimer;
#endif
Q_D(EventDispatcherLibEvent);
d->registerTimer(timerId, interval, type, object);
}
/**
* Unregisters the timer
*
* @param timerId ID of the timer
* @return Whether the timer has been unregistered
* @warning Timers can only be stopped from the same thread as the event dispatcher lives in
*/
bool EventDispatcherLibEvent::unregisterTimer(int timerId)
{
#ifndef QT_NO_DEBUG
if (timerId < 1) {
qWarning("%s: invalid arguments", Q_FUNC_INFO);
return false;
}
if (this->thread() != QThread::currentThread()) {
qWarning("%s: timers cannot be stopped from another thread", Q_FUNC_INFO);
return false;
}
#endif
Q_D(EventDispatcherLibEvent);
return d->unregisterTimer(timerId);
}
/**
* Unregisters all timers for the given @a object
*
* @param object Object
* @return Whether timers have been unregistered
* @warning @a object must belong to the same thread as the event dispatcher
* @warning Timers can only be started from the thread the event dispatcher lives in
*/
bool EventDispatcherLibEvent::unregisterTimers(QObject* object)
{
#ifndef QT_NO_DEBUG
if (!object) {
qWarning("%s: invalid arguments", Q_FUNC_INFO);
return false;
}
if (object->thread() != this->thread() && this->thread() != QThread::currentThread()) {
qWarning("%s: timers cannot be stopped from another thread", Q_FUNC_INFO);
return false;
}
#endif
Q_D(EventDispatcherLibEvent);
return d->unregisterTimers(object);
}
/**
* @brief Returns a list of registered timers for the given @a object.
* @param object Object
* @return List of registered timers
*/
QList<QAbstractEventDispatcher::TimerInfo> EventDispatcherLibEvent::registeredTimers(QObject* object) const
{
if (!object) {
qWarning("%s: invalid argument", Q_FUNC_INFO);
return QList<QAbstractEventDispatcher::TimerInfo>();
}
Q_D(const EventDispatcherLibEvent);
return d->registeredTimers(object);
}
#if QT_VERSION >= 0x050000
/**
* Returns the remaining time in milliseconds with the given @a timerId.
*
* @param timerId Timer ID
* @return The remaining time
* @retval -1 If the timer is inactive
* @retval 0 If the timer is overdue
*/
int EventDispatcherLibEvent::remainingTime(int timerId)
{
Q_D(const EventDispatcherLibEvent);
return d->remainingTime(timerId);
}
#endif
#if defined(Q_OS_WIN) && QT_VERSION >= 0x050000
bool EventDispatcherLibEvent::registerEventNotifier(QWinEventNotifier* notifier)
{
Q_UNUSED(notifier)
Q_UNIMPLEMENTED();
return false;
}
void EventDispatcherLibEvent::unregisterEventNotifier(QWinEventNotifier* notifier)
{
Q_UNUSED(notifier)
Q_UNIMPLEMENTED();
}
#endif
/**
* Wakes up the event loop. Thread-safe
*/
void EventDispatcherLibEvent::wakeUp(void)
{
Q_D(EventDispatcherLibEvent);
d->m_tco->wakeUp();
}
/**
* Interrupts event dispatching. The event dispatcher will return from @c processEvents()
* as soon as possible.
*/
void EventDispatcherLibEvent::interrupt(void)
{
Q_D(EventDispatcherLibEvent);
d->m_interrupt = true;
this->wakeUp();
}
/**
* @brief Does nothing
*/
void EventDispatcherLibEvent::flush(void)
{
}
/**
* @brief EventDispatcherLibEvent::EventDispatcherLibEvent
* @param dd
* @param parent
* @internal
*/
EventDispatcherLibEvent::EventDispatcherLibEvent(EventDispatcherLibEventPrivate& dd, QObject* parent)
: QAbstractEventDispatcher(parent), d_ptr(&dd)
{
}
void EventDispatcherLibEvent::reinitialize(void)
{
Q_D(EventDispatcherLibEvent);
event_reinit(d->m_base);
}
/**
* @fn void EventDispatcherLibEvent::awake()
*
* This signal is emitted after the event loop returns from a function that could block.
*
* @see wakeUp()
* @see aboutToBlock()
*/
/**
* @fn void EventDispatcherLibEvent::aboutToBlock()
*
* This signal is emitted before the event loop calls a function that could block.
*
* @see awake()
*/
<|endoftext|>
|
<commit_before>/*
Copyright 2012 Denys Sobchyshak
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <iostream>
#include "sorter.h"
//Performs a bubble sort on an array of ints.
void BubbleSort(int *array, int array_size){
for (int i = 0; i<array_size; i++){
bool swapped = false;
for (int j = array_size; j>i; j--){
if (array[j-1] > array[j]){
int tmp = array[j-1];
array[j-1] = array[j];
array[j] = tmp;
swapped = true;
}
}
//-> invariant: array[0..i] is sorted and elements are in final position
if (!swapped) break;
}
};
//Performs an insertion sort on an array of ints.
void InsertionSort(int *array, int array_size){
for (int i = 1; i < array_size; i++){
int key = array[i];
int j = i-1;
while (j >= 0 && array[j] > key) {
array[j+1] = array[j];
j--;
}
array[j+1] = key;
//-> invariant: array[0..j] is sorted
}
};
//Performs a shell sort on an array of ints.
void ShellSort(int *array, int array_size){
int h = 1;
while (h < array_size) h = 3*h + 1;
while (h > 0){
h = h/3;
for (int k = 0; k < h; k++){
for (int i = h; i < array_size; i+=h){
int key = array[i];
int j = i-h;
while (j>=0 && array[j] > key){
array[j+h] = array[j];
j-=h;
}
array[j+h] = key;
//-> invariant: array[0..j] is sorted
}
}
//->invariant: each h-sub-array is sorted
}
};
//Performs a selection sort on an array of ints.
void SelectionSort(int *array, int array_size){
for (int i = 0; i < array_size; i++){
int iMin = i;
for(int j = i+1; j < array_size; j++){
if (array[iMin] > array[j]) iMin = j;
}
if (iMin != i){
int tmp = array[i];
array[i] = array[iMin];
array[iMin] = tmp;
}
//->invariant: array[0...i] is sorted
}
};
//Performs a heap sort on an array of ints.
void HeapSort(int *array, int array_size){
};
//Performs a merge sort on an array of ints.
void MergeSort(int *array, int array_size){
};
//Performs a quick sort on an array of ints.
void QuickSort(int *array, int array_size){
};<commit_msg>fixed shell sort bug<commit_after>/*
Copyright 2012 Denys Sobchyshak
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <iostream>
#include "sorter.h"
//Performs a bubble sort on an array of ints.
void BubbleSort(int *array, int array_size){
for (int i = 0; i<array_size; i++){
bool swapped = false;
for (int j = array_size; j>i; j--){
if (array[j-1] > array[j]){
int tmp = array[j-1];
array[j-1] = array[j];
array[j] = tmp;
swapped = true;
}
}
//-> invariant: array[0..i] is sorted and elements are in final position
if (!swapped) break;
}
};
//Performs an insertion sort on an array of ints.
void InsertionSort(int *array, int array_size){
for (int i = 1; i < array_size; i++){
int key = array[i];
int j = i-1;
while (j >= 0 && array[j] > key) {
array[j+1] = array[j];
j--;
}
array[j+1] = key;
//-> invariant: array[0..j] is sorted
}
};
//Performs a shell sort on an array of ints.
void ShellSort(int *array, int array_size){
int h = 1;
while (h < array_size) h = 3*h + 1;
while (h > 0){
h = h/3;
for (int k = 0; k < h; k++){
for (int i = h+k; i < array_size; i+=h){
int key = array[i];
int j = i-h;
while (j>=0 && array[j] > key){
array[j+h] = array[j];
j-=h;
}
array[j+h] = key;
//-> invariant: array[k,k+h...j] is sorted
}
}
//->invariant: each h-sub-array is sorted
}
};
//Performs a selection sort on an array of ints.
void SelectionSort(int *array, int array_size){
for (int i = 0; i < array_size; i++){
int iMin = i;
for(int j = i+1; j < array_size; j++){
if (array[iMin] > array[j]) iMin = j;
}
if (iMin != i){
int tmp = array[i];
array[i] = array[iMin];
array[iMin] = tmp;
}
//->invariant: array[0...i] is sorted
}
};
//Performs a heap sort on an array of ints.
void HeapSort(int *array, int array_size){
};
//Performs a merge sort on an array of ints.
void MergeSort(int *array, int array_size){
};
//Performs a quick sort on an array of ints.
void QuickSort(int *array, int array_size){
};<|endoftext|>
|
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
//
// File contains modifications by: The Gulden developers
// All modifications:
// Copyright (c) 2016-2018 The Gulden developers
// Authored by: Malcolm MacLeod (mmacleod@gmx.com)
// Distributed under the GULDEN software license, see the accompanying
// file COPYING
#if defined(HAVE_CONFIG_H)
#include "config/build-config.h"
#endif
#include "chainparamsbase.h"
#include "clientversion.h"
#include "fs.h"
#include "rpc/client.h"
#include "rpc/protocol.h"
#include "util.h"
#include "utilstrencodings.h"
#include <stdio.h>
#define _(x) std::string(x)/* Keep the _() around in case gettext or such will be used later to translate non-UI */
#include <event2/buffer.h>
#include <event2/keyvalq_struct.h>
#include "support/events.h"
#include <univalue.h>
#include "util.h"
static const char DEFAULT_RPCCONNECT[] = "127.0.0.1";
static const int DEFAULT_HTTP_CLIENT_TIMEOUT=900;
static const bool DEFAULT_NAMED=false;
static const int CONTINUE_EXECUTION=-1;
static std::string HelpMessageCli()
{
const auto defaultBaseParams = CreateBaseChainParams(CBaseChainParams::MAIN);
const auto testnetBaseParams = CreateBaseChainParams(CBaseChainParams::TESTNET);
std::string strUsage;
strUsage += HelpMessageGroup(_("Options:"));
strUsage += HelpMessageOpt("-?", _("This help message"));
strUsage += HelpMessageOpt("-conf=<file>", strprintf(_("Specify configuration file (default: %s)"), DEFAULT_CONF_FILENAME));
strUsage += HelpMessageOpt("-datadir=<dir>", _("Specify data directory"));
AppendParamsHelpMessages(strUsage);
strUsage += HelpMessageOpt("-named", strprintf(_("Pass named instead of positional arguments (default: %s)"), DEFAULT_NAMED));
strUsage += HelpMessageOpt("-rpcconnect=<ip>", strprintf(_("Send commands to node running on <ip> (default: %s)"), DEFAULT_RPCCONNECT));
strUsage += HelpMessageOpt("-rpcport=<port>", strprintf(_("Connect to JSON-RPC on <port> (default: %u or testnet: %u)"), defaultBaseParams->RPCPort(), testnetBaseParams->RPCPort()));
strUsage += HelpMessageOpt("-rpcwait", _("Wait for RPC server to start"));
strUsage += HelpMessageOpt("-rpcuser=<user>", _("Username for JSON-RPC connections"));
strUsage += HelpMessageOpt("-rpcpassword=<pw>", _("Password for JSON-RPC connections"));
strUsage += HelpMessageOpt("-rpcclienttimeout=<n>", strprintf(_("Timeout in seconds during HTTP requests, or 0 for no timeout. (default: %d)"), DEFAULT_HTTP_CLIENT_TIMEOUT));
strUsage += HelpMessageOpt("-stdin", _("Read extra arguments from standard input, one per line until EOF/Ctrl-D (recommended for sensitive information such as passphrases)"));
return strUsage;
}
//////////////////////////////////////////////////////////////////////////////
//
// Start
//
//
// Exception thrown on connection error. This error is used to determine
// when to wait if -rpcwait is given.
//
class CConnectionFailed : public std::runtime_error
{
public:
explicit inline CConnectionFailed(const std::string& msg) :
std::runtime_error(msg)
{}
};
//
// This function returns either one of EXIT_ codes when it's expected to stop the process or
// CONTINUE_EXECUTION when it's expected to continue further.
//
static int AppInitRPC(int argc, char* argv[])
{
//
// Parameters
//
ParseParameters(argc, argv);
if (argc<2 || IsArgSet("-?") || IsArgSet("-h") || IsArgSet("-help") || IsArgSet("-version")) {
std::string strUsage = strprintf(_("%s RPC client version"), _(PACKAGE_NAME)) + " " + FormatFullVersion() + "\n";
if (!IsArgSet("-version")) {
strUsage += "\n" + _("Usage:") + "\n" +
" "CLI_NAME" [options] <command> [params] " + strprintf(_("Send command to %s"), _(PACKAGE_NAME)) + "\n" +
" "CLI_NAME" [options] -named <command> [name=value] ... " + strprintf(_("Send command to %s (with named arguments)"), _(PACKAGE_NAME)) + "\n" +
" "CLI_NAME" [options] help " + _("List commands") + "\n" +
" "CLI_NAME" [options] help <command> " + _("Get help for a command") + "\n";
strUsage += "\n" + HelpMessageCli();
}
fprintf(stdout, "%s", strUsage.c_str());
if (argc < 2) {
fprintf(stderr, "Error: too few parameters\n");
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
if (!fs::is_directory(GetDataDir(false))) {
fprintf(stderr, "Error: Specified data directory \"%s\" does not exist.\n", GetArg("-datadir", "").c_str());
return EXIT_FAILURE;
}
try {
ReadConfigFile(GetArg("-conf", DEFAULT_CONF_FILENAME));
} catch (const std::exception& e) {
fprintf(stderr,"Error reading configuration file: %s\n", e.what());
return EXIT_FAILURE;
}
// Check for -testnet or -regtest parameter (BaseParams() calls are only valid after this clause)
try {
SelectBaseParams(ChainNameFromCommandLine());
} catch (const std::exception& e) {
fprintf(stderr, "Error: %s\n", e.what());
return EXIT_FAILURE;
}
if (GetBoolArg("-rpcssl", false))
{
fprintf(stderr, "Error: SSL mode for RPC (-rpcssl) is no longer supported.\n");
return EXIT_FAILURE;
}
return CONTINUE_EXECUTION;
}
/** Reply structure for request_done to fill in */
struct HTTPReply
{
HTTPReply(): status(0), error(-1) {}
int status;
int error;
std::string body;
};
const char *http_errorstring(int code)
{
switch(code) {
#if LIBEVENT_VERSION_NUMBER >= 0x02010300
case EVREQ_HTTP_TIMEOUT:
return "timeout reached";
case EVREQ_HTTP_EOF:
return "EOF reached";
case EVREQ_HTTP_INVALID_HEADER:
return "error while reading header, or invalid header";
case EVREQ_HTTP_BUFFER_ERROR:
return "error encountered while reading or writing";
case EVREQ_HTTP_REQUEST_CANCEL:
return "request was canceled";
case EVREQ_HTTP_DATA_TOO_LONG:
return "response body is larger than allowed";
#endif
default:
return "unknown";
}
}
static void http_request_done(struct evhttp_request *req, void *ctx)
{
HTTPReply *reply = static_cast<HTTPReply*>(ctx);
if (req == NULL) {
/* If req is NULL, it means an error occurred while connecting: the
* error code will have been passed to http_error_cb.
*/
reply->status = 0;
return;
}
reply->status = evhttp_request_get_response_code(req);
struct evbuffer *buf = evhttp_request_get_input_buffer(req);
if (buf)
{
size_t size = evbuffer_get_length(buf);
const char *data = (const char*)evbuffer_pullup(buf, size);
if (data)
reply->body = std::string(data, size);
evbuffer_drain(buf, size);
}
}
#if LIBEVENT_VERSION_NUMBER >= 0x02010300
static void http_error_cb(enum evhttp_request_error err, void *ctx)
{
HTTPReply *reply = static_cast<HTTPReply*>(ctx);
reply->error = err;
}
#endif
UniValue CallRPC(const std::string& strMethod, const UniValue& params)
{
std::string host = GetArg("-rpcconnect", DEFAULT_RPCCONNECT);
int port = GetArg("-rpcport", BaseParams().RPCPort());
// Obtain event base
raii_event_base base = obtain_event_base();
// Synchronously look up hostname
raii_evhttp_connection evcon = obtain_evhttp_connection_base(base.get(), host, port);
evhttp_connection_set_timeout(evcon.get(), GetArg("-rpcclienttimeout", DEFAULT_HTTP_CLIENT_TIMEOUT));
HTTPReply response;
raii_evhttp_request req = obtain_evhttp_request(http_request_done, (void*)&response);
if (req == NULL)
throw std::runtime_error("create http request failed");
#if LIBEVENT_VERSION_NUMBER >= 0x02010300
evhttp_request_set_error_cb(req.get(), http_error_cb);
#endif
// Get credentials
std::string strRPCUserColonPass;
if (GetArg("-rpcpassword", "") == "") {
// Try fall back to cookie-based authentication if no password is provided
if (!GetAuthCookie(&strRPCUserColonPass)) {
throw std::runtime_error(strprintf(
_("Could not locate RPC credentials. No authentication cookie could be found, and no rpcpassword is set in the configuration file (%s)"),
GetConfigFile(GetArg("-conf", DEFAULT_CONF_FILENAME)).string().c_str()));
}
} else {
strRPCUserColonPass = GetArg("-rpcuser", "") + ":" + GetArg("-rpcpassword", "");
}
struct evkeyvalq* output_headers = evhttp_request_get_output_headers(req.get());
assert(output_headers);
evhttp_add_header(output_headers, "Host", host.c_str());
evhttp_add_header(output_headers, "Connection", "close");
evhttp_add_header(output_headers, "Authorization", (std::string("Basic ") + EncodeBase64(strRPCUserColonPass)).c_str());
// Attach request data
std::string strRequest = JSONRPCRequestObj(strMethod, params, 1).write() + "\n";
struct evbuffer* output_buffer = evhttp_request_get_output_buffer(req.get());
assert(output_buffer);
evbuffer_add(output_buffer, strRequest.data(), strRequest.size());
int r = evhttp_make_request(evcon.get(), req.get(), EVHTTP_REQ_POST, "/");
req.release(); // ownership moved to evcon in above call
if (r != 0) {
throw CConnectionFailed("send http request failed");
}
event_base_dispatch(base.get());
if (response.status == 0)
throw CConnectionFailed(strprintf("couldn't connect to server: %s (code %d)\n(make sure server is running and you are connecting to the correct RPC port)", http_errorstring(response.error), response.error));
else if (response.status == HTTP_UNAUTHORIZED)
throw std::runtime_error("incorrect rpcuser or rpcpassword (authorization failed)");
else if (response.status >= 400 && response.status != HTTP_BAD_REQUEST && response.status != HTTP_NOT_FOUND && response.status != HTTP_INTERNAL_SERVER_ERROR)
throw std::runtime_error(strprintf("server returned HTTP error %d", response.status));
else if (response.body.empty())
throw std::runtime_error("no response from server");
// Parse reply
UniValue valReply(UniValue::VSTR);
if (!valReply.read(response.body))
throw std::runtime_error("couldn't parse reply from server");
const UniValue& reply = valReply.get_obj();
if (reply.empty())
throw std::runtime_error("expected reply to have result, error and id properties");
return reply;
}
int CommandLineRPC(int argc, char *argv[])
{
std::string strPrint;
int nRet = 0;
try {
// Skip switches
while (argc > 1 && IsSwitchChar(argv[1][0])) {
argc--;
argv++;
}
std::vector<std::string> args = std::vector<std::string>(&argv[1], &argv[argc]);
if (GetBoolArg("-stdin", false)) {
// Read one arg per line from stdin and append
std::string line;
while (std::getline(std::cin,line))
args.push_back(line);
}
if (args.size() < 1)
throw std::runtime_error("too few parameters (need at least command)");
std::string strMethod = args[0];
args.erase(args.begin()); // Remove trailing method name from arguments vector
UniValue params;
if(GetBoolArg("-named", DEFAULT_NAMED)) {
params = RPCConvertNamedValues(strMethod, args);
} else {
params = RPCConvertValues(strMethod, args);
}
// Execute and handle connection failures with -rpcwait
const bool fWait = GetBoolArg("-rpcwait", false);
do {
try {
const UniValue reply = CallRPC(strMethod, params);
// Parse reply
const UniValue& result = find_value(reply, "result");
const UniValue& error = find_value(reply, "error");
if (!error.isNull()) {
// Error
int code = error["code"].get_int();
if (fWait && code == RPC_IN_WARMUP)
throw CConnectionFailed("server in warmup");
strPrint = "error: " + error.write();
nRet = abs(code);
if (error.isObject())
{
UniValue errCode = find_value(error, "code");
UniValue errMsg = find_value(error, "message");
strPrint = errCode.isNull() ? "" : "error code: "+errCode.getValStr()+"\n";
if (errMsg.isStr())
strPrint += "error message:\n"+errMsg.get_str();
}
} else {
// Result
if (result.isNull())
strPrint = "";
else if (result.isStr())
strPrint = result.get_str();
else
strPrint = result.write(2);
}
// Connection succeeded, no need to retry.
break;
}
catch (const CConnectionFailed&) {
if (fWait)
MilliSleep(1000);
else
throw;
}
} while (fWait);
}
catch (const boost::thread_interrupted&) {
throw;
}
catch (const std::exception& e) {
strPrint = std::string("error: ") + e.what();
nRet = EXIT_FAILURE;
}
catch (...) {
PrintExceptionContinue(NULL, "CommandLineRPC()");
throw;
}
if (strPrint != "") {
fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());
}
return nRet;
}
int main(int argc, char* argv[])
{
SetupEnvironment();
if (!SetupNetworking()) {
fprintf(stderr, "Error: Initializing networking failed\n");
return EXIT_FAILURE;
}
try {
int ret = AppInitRPC(argc, argv);
if (ret != CONTINUE_EXECUTION)
return ret;
}
catch (const std::exception& e) {
PrintExceptionContinue(&e, "AppInitRPC()");
return EXIT_FAILURE;
} catch (...) {
PrintExceptionContinue(NULL, "AppInitRPC()");
return EXIT_FAILURE;
}
int ret = EXIT_FAILURE;
try {
ret = CommandLineRPC(argc, argv);
}
catch (const std::exception& e) {
PrintExceptionContinue(&e, "CommandLineRPC()");
} catch (...) {
PrintExceptionContinue(NULL, "CommandLineRPC()");
}
return ret;
}
//fixme: (HIGH)
//Super gross workaround - for some reason our macos build keeps failing to provide '___cpu_model' symbol, so we just define it ourselves as a workaround until we can fix the issue.
#ifdef MAC_OSX
#include "llvm-cpumodel-hack.cpp"
#endif
<commit_msg>QA: Travis build fix<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
//
// File contains modifications by: The Gulden developers
// All modifications:
// Copyright (c) 2016-2018 The Gulden developers
// Authored by: Malcolm MacLeod (mmacleod@gmx.com)
// Distributed under the GULDEN software license, see the accompanying
// file COPYING
#if defined(HAVE_CONFIG_H)
#include "config/build-config.h"
#endif
#include "chainparamsbase.h"
#include "clientversion.h"
#include "fs.h"
#include "rpc/client.h"
#include "rpc/protocol.h"
#include "util.h"
#include "utilstrencodings.h"
#include <stdio.h>
#define _(x) std::string(x)/* Keep the _() around in case gettext or such will be used later to translate non-UI */
#include <event2/buffer.h>
#include <event2/keyvalq_struct.h>
#include "support/events.h"
#include <univalue.h>
#include "util.h"
static const char DEFAULT_RPCCONNECT[] = "127.0.0.1";
static const int DEFAULT_HTTP_CLIENT_TIMEOUT=900;
static const bool DEFAULT_NAMED=false;
static const int CONTINUE_EXECUTION=-1;
static std::string HelpMessageCli()
{
const auto defaultBaseParams = CreateBaseChainParams(CBaseChainParams::MAIN);
const auto testnetBaseParams = CreateBaseChainParams(CBaseChainParams::TESTNET);
std::string strUsage;
strUsage += HelpMessageGroup(_("Options:"));
strUsage += HelpMessageOpt("-?", _("This help message"));
strUsage += HelpMessageOpt("-conf=<file>", strprintf(_("Specify configuration file (default: %s)"), DEFAULT_CONF_FILENAME));
strUsage += HelpMessageOpt("-datadir=<dir>", _("Specify data directory"));
AppendParamsHelpMessages(strUsage);
strUsage += HelpMessageOpt("-named", strprintf(_("Pass named instead of positional arguments (default: %s)"), DEFAULT_NAMED));
strUsage += HelpMessageOpt("-rpcconnect=<ip>", strprintf(_("Send commands to node running on <ip> (default: %s)"), DEFAULT_RPCCONNECT));
strUsage += HelpMessageOpt("-rpcport=<port>", strprintf(_("Connect to JSON-RPC on <port> (default: %u or testnet: %u)"), defaultBaseParams->RPCPort(), testnetBaseParams->RPCPort()));
strUsage += HelpMessageOpt("-rpcwait", _("Wait for RPC server to start"));
strUsage += HelpMessageOpt("-rpcuser=<user>", _("Username for JSON-RPC connections"));
strUsage += HelpMessageOpt("-rpcpassword=<pw>", _("Password for JSON-RPC connections"));
strUsage += HelpMessageOpt("-rpcclienttimeout=<n>", strprintf(_("Timeout in seconds during HTTP requests, or 0 for no timeout. (default: %d)"), DEFAULT_HTTP_CLIENT_TIMEOUT));
strUsage += HelpMessageOpt("-stdin", _("Read extra arguments from standard input, one per line until EOF/Ctrl-D (recommended for sensitive information such as passphrases)"));
return strUsage;
}
//////////////////////////////////////////////////////////////////////////////
//
// Start
//
//
// Exception thrown on connection error. This error is used to determine
// when to wait if -rpcwait is given.
//
class CConnectionFailed : public std::runtime_error
{
public:
explicit inline CConnectionFailed(const std::string& msg) :
std::runtime_error(msg)
{}
};
//
// This function returns either one of EXIT_ codes when it's expected to stop the process or
// CONTINUE_EXECUTION when it's expected to continue further.
//
static int AppInitRPC(int argc, char* argv[])
{
//
// Parameters
//
ParseParameters(argc, argv);
if (argc<2 || IsArgSet("-?") || IsArgSet("-h") || IsArgSet("-help") || IsArgSet("-version")) {
std::string strUsage = strprintf(_("%s RPC client version"), _(PACKAGE_NAME)) + " " + FormatFullVersion() + "\n";
if (!IsArgSet("-version")) {
strUsage += "\n" + _("Usage:") + "\n" +
" " CLI_NAME " [options] <command> [params] " + strprintf(_("Send command to %s"), _(PACKAGE_NAME)) + "\n" +
" " CLI_NAME " [options] -named <command> [name=value] ... " + strprintf(_("Send command to %s (with named arguments)"), _(PACKAGE_NAME)) + "\n" +
" " CLI_NAME " [options] help " + _("List commands") + "\n" +
" " CLI_NAME " [options] help <command> " + _("Get help for a command") + "\n";
strUsage += "\n" + HelpMessageCli();
}
fprintf(stdout, "%s", strUsage.c_str());
if (argc < 2) {
fprintf(stderr, "Error: too few parameters\n");
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
if (!fs::is_directory(GetDataDir(false))) {
fprintf(stderr, "Error: Specified data directory \"%s\" does not exist.\n", GetArg("-datadir", "").c_str());
return EXIT_FAILURE;
}
try {
ReadConfigFile(GetArg("-conf", DEFAULT_CONF_FILENAME));
} catch (const std::exception& e) {
fprintf(stderr,"Error reading configuration file: %s\n", e.what());
return EXIT_FAILURE;
}
// Check for -testnet or -regtest parameter (BaseParams() calls are only valid after this clause)
try {
SelectBaseParams(ChainNameFromCommandLine());
} catch (const std::exception& e) {
fprintf(stderr, "Error: %s\n", e.what());
return EXIT_FAILURE;
}
if (GetBoolArg("-rpcssl", false))
{
fprintf(stderr, "Error: SSL mode for RPC (-rpcssl) is no longer supported.\n");
return EXIT_FAILURE;
}
return CONTINUE_EXECUTION;
}
/** Reply structure for request_done to fill in */
struct HTTPReply
{
HTTPReply(): status(0), error(-1) {}
int status;
int error;
std::string body;
};
const char *http_errorstring(int code)
{
switch(code) {
#if LIBEVENT_VERSION_NUMBER >= 0x02010300
case EVREQ_HTTP_TIMEOUT:
return "timeout reached";
case EVREQ_HTTP_EOF:
return "EOF reached";
case EVREQ_HTTP_INVALID_HEADER:
return "error while reading header, or invalid header";
case EVREQ_HTTP_BUFFER_ERROR:
return "error encountered while reading or writing";
case EVREQ_HTTP_REQUEST_CANCEL:
return "request was canceled";
case EVREQ_HTTP_DATA_TOO_LONG:
return "response body is larger than allowed";
#endif
default:
return "unknown";
}
}
static void http_request_done(struct evhttp_request *req, void *ctx)
{
HTTPReply *reply = static_cast<HTTPReply*>(ctx);
if (req == NULL) {
/* If req is NULL, it means an error occurred while connecting: the
* error code will have been passed to http_error_cb.
*/
reply->status = 0;
return;
}
reply->status = evhttp_request_get_response_code(req);
struct evbuffer *buf = evhttp_request_get_input_buffer(req);
if (buf)
{
size_t size = evbuffer_get_length(buf);
const char *data = (const char*)evbuffer_pullup(buf, size);
if (data)
reply->body = std::string(data, size);
evbuffer_drain(buf, size);
}
}
#if LIBEVENT_VERSION_NUMBER >= 0x02010300
static void http_error_cb(enum evhttp_request_error err, void *ctx)
{
HTTPReply *reply = static_cast<HTTPReply*>(ctx);
reply->error = err;
}
#endif
UniValue CallRPC(const std::string& strMethod, const UniValue& params)
{
std::string host = GetArg("-rpcconnect", DEFAULT_RPCCONNECT);
int port = GetArg("-rpcport", BaseParams().RPCPort());
// Obtain event base
raii_event_base base = obtain_event_base();
// Synchronously look up hostname
raii_evhttp_connection evcon = obtain_evhttp_connection_base(base.get(), host, port);
evhttp_connection_set_timeout(evcon.get(), GetArg("-rpcclienttimeout", DEFAULT_HTTP_CLIENT_TIMEOUT));
HTTPReply response;
raii_evhttp_request req = obtain_evhttp_request(http_request_done, (void*)&response);
if (req == NULL)
throw std::runtime_error("create http request failed");
#if LIBEVENT_VERSION_NUMBER >= 0x02010300
evhttp_request_set_error_cb(req.get(), http_error_cb);
#endif
// Get credentials
std::string strRPCUserColonPass;
if (GetArg("-rpcpassword", "") == "") {
// Try fall back to cookie-based authentication if no password is provided
if (!GetAuthCookie(&strRPCUserColonPass)) {
throw std::runtime_error(strprintf(
_("Could not locate RPC credentials. No authentication cookie could be found, and no rpcpassword is set in the configuration file (%s)"),
GetConfigFile(GetArg("-conf", DEFAULT_CONF_FILENAME)).string().c_str()));
}
} else {
strRPCUserColonPass = GetArg("-rpcuser", "") + ":" + GetArg("-rpcpassword", "");
}
struct evkeyvalq* output_headers = evhttp_request_get_output_headers(req.get());
assert(output_headers);
evhttp_add_header(output_headers, "Host", host.c_str());
evhttp_add_header(output_headers, "Connection", "close");
evhttp_add_header(output_headers, "Authorization", (std::string("Basic ") + EncodeBase64(strRPCUserColonPass)).c_str());
// Attach request data
std::string strRequest = JSONRPCRequestObj(strMethod, params, 1).write() + "\n";
struct evbuffer* output_buffer = evhttp_request_get_output_buffer(req.get());
assert(output_buffer);
evbuffer_add(output_buffer, strRequest.data(), strRequest.size());
int r = evhttp_make_request(evcon.get(), req.get(), EVHTTP_REQ_POST, "/");
req.release(); // ownership moved to evcon in above call
if (r != 0) {
throw CConnectionFailed("send http request failed");
}
event_base_dispatch(base.get());
if (response.status == 0)
throw CConnectionFailed(strprintf("couldn't connect to server: %s (code %d)\n(make sure server is running and you are connecting to the correct RPC port)", http_errorstring(response.error), response.error));
else if (response.status == HTTP_UNAUTHORIZED)
throw std::runtime_error("incorrect rpcuser or rpcpassword (authorization failed)");
else if (response.status >= 400 && response.status != HTTP_BAD_REQUEST && response.status != HTTP_NOT_FOUND && response.status != HTTP_INTERNAL_SERVER_ERROR)
throw std::runtime_error(strprintf("server returned HTTP error %d", response.status));
else if (response.body.empty())
throw std::runtime_error("no response from server");
// Parse reply
UniValue valReply(UniValue::VSTR);
if (!valReply.read(response.body))
throw std::runtime_error("couldn't parse reply from server");
const UniValue& reply = valReply.get_obj();
if (reply.empty())
throw std::runtime_error("expected reply to have result, error and id properties");
return reply;
}
int CommandLineRPC(int argc, char *argv[])
{
std::string strPrint;
int nRet = 0;
try {
// Skip switches
while (argc > 1 && IsSwitchChar(argv[1][0])) {
argc--;
argv++;
}
std::vector<std::string> args = std::vector<std::string>(&argv[1], &argv[argc]);
if (GetBoolArg("-stdin", false)) {
// Read one arg per line from stdin and append
std::string line;
while (std::getline(std::cin,line))
args.push_back(line);
}
if (args.size() < 1)
throw std::runtime_error("too few parameters (need at least command)");
std::string strMethod = args[0];
args.erase(args.begin()); // Remove trailing method name from arguments vector
UniValue params;
if(GetBoolArg("-named", DEFAULT_NAMED)) {
params = RPCConvertNamedValues(strMethod, args);
} else {
params = RPCConvertValues(strMethod, args);
}
// Execute and handle connection failures with -rpcwait
const bool fWait = GetBoolArg("-rpcwait", false);
do {
try {
const UniValue reply = CallRPC(strMethod, params);
// Parse reply
const UniValue& result = find_value(reply, "result");
const UniValue& error = find_value(reply, "error");
if (!error.isNull()) {
// Error
int code = error["code"].get_int();
if (fWait && code == RPC_IN_WARMUP)
throw CConnectionFailed("server in warmup");
strPrint = "error: " + error.write();
nRet = abs(code);
if (error.isObject())
{
UniValue errCode = find_value(error, "code");
UniValue errMsg = find_value(error, "message");
strPrint = errCode.isNull() ? "" : "error code: "+errCode.getValStr()+"\n";
if (errMsg.isStr())
strPrint += "error message:\n"+errMsg.get_str();
}
} else {
// Result
if (result.isNull())
strPrint = "";
else if (result.isStr())
strPrint = result.get_str();
else
strPrint = result.write(2);
}
// Connection succeeded, no need to retry.
break;
}
catch (const CConnectionFailed&) {
if (fWait)
MilliSleep(1000);
else
throw;
}
} while (fWait);
}
catch (const boost::thread_interrupted&) {
throw;
}
catch (const std::exception& e) {
strPrint = std::string("error: ") + e.what();
nRet = EXIT_FAILURE;
}
catch (...) {
PrintExceptionContinue(NULL, "CommandLineRPC()");
throw;
}
if (strPrint != "") {
fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());
}
return nRet;
}
int main(int argc, char* argv[])
{
SetupEnvironment();
if (!SetupNetworking()) {
fprintf(stderr, "Error: Initializing networking failed\n");
return EXIT_FAILURE;
}
try {
int ret = AppInitRPC(argc, argv);
if (ret != CONTINUE_EXECUTION)
return ret;
}
catch (const std::exception& e) {
PrintExceptionContinue(&e, "AppInitRPC()");
return EXIT_FAILURE;
} catch (...) {
PrintExceptionContinue(NULL, "AppInitRPC()");
return EXIT_FAILURE;
}
int ret = EXIT_FAILURE;
try {
ret = CommandLineRPC(argc, argv);
}
catch (const std::exception& e) {
PrintExceptionContinue(&e, "CommandLineRPC()");
} catch (...) {
PrintExceptionContinue(NULL, "CommandLineRPC()");
}
return ret;
}
//fixme: (HIGH)
//Super gross workaround - for some reason our macos build keeps failing to provide '___cpu_model' symbol, so we just define it ourselves as a workaround until we can fix the issue.
#ifdef MAC_OSX
#include "llvm-cpumodel-hack.cpp"
#endif
<|endoftext|>
|
<commit_before>// Copyright 2018 The SwiftShader 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.
#ifndef VK_DEVICE_HPP_
#define VK_DEVICE_HPP_
#include "VkObject.hpp"
#include "Device/LRUCache.hpp"
#include "Reactor/Routine.hpp"
#include <memory>
#include <mutex>
namespace marl
{
class Scheduler;
}
namespace sw
{
class Blitter;
}
namespace vk
{
class PhysicalDevice;
class Queue;
class Device
{
public:
static constexpr VkSystemAllocationScope GetAllocationScope() { return VK_SYSTEM_ALLOCATION_SCOPE_DEVICE; }
Device(const VkDeviceCreateInfo* pCreateInfo, void* mem, PhysicalDevice *physicalDevice, const VkPhysicalDeviceFeatures *enabledFeatures, const std::shared_ptr<marl::Scheduler>& scheduler);
void destroy(const VkAllocationCallbacks* pAllocator);
static size_t ComputeRequiredAllocationSize(const VkDeviceCreateInfo* pCreateInfo);
bool hasExtension(const char* extensionName) const;
VkQueue getQueue(uint32_t queueFamilyIndex, uint32_t queueIndex) const;
VkResult waitForFences(uint32_t fenceCount, const VkFence* pFences, VkBool32 waitAll, uint64_t timeout);
VkResult waitIdle();
void getDescriptorSetLayoutSupport(const VkDescriptorSetLayoutCreateInfo* pCreateInfo,
VkDescriptorSetLayoutSupport* pSupport) const;
PhysicalDevice *getPhysicalDevice() const { return physicalDevice; }
void updateDescriptorSets(uint32_t descriptorWriteCount, const VkWriteDescriptorSet* pDescriptorWrites,
uint32_t descriptorCopyCount, const VkCopyDescriptorSet* pDescriptorCopies);
const VkPhysicalDeviceFeatures &getEnabledFeatures() const { return enabledFeatures; }
sw::Blitter* getBlitter() const { return blitter.get(); }
class SamplingRoutineCache
{
public:
SamplingRoutineCache() : cache(1024) {}
~SamplingRoutineCache() {}
struct Key
{
uint32_t instruction;
uint32_t sampler;
uint32_t imageView;
inline bool operator == (const Key& rhs) const;
inline bool operator < (const Key& rhs) const;
struct Hash
{
inline std::size_t operator()(const Key& key) const noexcept;
};
};
std::shared_ptr<rr::Routine> query(const Key& key) const;
void add(const Key& key, const std::shared_ptr<rr::Routine>& routine);
rr::Routine* queryConst(const Key& key) const;
void updateConstCache();
private:
sw::LRUConstCache<Key, std::shared_ptr<rr::Routine>, Key::Hash> cache;
};
SamplingRoutineCache* getSamplingRoutineCache() const;
std::mutex& getSamplingRoutineCacheMutex();
rr::Routine* findInConstCache(const SamplingRoutineCache::Key& key) const;
void updateSamplingRoutineConstCache();
private:
PhysicalDevice *const physicalDevice = nullptr;
Queue *const queues = nullptr;
uint32_t queueCount = 0;
std::unique_ptr<sw::Blitter> blitter;
std::unique_ptr<SamplingRoutineCache> samplingRoutineCache;
std::mutex samplingRoutineCacheMutex;
uint32_t enabledExtensionCount = 0;
typedef char ExtensionName[VK_MAX_EXTENSION_NAME_SIZE];
ExtensionName* extensions = nullptr;
const VkPhysicalDeviceFeatures enabledFeatures = {};
std::shared_ptr<marl::Scheduler> scheduler;
};
using DispatchableDevice = DispatchableObject<Device, VkDevice>;
static inline Device* Cast(VkDevice object)
{
return DispatchableDevice::Cast(object);
}
inline bool vk::Device::SamplingRoutineCache::Key::operator == (const Key& rhs) const
{
return instruction == rhs.instruction && sampler == rhs.sampler && imageView == rhs.imageView;
}
inline bool vk::Device::SamplingRoutineCache::Key::operator < (const Key& rhs) const
{
return std::tie(instruction, sampler, imageView) < std::tie(rhs.instruction, rhs.sampler, rhs.imageView);
}
inline std::size_t vk::Device::SamplingRoutineCache::Key::Hash::operator() (const Key& key) const noexcept
{
// Combine three 32-bit integers into a 64-bit hash.
// 2642239 is the largest prime which when cubed is smaller than 2^64.
uint64_t hash = key.instruction;
hash = (hash * 2642239) ^ key.sampler;
hash = (hash * 2642239) ^ key.imageView;
return static_cast<std::size_t>(hash); // Truncates to 32-bits on 32-bit platforms.
}
} // namespace vk
#endif // VK_DEVICE_HPP_
<commit_msg>Remove unused SamplingRoutineCache::Key::operator<<commit_after>// Copyright 2018 The SwiftShader 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.
#ifndef VK_DEVICE_HPP_
#define VK_DEVICE_HPP_
#include "VkObject.hpp"
#include "Device/LRUCache.hpp"
#include "Reactor/Routine.hpp"
#include <memory>
#include <mutex>
namespace marl
{
class Scheduler;
}
namespace sw
{
class Blitter;
}
namespace vk
{
class PhysicalDevice;
class Queue;
class Device
{
public:
static constexpr VkSystemAllocationScope GetAllocationScope() { return VK_SYSTEM_ALLOCATION_SCOPE_DEVICE; }
Device(const VkDeviceCreateInfo* pCreateInfo, void* mem, PhysicalDevice *physicalDevice, const VkPhysicalDeviceFeatures *enabledFeatures, const std::shared_ptr<marl::Scheduler>& scheduler);
void destroy(const VkAllocationCallbacks* pAllocator);
static size_t ComputeRequiredAllocationSize(const VkDeviceCreateInfo* pCreateInfo);
bool hasExtension(const char* extensionName) const;
VkQueue getQueue(uint32_t queueFamilyIndex, uint32_t queueIndex) const;
VkResult waitForFences(uint32_t fenceCount, const VkFence* pFences, VkBool32 waitAll, uint64_t timeout);
VkResult waitIdle();
void getDescriptorSetLayoutSupport(const VkDescriptorSetLayoutCreateInfo* pCreateInfo,
VkDescriptorSetLayoutSupport* pSupport) const;
PhysicalDevice *getPhysicalDevice() const { return physicalDevice; }
void updateDescriptorSets(uint32_t descriptorWriteCount, const VkWriteDescriptorSet* pDescriptorWrites,
uint32_t descriptorCopyCount, const VkCopyDescriptorSet* pDescriptorCopies);
const VkPhysicalDeviceFeatures &getEnabledFeatures() const { return enabledFeatures; }
sw::Blitter* getBlitter() const { return blitter.get(); }
class SamplingRoutineCache
{
public:
SamplingRoutineCache() : cache(1024) {}
~SamplingRoutineCache() {}
struct Key
{
uint32_t instruction;
uint32_t sampler;
uint32_t imageView;
inline bool operator == (const Key& rhs) const;
struct Hash
{
inline std::size_t operator()(const Key& key) const noexcept;
};
};
std::shared_ptr<rr::Routine> query(const Key& key) const;
void add(const Key& key, const std::shared_ptr<rr::Routine>& routine);
rr::Routine* queryConst(const Key& key) const;
void updateConstCache();
private:
sw::LRUConstCache<Key, std::shared_ptr<rr::Routine>, Key::Hash> cache;
};
SamplingRoutineCache* getSamplingRoutineCache() const;
std::mutex& getSamplingRoutineCacheMutex();
rr::Routine* findInConstCache(const SamplingRoutineCache::Key& key) const;
void updateSamplingRoutineConstCache();
private:
PhysicalDevice *const physicalDevice = nullptr;
Queue *const queues = nullptr;
uint32_t queueCount = 0;
std::unique_ptr<sw::Blitter> blitter;
std::unique_ptr<SamplingRoutineCache> samplingRoutineCache;
std::mutex samplingRoutineCacheMutex;
uint32_t enabledExtensionCount = 0;
typedef char ExtensionName[VK_MAX_EXTENSION_NAME_SIZE];
ExtensionName* extensions = nullptr;
const VkPhysicalDeviceFeatures enabledFeatures = {};
std::shared_ptr<marl::Scheduler> scheduler;
};
using DispatchableDevice = DispatchableObject<Device, VkDevice>;
static inline Device* Cast(VkDevice object)
{
return DispatchableDevice::Cast(object);
}
inline bool vk::Device::SamplingRoutineCache::Key::operator == (const Key& rhs) const
{
return instruction == rhs.instruction && sampler == rhs.sampler && imageView == rhs.imageView;
}
inline std::size_t vk::Device::SamplingRoutineCache::Key::Hash::operator() (const Key& key) const noexcept
{
// Combine three 32-bit integers into a 64-bit hash.
// 2642239 is the largest prime which when cubed is smaller than 2^64.
uint64_t hash = key.instruction;
hash = (hash * 2642239) ^ key.sampler;
hash = (hash * 2642239) ^ key.imageView;
return static_cast<std::size_t>(hash); // Truncates to 32-bits on 32-bit platforms.
}
} // namespace vk
#endif // VK_DEVICE_HPP_
<|endoftext|>
|
<commit_before>#include <iostream>
#include <exception>
#include <fstream>
#include <sstream>
#include <regex>
#include "cli_utils.h"
// This file has utilities employed by the glnexus applet.
using namespace std;
namespace GLnexus {
namespace cli {
namespace utils {
// Parse a range like chr1:1000-2000. The item can also just be the name of a
// contig, in which case it gets mapped to the contig's full length.
bool parse_range(const vector<pair<string,size_t> >& contigs,
const string& range_txt, range& ans) {
static regex re_range("([^:]+):([0-9,]+)-([0-9,]+)");
string contig = range_txt;
size_t beg=1, end=0;
smatch sm;
if (regex_match(range_txt, sm, re_range)) {
assert(sm.size() == 4);
contig = sm[1];
string sbeg = sm[2], send = sm[3];
sbeg.erase(std::remove(sbeg.begin(), sbeg.end(), ','), sbeg.end());
send.erase(std::remove(send.begin(), send.end(), ','), send.end());
beg = strtoul(sbeg.c_str(), nullptr, 10);
end = strtoul(send.c_str(), nullptr, 10);
}
int rid=0;
while (rid < contigs.size() && contig != contigs[rid].first) rid++;
if (rid >= contigs.size()) {
return false;
}
end = end>0 ? end : contigs[rid].second;
if (beg < 1 || beg >= end) {
return false;
}
ans = range(rid, beg-1, end);
return true;
}
// parse a comma-separated list of ranges
bool parse_ranges(const vector<pair<string,size_t> >& contigs,
const string& ranges, vector<range>& ans) {
ans.clear();
string item;
stringstream ss(ranges);
while (std::getline(ss, item, ',')) {
range range(-1,-1,-1);
if (!parse_range(contigs, item, range)) {
return false;
}
ans.push_back(range);
}
return true;
}
Status LoadYAMLFile(const string& filename, YAML::Node &node) {
if (filename.size() == 0)
return Status::Invalid("The YAML file must be specified");
try {
node = YAML::LoadFile(filename);
} catch (exception &e) {
return Status::Invalid("Error loading yaml file ", filename);
}
if (node.IsNull())
return Status::NotFound("bad YAML file", filename);
return Status::OK();
}
Status yaml_of_contigs(const std::vector<std::pair<std::string,size_t> > &contigs,
YAML::Emitter &yaml) {
yaml << YAML::BeginSeq;
for (const std::pair<string,size_t> &pr : contigs) {
yaml << YAML::BeginMap;
yaml << YAML::Key << "name";
yaml << YAML::Value << pr.first;
yaml << YAML::Key << "size";
yaml << YAML::Value << pr.second;
yaml << YAML::EndMap;
}
yaml << YAML::EndSeq;
return Status::OK();
}
Status contigs_of_yaml(const YAML::Node& yaml,
std::vector<std::pair<std::string,size_t> > &contigs) {
contigs.clear();
// read contigs
if (!yaml.IsSequence()) {
return Status::Invalid("contigs should be a yaml sequence");
}
for (auto p = yaml.begin(); p != yaml.end(); ++p) {
const std::string name = (*p)["name"].as<std::string>();
size_t size = (*p)["size"].as<size_t>();
contigs.push_back(make_pair(name, size));
}
return Status::OK();
}
// We write the stream as follows:
//
// ---
// contigs
// ---
// allele 1
// ---
// allele 2
// ---
// etc.
// allele N
// ...
//
// Each element is transformed to YAML, and then written to the output stream.
// This generates the document in pieces, while keeping it valid YAML.
Status yaml_stream_of_discovered_alleles(const std::vector<std::pair<std::string,size_t> > &contigs,
const discovered_alleles &dsals,
std::ostream &os) {
Status s;
// write the contigs
{
os << "---" << endl;
YAML::Emitter yaml;
S(yaml_of_contigs(contigs, yaml));
os << yaml.c_str() << endl;
}
// Write alleles
for (auto &pr : dsals) {
os << "---" << endl;
YAML::Emitter yaml;
S(yaml_of_one_discovered_allele(pr.first, pr.second, contigs, yaml));
os << yaml.c_str() << endl;
}
// special notation for end-of-file
os << "..." << endl;
return Status::OK();
}
static string yaml_begin_doc = "---";
static string yaml_end_doc_list = "...";
// Verify the document begins with '---' line. Move the stream position to the next line.
static Status yaml_verify_begin_doc_list(std::istream &is) {
try {
string marker;
std::getline(is, marker);
if (marker != yaml_begin_doc)
return Status::Invalid("document does not start with `---`");
return Status::OK();
} catch (exception e) {
string err = e.what();
return Status::Failure("exception caught in yaml_verify_begin_doc_list: ", err);
}
}
// Verify that we have reached the end of the file
static Status yaml_verify_eof(std::istream &is) {
try {
// The end-of-file flag is lit up only after reading past the
// end of file
char c;
is.get(c);
if (!is.eof()) {
return Status::Invalid("Found YAML end-of-document marker, but there is unread data");
}
return Status::OK();
} catch (exception e) {
string err = e.what();
return Status::Failure("exception caught in yaml_verify_eof: ", err);
}
}
// In a YAML document built as a of document list, get the next document.
//
// Notes:
// - Catch any exceptions, and convert to bad status
static Status yaml_get_next_document(std::istream &is,
YAML::Node &ans,
string& next_marker) {
try {
stringstream ss;
while (is.good() && !is.eof()) {
string line;
std::getline(is, line);
if (line.size() == 3) {
// check if we reached the end of this top level document
if (line == yaml_begin_doc ||
line == yaml_end_doc_list) {
// We have the entire document in memory. Convert to
// a YAML node and return.
next_marker = line;
ans = std::move(YAML::Load(ss.str()));
return Status::OK();
}
}
ss.write(line.c_str(), line.size());
ss.write("\n", 1);
}
if (!is.good())
return Status::IOError("reading yaml stream");
return Status::Invalid("premature end of document, did not find end-of-document marker");
} catch (exception e) {
string err = e.what();
return Status::Failure("exception caught in yaml_get_next_document: ", err);
}
}
Status discovered_alleles_of_yaml_stream(std::istream &is,
std::vector<std::pair<std::string,size_t> > &contigs,
discovered_alleles &dsals) {
Status s;
string next_marker;
YAML::Node doc;
contigs.clear();
dsals.clear();
S(yaml_verify_begin_doc_list(is));
// The first top-level document is the contigs
S(yaml_get_next_document(is, doc, next_marker));
S(contigs_of_yaml(doc, contigs));
// All other documents are discovered-alleles
while (next_marker != yaml_end_doc_list) {
S(yaml_get_next_document(is, doc, next_marker));
allele allele(range(-1,-1,-1), "A");
discovered_allele_info ainfo;
S(one_discovered_allele_of_yaml(doc, contigs, allele, ainfo));
dsals[allele] = ainfo;
}
S(yaml_verify_eof(is));
if (contigs.size() == 0)
return Status::Invalid("Empty contigs");
return Status::OK();
}
// Serialize the unified sites to yaml format.
//
Status yaml_stream_of_unified_sites(const std::vector<unified_site> &sites,
const std::vector<std::pair<std::string,size_t> > &contigs,
std::ostream &os) {
Status s;
for (auto& u_site : sites) {
os << "---" << endl;
YAML::Emitter yaml;
S(u_site.yaml(contigs, yaml));
os << yaml.c_str() << endl;
}
// special notation for end-of-file
os << "..." << endl;
return Status::OK();
}
// Load the unified-sites from a file in yaml format.
//
Status unified_sites_of_yaml_stream(std::istream &is,
const std::vector<std::pair<std::string,size_t> > &contigs,
std::vector<unified_site> &sites) {
Status s;
string next_marker;
sites.clear();
S(yaml_verify_begin_doc_list(is));
// Read a list of documents representing unified-sites
do {
YAML::Node doc;
S(yaml_get_next_document(is, doc, next_marker));
unified_site u_site(range(-1, -1, -1));
S(unified_site::of_yaml(doc, contigs, u_site));
sites.push_back(u_site);
} while (next_marker != yaml_end_doc_list);
S(yaml_verify_eof(is));
return Status::OK();
}
// Load first file
Status merge_discovered_allele_files(std::shared_ptr<spdlog::logger> logger,
const vector<string> &filenames,
vector<pair<string,size_t>> &contigs,
discovered_alleles &dsals) {
Status s;
if (filenames.size() == 0)
return Status::Invalid("no discovered allele files provided");
contigs.clear();
dsals.clear();
// Load the first file
const string& first_file = filenames[0];
{
std::ifstream ifs(first_file.c_str());
S(discovered_alleles_of_yaml_stream(ifs, contigs, dsals));
logger->info() << "loaded " << dsals.size() << " alleles from " << first_file;
ifs.close();
}
if (filenames.size() == 1)
return Status::OK();
// Load the rest of the files, and merge
for (auto it = filenames.begin() + 1; it != filenames.end(); ++it) {
vector<pair<string,size_t>> contigs2;
discovered_alleles dsals2;
const string &crnt_file = *it;
std::ifstream ifs(crnt_file.c_str());
S(discovered_alleles_of_yaml_stream(ifs, contigs2, dsals2));
logger->info() << "loaded " << dsals2.size() << " alleles from " << crnt_file;
ifs.close();
// verify that the contigs are the same
if (contigs != contigs2) {
return Status::Invalid("The contigs are different between", first_file + " " + crnt_file);
}
S(merge_discovered_alleles(dsals2, dsals));
}
return Status::OK();
}
Status find_containing_range(const std::set<range> &ranges,
const range &pos,
range &ans) {
if (ranges.size() == 0) {
return Status::NotFound();
}
// The returned value here is the first element that is
// greater or equal to [pos].
auto it = ranges.lower_bound(pos);
if (it == ranges.end() || !it->contains(pos)) {
// we landed one range after the one we need
if (it != ranges.begin()) {
it = std::prev(it);
}
}
if (it->contains(pos)) {
// we got the right range
ans = *it;
return Status::OK();
}
return Status::NotFound();
}
}}}
<commit_msg>cli_utils::discovered_alleles_of_yaml_stream: deallocate YAML::Node every time<commit_after>#include <iostream>
#include <exception>
#include <fstream>
#include <sstream>
#include <regex>
#include "cli_utils.h"
// This file has utilities employed by the glnexus applet.
using namespace std;
namespace GLnexus {
namespace cli {
namespace utils {
// Parse a range like chr1:1000-2000. The item can also just be the name of a
// contig, in which case it gets mapped to the contig's full length.
bool parse_range(const vector<pair<string,size_t> >& contigs,
const string& range_txt, range& ans) {
static regex re_range("([^:]+):([0-9,]+)-([0-9,]+)");
string contig = range_txt;
size_t beg=1, end=0;
smatch sm;
if (regex_match(range_txt, sm, re_range)) {
assert(sm.size() == 4);
contig = sm[1];
string sbeg = sm[2], send = sm[3];
sbeg.erase(std::remove(sbeg.begin(), sbeg.end(), ','), sbeg.end());
send.erase(std::remove(send.begin(), send.end(), ','), send.end());
beg = strtoul(sbeg.c_str(), nullptr, 10);
end = strtoul(send.c_str(), nullptr, 10);
}
int rid=0;
while (rid < contigs.size() && contig != contigs[rid].first) rid++;
if (rid >= contigs.size()) {
return false;
}
end = end>0 ? end : contigs[rid].second;
if (beg < 1 || beg >= end) {
return false;
}
ans = range(rid, beg-1, end);
return true;
}
// parse a comma-separated list of ranges
bool parse_ranges(const vector<pair<string,size_t> >& contigs,
const string& ranges, vector<range>& ans) {
ans.clear();
string item;
stringstream ss(ranges);
while (std::getline(ss, item, ',')) {
range range(-1,-1,-1);
if (!parse_range(contigs, item, range)) {
return false;
}
ans.push_back(range);
}
return true;
}
Status LoadYAMLFile(const string& filename, YAML::Node &node) {
if (filename.size() == 0)
return Status::Invalid("The YAML file must be specified");
try {
node = YAML::LoadFile(filename);
} catch (exception &e) {
return Status::Invalid("Error loading yaml file ", filename);
}
if (node.IsNull())
return Status::NotFound("bad YAML file", filename);
return Status::OK();
}
Status yaml_of_contigs(const std::vector<std::pair<std::string,size_t> > &contigs,
YAML::Emitter &yaml) {
yaml << YAML::BeginSeq;
for (const std::pair<string,size_t> &pr : contigs) {
yaml << YAML::BeginMap;
yaml << YAML::Key << "name";
yaml << YAML::Value << pr.first;
yaml << YAML::Key << "size";
yaml << YAML::Value << pr.second;
yaml << YAML::EndMap;
}
yaml << YAML::EndSeq;
return Status::OK();
}
Status contigs_of_yaml(const YAML::Node& yaml,
std::vector<std::pair<std::string,size_t> > &contigs) {
contigs.clear();
// read contigs
if (!yaml.IsSequence()) {
return Status::Invalid("contigs should be a yaml sequence");
}
for (auto p = yaml.begin(); p != yaml.end(); ++p) {
const std::string name = (*p)["name"].as<std::string>();
size_t size = (*p)["size"].as<size_t>();
contigs.push_back(make_pair(name, size));
}
return Status::OK();
}
// We write the stream as follows:
//
// ---
// contigs
// ---
// allele 1
// ---
// allele 2
// ---
// etc.
// allele N
// ...
//
// Each element is transformed to YAML, and then written to the output stream.
// This generates the document in pieces, while keeping it valid YAML.
Status yaml_stream_of_discovered_alleles(const std::vector<std::pair<std::string,size_t> > &contigs,
const discovered_alleles &dsals,
std::ostream &os) {
Status s;
// write the contigs
{
os << "---" << endl;
YAML::Emitter yaml;
S(yaml_of_contigs(contigs, yaml));
os << yaml.c_str() << endl;
}
// Write alleles
for (auto &pr : dsals) {
os << "---" << endl;
YAML::Emitter yaml;
S(yaml_of_one_discovered_allele(pr.first, pr.second, contigs, yaml));
os << yaml.c_str() << endl;
}
// special notation for end-of-file
os << "..." << endl;
return Status::OK();
}
static string yaml_begin_doc = "---";
static string yaml_end_doc_list = "...";
// Verify the document begins with '---' line. Move the stream position to the next line.
static Status yaml_verify_begin_doc_list(std::istream &is) {
try {
string marker;
std::getline(is, marker);
if (marker != yaml_begin_doc)
return Status::Invalid("document does not start with `---`");
return Status::OK();
} catch (exception e) {
string err = e.what();
return Status::Failure("exception caught in yaml_verify_begin_doc_list: ", err);
}
}
// Verify that we have reached the end of the file
static Status yaml_verify_eof(std::istream &is) {
try {
// The end-of-file flag is lit up only after reading past the
// end of file
char c;
is.get(c);
if (!is.eof()) {
return Status::Invalid("Found YAML end-of-document marker, but there is unread data");
}
return Status::OK();
} catch (exception e) {
string err = e.what();
return Status::Failure("exception caught in yaml_verify_eof: ", err);
}
}
// In a YAML document built as a of document list, get the next document.
//
// Notes:
// - Catch any exceptions, and convert to bad status
static Status yaml_get_next_document(std::istream &is,
YAML::Node &ans,
string& next_marker) {
try {
stringstream ss;
while (is.good() && !is.eof()) {
string line;
std::getline(is, line);
if (line.size() == 3) {
// check if we reached the end of this top level document
if (line == yaml_begin_doc ||
line == yaml_end_doc_list) {
// We have the entire document in memory. Convert to
// a YAML node and return.
next_marker = line;
ans = std::move(YAML::Load(ss.str()));
return Status::OK();
}
}
ss.write(line.c_str(), line.size());
ss.write("\n", 1);
}
if (!is.good())
return Status::IOError("reading yaml stream");
return Status::Invalid("premature end of document, did not find end-of-document marker");
} catch (exception e) {
string err = e.what();
return Status::Failure("exception caught in yaml_get_next_document: ", err);
}
}
Status discovered_alleles_of_yaml_stream(std::istream &is,
std::vector<std::pair<std::string,size_t> > &contigs,
discovered_alleles &dsals) {
Status s;
string next_marker;
contigs.clear();
dsals.clear();
S(yaml_verify_begin_doc_list(is));
// The first top-level document is the contigs
{
YAML::Node doc;
S(yaml_get_next_document(is, doc, next_marker));
S(contigs_of_yaml(doc, contigs));
}
// All other documents are discovered-alleles
while (next_marker != yaml_end_doc_list) {
YAML::Node doc;
S(yaml_get_next_document(is, doc, next_marker));
allele allele(range(-1,-1,-1), "A");
discovered_allele_info ainfo;
S(one_discovered_allele_of_yaml(doc, contigs, allele, ainfo));
dsals[allele] = ainfo;
}
S(yaml_verify_eof(is));
if (contigs.size() == 0)
return Status::Invalid("Empty contigs");
return Status::OK();
}
// Serialize the unified sites to yaml format.
//
Status yaml_stream_of_unified_sites(const std::vector<unified_site> &sites,
const std::vector<std::pair<std::string,size_t> > &contigs,
std::ostream &os) {
Status s;
for (auto& u_site : sites) {
os << "---" << endl;
YAML::Emitter yaml;
S(u_site.yaml(contigs, yaml));
os << yaml.c_str() << endl;
}
// special notation for end-of-file
os << "..." << endl;
return Status::OK();
}
// Load the unified-sites from a file in yaml format.
//
Status unified_sites_of_yaml_stream(std::istream &is,
const std::vector<std::pair<std::string,size_t> > &contigs,
std::vector<unified_site> &sites) {
Status s;
string next_marker;
sites.clear();
S(yaml_verify_begin_doc_list(is));
// Read a list of documents representing unified-sites
do {
YAML::Node doc;
S(yaml_get_next_document(is, doc, next_marker));
unified_site u_site(range(-1, -1, -1));
S(unified_site::of_yaml(doc, contigs, u_site));
sites.push_back(u_site);
} while (next_marker != yaml_end_doc_list);
S(yaml_verify_eof(is));
return Status::OK();
}
// Load first file
Status merge_discovered_allele_files(std::shared_ptr<spdlog::logger> logger,
const vector<string> &filenames,
vector<pair<string,size_t>> &contigs,
discovered_alleles &dsals) {
Status s;
if (filenames.size() == 0)
return Status::Invalid("no discovered allele files provided");
contigs.clear();
dsals.clear();
// Load the first file
const string& first_file = filenames[0];
{
std::ifstream ifs(first_file.c_str());
S(discovered_alleles_of_yaml_stream(ifs, contigs, dsals));
logger->info() << "loaded " << dsals.size() << " alleles from " << first_file;
ifs.close();
}
if (filenames.size() == 1)
return Status::OK();
// Load the rest of the files, and merge
for (auto it = filenames.begin() + 1; it != filenames.end(); ++it) {
vector<pair<string,size_t>> contigs2;
discovered_alleles dsals2;
const string &crnt_file = *it;
std::ifstream ifs(crnt_file.c_str());
S(discovered_alleles_of_yaml_stream(ifs, contigs2, dsals2));
logger->info() << "loaded " << dsals2.size() << " alleles from " << crnt_file;
ifs.close();
// verify that the contigs are the same
if (contigs != contigs2) {
return Status::Invalid("The contigs are different between", first_file + " " + crnt_file);
}
S(merge_discovered_alleles(dsals2, dsals));
}
return Status::OK();
}
Status find_containing_range(const std::set<range> &ranges,
const range &pos,
range &ans) {
if (ranges.size() == 0) {
return Status::NotFound();
}
// The returned value here is the first element that is
// greater or equal to [pos].
auto it = ranges.lower_bound(pos);
if (it == ranges.end() || !it->contains(pos)) {
// we landed one range after the one we need
if (it != ranges.begin()) {
it = std::prev(it);
}
}
if (it->contains(pos)) {
// we got the right range
ans = *it;
return Status::OK();
}
return Status::NotFound();
}
}}}
<|endoftext|>
|
<commit_before>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999 The Apache Software Foundation. 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. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/**
*
* @author Scott Boag (scott_boag@lotus.com)
* @author David N. Bertoni (david_n_bertoni@lotus.com)
*/
// Class header file.
#include "NodeSorter.hpp"
#include <PlatformSupport/DOMStringHelper.hpp>
#include <PlatformSupport/DoubleSupport.hpp>
#include <XPath/XPath.hpp>
NodeSorter::NodeSorter(XPathExecutionContext& executionContext) :
m_executionContext(executionContext),
m_keys()
{
}
NodeSorter::~NodeSorter()
{
}
void
NodeSorter::sort(
NodeVectorType& v,
const NodeSortKeyVectorType& keys)
{
#if !defined(XALAN_NO_NAMESPACES)
using std::stable_sort;
#endif
m_keys = keys;
NodeSortKeyCompare theComparer(m_executionContext,
v,
keys);
// Use the stl sort algorithm, which will use our compare functor,
// which returns true if first less than second
stable_sort(v.begin(),
v.end(),
theComparer);
}
void
NodeSorter::sort(
MutableNodeRefList& theList,
const NodeSortKeyVectorType& keys)
{
const unsigned int theLength = theList.getLength();
// Copy the nodes to a vector...
NodeVectorType theNodes(theLength);
unsigned int i = 0;
for (; i < theLength; ++i)
{
theNodes[i] = theList.item(i);
}
sort(theNodes,
keys);
assert(theNodes.size() ==
static_cast<NodeVectorType::size_type>(theLength));
theList.clear();
for (i = 0; i < theLength; ++i)
{
theList.addNode(theNodes[i]);
}
assert(theList.getLength() == theLength);
}
NodeSorter::NodeSortKeyCompare::result_type
NodeSorter::NodeSortKeyCompare::operator()(
first_argument_type theLHS,
second_argument_type theRHS,
unsigned int theKeyIndex) const
{
assert(theKeyIndex < UINT_MAX);
result_type theResult = false;
const NodeSortKey& theKey = m_nodeSortKeys[theKeyIndex];
const XPath& xpath = theKey.getSelectPattern();
XObject* r1 = xpath.execute(theLHS, theKey.getPrefixResolver(), NodeRefList(), m_executionContext);
XObject* r2 = xpath.execute(theRHS, theKey.getPrefixResolver(), NodeRefList(), m_executionContext);
// Compare as numbers
if(theKey.getTreatAsNumbers() == true)
{
double n1Num = r1->num();
double n2Num = r2->num();
if (DoubleSupport::isNaN(n1Num))
n1Num = 0.0;
if (DoubleSupport::isNaN(n2Num))
n2Num = 0.0;
if(n1Num == n2Num &&
(theKeyIndex + 1 ) < m_nodeSortKeys.size())
{
theResult = operator()(theLHS, theRHS, theKeyIndex + 1);
}
else
{
const double diff = n1Num - n2Num;
theResult = diff < 0.0 ? true : false;
if (theKey.getDescending() == true)
{
theResult = !theResult;
}
}
}
// Compare as strings
else
{
const int theCompareResult = compare(r1->str(), r2->str());
if(0 == theCompareResult)
{
if ((theKeyIndex + 1 ) < m_nodeSortKeys.size())
{
theResult = operator()(theLHS, theRHS, theKeyIndex + 1);
}
}
else
{
theResult = theCompareResult < 0 ? true : false;
if (theKey.getDescending() == true)
{
theResult = !theResult;
}
}
}
return theResult;
}
<commit_msg>Compare strings according to collation sequence.<commit_after>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999 The Apache Software Foundation. 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. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/**
*
* @author Scott Boag (scott_boag@lotus.com)
* @author David N. Bertoni (david_n_bertoni@lotus.com)
*/
// Class header file.
#include "NodeSorter.hpp"
#include <PlatformSupport/DOMStringHelper.hpp>
#include <PlatformSupport/DoubleSupport.hpp>
#include <XPath/XPath.hpp>
NodeSorter::NodeSorter(XPathExecutionContext& executionContext) :
m_executionContext(executionContext),
m_keys()
{
}
NodeSorter::~NodeSorter()
{
}
void
NodeSorter::sort(
NodeVectorType& v,
const NodeSortKeyVectorType& keys)
{
#if !defined(XALAN_NO_NAMESPACES)
using std::stable_sort;
#endif
m_keys = keys;
NodeSortKeyCompare theComparer(m_executionContext,
v,
keys);
// Use the stl sort algorithm, which will use our compare functor,
// which returns true if first less than second
stable_sort(v.begin(),
v.end(),
theComparer);
}
void
NodeSorter::sort(
MutableNodeRefList& theList,
const NodeSortKeyVectorType& keys)
{
const unsigned int theLength = theList.getLength();
// Copy the nodes to a vector...
NodeVectorType theNodes(theLength);
unsigned int i = 0;
for (; i < theLength; ++i)
{
theNodes[i] = theList.item(i);
}
sort(theNodes,
keys);
assert(theNodes.size() ==
static_cast<NodeVectorType::size_type>(theLength));
theList.clear();
for (i = 0; i < theLength; ++i)
{
theList.addNode(theNodes[i]);
}
assert(theList.getLength() == theLength);
}
NodeSorter::NodeSortKeyCompare::result_type
NodeSorter::NodeSortKeyCompare::operator()(
first_argument_type theLHS,
second_argument_type theRHS,
unsigned int theKeyIndex) const
{
assert(theKeyIndex < UINT_MAX);
result_type theResult = false;
const NodeSortKey& theKey = m_nodeSortKeys[theKeyIndex];
const XPath& xpath = theKey.getSelectPattern();
XObject* r1 = xpath.execute(theLHS, theKey.getPrefixResolver(), NodeRefList(), m_executionContext);
XObject* r2 = xpath.execute(theRHS, theKey.getPrefixResolver(), NodeRefList(), m_executionContext);
// Compare as numbers
if(theKey.getTreatAsNumbers() == true)
{
double n1Num = r1->num();
double n2Num = r2->num();
if (DoubleSupport::isNaN(n1Num))
n1Num = 0.0;
if (DoubleSupport::isNaN(n2Num))
n2Num = 0.0;
if(n1Num == n2Num &&
(theKeyIndex + 1 ) < m_nodeSortKeys.size())
{
theResult = operator()(theLHS, theRHS, theKeyIndex + 1);
}
else
{
const double diff = n1Num - n2Num;
theResult = diff < 0.0 ? true : false;
if (theKey.getDescending() == true)
{
theResult = !theResult;
}
}
}
// Compare as strings
else
{
const int theCompareResult = collationCompare(r1->str(), r2->str());
if(0 == theCompareResult)
{
if ((theKeyIndex + 1 ) < m_nodeSortKeys.size())
{
theResult = operator()(theLHS, theRHS, theKeyIndex + 1);
}
}
else
{
theResult = theCompareResult < 0 ? true : false;
if (theKey.getDescending() == true)
{
theResult = !theResult;
}
}
}
return theResult;
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkImageAccumulate.cxx
Language: C++
Date: $Date$
Version: $Revision$
Thanks: Thanks to C. Charles Law who developed this class.
Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen
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 name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
of any contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
* Modified source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
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 AUTHORS 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 "vtkImageAccumulate.h"
#include <math.h>
#include <stdlib.h>
#include "vtkObjectFactory.h"
//----------------------------------------------------------------------------
vtkImageAccumulate* vtkImageAccumulate::New()
{
// First try to create the object from the vtkObjectFactory
vtkObject* ret = vtkObjectFactory::CreateInstance("vtkImageAccumulate");
if(ret)
{
return (vtkImageAccumulate*)ret;
}
// If the factory was unable to create the object, then create it here.
return new vtkImageAccumulate;
}
//----------------------------------------------------------------------------
// Constructor sets default values
vtkImageAccumulate::vtkImageAccumulate()
{
int idx;
for (idx = 0; idx < 3; ++idx)
{
this->ComponentSpacing[idx] = 1.0;
this->ComponentOrigin[idx] = 0.0;
this->ComponentExtent[idx*2] = 0;
this->ComponentExtent[idx*2+1] = 0;
}
this->ComponentExtent[1] = 255;
this->StencilFunction = NULL;
this->ClippingExtents = NULL;
this->ReverseStencil = 0;
this->Min[0] = this->Min[1] = this->Min[2] = 0.0;
this->Max[0] = this->Max[1] = this->Max[2] = 0.0;
this->Mean[0] = this->Mean[1] = this->Mean[2] = 0.0;
this->PixelCount = 0;
}
//----------------------------------------------------------------------------
vtkImageAccumulate::~vtkImageAccumulate()
{
this->SetStencilFunction(NULL);
this->SetClippingExtents(NULL);
}
//----------------------------------------------------------------------------
void vtkImageAccumulate::SetComponentExtent(int extent[6])
{
int idx, modified = 0;
for (idx = 0; idx < 6; ++idx)
{
if (this->ComponentExtent[idx] != extent[idx])
{
this->ComponentExtent[idx] = extent[idx];
this->Modified();
}
}
if (modified)
{
this->Modified();
}
}
//----------------------------------------------------------------------------
void vtkImageAccumulate::SetComponentExtent(int minX, int maxX,
int minY, int maxY,
int minZ, int maxZ)
{
int extent[6];
extent[0] = minX; extent[1] = maxX;
extent[2] = minY; extent[3] = maxY;
extent[4] = minZ; extent[5] = maxZ;
this->SetComponentExtent(extent);
}
//----------------------------------------------------------------------------
void vtkImageAccumulate::GetComponentExtent(int extent[6])
{
int idx;
for (idx = 0; idx < 6; ++idx)
{
extent[idx] = this->ComponentExtent[idx];
}
}
//----------------------------------------------------------------------------
// This templated function executes the filter for any type of data.
template <class T>
static void vtkImageAccumulateExecute(vtkImageAccumulate *self,
vtkImageData *inData, T *inPtr,
vtkImageData *outData, int *outPtr,
double Min[3],
double Max[3],
double Mean[3],
long int *PixelCount)
{
int idX, idY, idZ, idxC;
int r1, r2, cr1, cr2, iter, rval;
int min0, max0, min1, max1, min2, max2;
int inInc0, inInc1, inInc2;
T *tempPtr;
int *outPtrC;
int numC, outIdx, *outExtent, *outIncs;
float *origin, *spacing;
unsigned long count = 0;
unsigned long target;
// variables used to compute statistics (filter handles max 3 components)
double sum[3];
sum[0] = sum[1] = sum[2] = 0.0;
Min[0] = Min[1] = Min[2] = VTK_DOUBLE_MAX;
Max[0] = Max[1] = Max[2] = VTK_DOUBLE_MIN;
*PixelCount = 0;
vtkImageClippingExtents *clippingExtents = self->GetClippingExtents();
// Zero count in every bin
outData->GetExtent(min0, max0, min1, max1, min2, max2);
memset((void *)outPtr, 0,
(max0-min0+1)*(max1-min1+1)*(max2-min2+1)*sizeof(int));
// Get information to march through data
numC = inData->GetNumberOfScalarComponents();
inData->GetUpdateExtent(min0, max0, min1, max1, min2, max2);
inData->GetIncrements(inInc0, inInc1, inInc2);
outExtent = outData->GetExtent();
outIncs = outData->GetIncrements();
origin = outData->GetOrigin();
spacing = outData->GetSpacing();
target = (unsigned long)((max2 - min2 + 1)*(max1 - min1 +1)/50.0);
target++;
// Loop through input pixels
for (idZ = min2; idZ <= max2; idZ++)
{
for (idY = min1; idY <= max1; idY++)
{
if (!(count%target))
{
self->UpdateProgress(count/(50.0*target));
}
count++;
if (clippingExtents == NULL)
{
tempPtr = inPtr + (inInc2*(idZ - min2) +
inInc1*(idY - min1));
for (idX = min0; idX <= max0; idX++)
{
// find the bin for this pixel.
outPtrC = outPtr;
for (idxC = 0; idxC < numC; ++idxC)
{
// Gather statistics
sum[idxC]+= *tempPtr;
if (*tempPtr > Max[idxC])
Max[idxC] = *tempPtr;
else if (*tempPtr < Min[idxC])
Min[idxC] = *tempPtr;
(*PixelCount)++;
// compute the index
outIdx = (int) floor((((double)*tempPtr++ - origin[idxC]) / spacing[idxC]));
if (outIdx < outExtent[idxC*2] || outIdx > outExtent[idxC*2+1])
{
// Out of bin range
outPtrC = NULL;
break;
}
outPtrC += (outIdx - outExtent[idxC*2]) * outIncs[idxC];
}
if (outPtrC)
{
++(*outPtrC);
}
}
}
else
{
iter = 0;
cr1 = min0;
for (;;)
{
rval = clippingExtents->GetNextExtent(r1, r2, min0, max0,
idY, idZ, iter);
cr2 = r1 - 1;
if (!self->GetReverseStencil())
{
tempPtr = inPtr + (inInc2*(idZ - min2) +
inInc1*(idY - min1) +
numC*(cr1 - min0));
for (idX = cr1; idX <= cr2; idX++)
{
// find the bin for this pixel.
outPtrC = outPtr;
for (idxC = 0; idxC < numC; ++idxC)
{
// Gather statistics
sum[idxC]+= *tempPtr;
if (*tempPtr > Max[idxC])
Max[idxC] = *tempPtr;
else if (*tempPtr < Min[idxC])
Min[idxC] = *tempPtr;
(*PixelCount)++;
// compute the index
outIdx = (int) floor((((double)*tempPtr++ - origin[idxC]) / spacing[idxC]));
if (outIdx < outExtent[idxC*2] || outIdx > outExtent[idxC*2+1])
{
// Out of bin range
outPtrC = NULL;
break;
}
outPtrC += (outIdx - outExtent[idxC*2]) * outIncs[idxC];
}
if (outPtrC)
{
++(*outPtrC);
}
}
}
cr1 = r2 + 1;
// break if no foreground extents left
if (rval == 0)
{
break;
}
if (self->GetReverseStencil())
{
// do unchanged portion
tempPtr = inPtr + (inInc2*(idZ - min2) +
inInc1*(idY - min1) +
numC*(r1 - min0));
for (idX = r1; idX <= r2; idX++)
{
// find the bin for this pixel.
outPtrC = outPtr;
for (idxC = 0; idxC < numC; ++idxC)
{
// Gather statistics
sum[idxC]+= *tempPtr;
if (*tempPtr > Max[idxC])
Max[idxC] = *tempPtr;
else if (*tempPtr < Min[idxC])
Min[idxC] = *tempPtr;
(*PixelCount)++;
// compute the index
outIdx = (int) floor((((double)*tempPtr++ - origin[idxC]) / spacing[idxC]));
if (outIdx < outExtent[idxC*2] || outIdx > outExtent[idxC*2+1])
{
// Out of bin range
outPtrC = NULL;
break;
}
outPtrC += (outIdx - outExtent[idxC*2]) * outIncs[idxC];
}
if (outPtrC)
{
++(*outPtrC);
}
}
}
}
}
}
}
if (*PixelCount) // avoid the div0
{
Mean[0] = sum[0] / (double)*PixelCount;
Mean[1] = sum[1] / (double)*PixelCount;
Mean[2] = sum[2] / (double)*PixelCount;
}
else
{
Mean[0]=Mean[1]=Mean[2] = 0.0;
}
}
//----------------------------------------------------------------------------
// This method is passed a input and output Data, and executes the filter
// algorithm to fill the output from the input.
// It just executes a switch statement to call the correct function for
// the Datas data types.
void vtkImageAccumulate::ExecuteData(vtkDataObject *vtkNotUsed(out))
{
void *inPtr;
void *outPtr;
vtkImageData *inData = this->GetInput();
vtkImageData *outData = this->GetOutput();
vtkDebugMacro(<<"Executing image accumulate");
// We need to allocate our own scalars since we are overriding
// the superclasses "Execute()" method.
outData->SetExtent(outData->GetWholeExtent());
outData->AllocateScalars();
inPtr = inData->GetScalarPointerForExtent(inData->GetUpdateExtent());
outPtr = outData->GetScalarPointer();
// Components turned into x, y and z
if (this->GetInput()->GetNumberOfScalarComponents() > 3)
{
vtkErrorMacro("This filter can handle upto 3 components");
return;
}
// this filter expects that output is type int.
if (outData->GetScalarType() != VTK_INT)
{
vtkErrorMacro(<< "Execute: out ScalarType " << outData->GetScalarType()
<< " must be int\n");
return;
}
switch (inData->GetScalarType())
{
vtkTemplateMacro9(vtkImageAccumulateExecute, this,
inData, (VTK_TT *)(inPtr),
outData, (int *)(outPtr),
this->Min, this->Max,
this->Mean, &this->PixelCount);
default:
vtkErrorMacro(<< "Execute: Unknown ScalarType");
return;
}
}
//----------------------------------------------------------------------------
void vtkImageAccumulate::ExecuteInformation(vtkImageData *input,
vtkImageData *output)
{
output->SetWholeExtent(this->ComponentExtent);
output->SetOrigin(this->ComponentOrigin);
output->SetSpacing(this->ComponentSpacing);
output->SetNumberOfScalarComponents(1);
output->SetScalarType(VTK_INT);
// See if we should be setting up some clipping extents
if (this->StencilFunction)
{
if (!this->ClippingExtents)
{
this->ClippingExtents = vtkImageClippingExtents::New();
}
this->ClippingExtents->SetClippingObject(this->StencilFunction);
}
if (this->ClippingExtents)
{
this->ClippingExtents->BuildExtents(input);
}
}
//----------------------------------------------------------------------------
// Get ALL of the input.
void vtkImageAccumulate::ComputeInputUpdateExtent(int inExt[6],
int outExt[6])
{
int *wholeExtent;
outExt = outExt;
wholeExtent = this->GetInput()->GetWholeExtent();
memcpy(inExt, wholeExtent, 6*sizeof(int));
}
void vtkImageAccumulate::PrintSelf(ostream& os, vtkIndent indent)
{
vtkImageToImageFilter::PrintSelf(os,indent);
os << indent << "ComponentOrigin: ( "
<< this->ComponentOrigin[0] << ", "
<< this->ComponentOrigin[1] << ", "
<< this->ComponentOrigin[2] << " )\n";
os << indent << "ComponentSpacing: ( "
<< this->ComponentSpacing[0] << ", "
<< this->ComponentSpacing[1] << ", "
<< this->ComponentSpacing[2] << " )\n";
os << indent << "ComponentExtent: ( "
<< this->ComponentExtent[0] << "," << this->ComponentExtent[1] << " "
<< this->ComponentExtent[2] << "," << this->ComponentExtent[3] << " "
<< this->ComponentExtent[4] << "," << this->ComponentExtent[5] << " }\n";
}
<commit_msg><commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkImageAccumulate.cxx
Language: C++
Date: $Date$
Version: $Revision$
Thanks: Thanks to C. Charles Law who developed this class.
Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen
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 name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
of any contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
* Modified source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
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 AUTHORS 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 "vtkImageAccumulate.h"
#include <math.h>
#include <stdlib.h>
#include "vtkObjectFactory.h"
//----------------------------------------------------------------------------
vtkImageAccumulate* vtkImageAccumulate::New()
{
// First try to create the object from the vtkObjectFactory
vtkObject* ret = vtkObjectFactory::CreateInstance("vtkImageAccumulate");
if(ret)
{
return (vtkImageAccumulate*)ret;
}
// If the factory was unable to create the object, then create it here.
return new vtkImageAccumulate;
}
//----------------------------------------------------------------------------
// Constructor sets default values
vtkImageAccumulate::vtkImageAccumulate()
{
int idx;
for (idx = 0; idx < 3; ++idx)
{
this->ComponentSpacing[idx] = 1.0;
this->ComponentOrigin[idx] = 0.0;
this->ComponentExtent[idx*2] = 0;
this->ComponentExtent[idx*2+1] = 0;
}
this->ComponentExtent[1] = 255;
this->StencilFunction = NULL;
this->ClippingExtents = NULL;
this->ReverseStencil = 0;
this->Min[0] = this->Min[1] = this->Min[2] = 0.0;
this->Max[0] = this->Max[1] = this->Max[2] = 0.0;
this->Mean[0] = this->Mean[1] = this->Mean[2] = 0.0;
this->PixelCount = 0;
}
//----------------------------------------------------------------------------
vtkImageAccumulate::~vtkImageAccumulate()
{
this->SetStencilFunction(NULL);
this->SetClippingExtents(NULL);
}
//----------------------------------------------------------------------------
void vtkImageAccumulate::SetComponentExtent(int extent[6])
{
int idx, modified = 0;
for (idx = 0; idx < 6; ++idx)
{
if (this->ComponentExtent[idx] != extent[idx])
{
this->ComponentExtent[idx] = extent[idx];
this->Modified();
}
}
if (modified)
{
this->Modified();
}
}
//----------------------------------------------------------------------------
void vtkImageAccumulate::SetComponentExtent(int minX, int maxX,
int minY, int maxY,
int minZ, int maxZ)
{
int extent[6];
extent[0] = minX; extent[1] = maxX;
extent[2] = minY; extent[3] = maxY;
extent[4] = minZ; extent[5] = maxZ;
this->SetComponentExtent(extent);
}
//----------------------------------------------------------------------------
void vtkImageAccumulate::GetComponentExtent(int extent[6])
{
int idx;
for (idx = 0; idx < 6; ++idx)
{
extent[idx] = this->ComponentExtent[idx];
}
}
//----------------------------------------------------------------------------
// This templated function executes the filter for any type of data.
template <class T>
static void vtkImageAccumulateExecute(vtkImageAccumulate *self,
vtkImageData *inData, T *inPtr,
vtkImageData *outData, int *outPtr,
double Min[3],
double Max[3],
double Mean[3],
long int *PixelCount)
{
int idX, idY, idZ, idxC;
int r1, r2, cr1, cr2, iter, rval;
int min0, max0, min1, max1, min2, max2;
int inInc0, inInc1, inInc2;
T *tempPtr;
int *outPtrC;
int numC, outIdx, *outExtent, *outIncs;
float *origin, *spacing;
unsigned long count = 0;
unsigned long target;
// variables used to compute statistics (filter handles max 3 components)
double sum[3];
sum[0] = sum[1] = sum[2] = 0.0;
Min[0] = Min[1] = Min[2] = VTK_DOUBLE_MAX;
Max[0] = Max[1] = Max[2] = VTK_DOUBLE_MIN;
*PixelCount = 0;
vtkImageClippingExtents *clippingExtents = self->GetClippingExtents();
// Zero count in every bin
outData->GetExtent(min0, max0, min1, max1, min2, max2);
memset((void *)outPtr, 0,
(max0-min0+1)*(max1-min1+1)*(max2-min2+1)*sizeof(int));
// Get information to march through data
numC = inData->GetNumberOfScalarComponents();
inData->GetUpdateExtent(min0, max0, min1, max1, min2, max2);
inData->GetIncrements(inInc0, inInc1, inInc2);
outExtent = outData->GetExtent();
outIncs = outData->GetIncrements();
origin = outData->GetOrigin();
spacing = outData->GetSpacing();
target = (unsigned long)((max2 - min2 + 1)*(max1 - min1 +1)/50.0);
target++;
// Loop through input pixels
for (idZ = min2; idZ <= max2; idZ++)
{
for (idY = min1; idY <= max1; idY++)
{
if (!(count%target))
{
self->UpdateProgress(count/(50.0*target));
}
count++;
if (clippingExtents == NULL)
{
tempPtr = inPtr + (inInc2*(idZ - min2) +
inInc1*(idY - min1));
for (idX = min0; idX <= max0; idX++)
{
// find the bin for this pixel.
outPtrC = outPtr;
for (idxC = 0; idxC < numC; ++idxC)
{
// Gather statistics
sum[idxC]+= *tempPtr;
if (*tempPtr > Max[idxC])
Max[idxC] = *tempPtr;
else if (*tempPtr < Min[idxC])
Min[idxC] = *tempPtr;
(*PixelCount)++;
// compute the index
outIdx = (int) floor((((double)*tempPtr++ - origin[idxC]) / spacing[idxC]));
if (outIdx < outExtent[idxC*2] || outIdx > outExtent[idxC*2+1])
{
// Out of bin range
outPtrC = NULL;
break;
}
outPtrC += (outIdx - outExtent[idxC*2]) * outIncs[idxC];
}
if (outPtrC)
{
++(*outPtrC);
}
}
}
else
{
iter = 0;
cr1 = min0;
for (;;)
{
rval = clippingExtents->GetNextExtent(r1, r2, min0, max0,
idY, idZ, iter);
cr2 = r1 - 1;
if (!self->GetReverseStencil())
{
tempPtr = inPtr + (inInc2*(idZ - min2) +
inInc1*(idY - min1) +
numC*(cr1 - min0));
for (idX = cr1; idX <= cr2; idX++)
{
// find the bin for this pixel.
outPtrC = outPtr;
for (idxC = 0; idxC < numC; ++idxC)
{
// Gather statistics
sum[idxC]+= *tempPtr;
if (*tempPtr > Max[idxC])
Max[idxC] = *tempPtr;
else if (*tempPtr < Min[idxC])
Min[idxC] = *tempPtr;
(*PixelCount)++;
// compute the index
outIdx = (int) floor((((double)*tempPtr++ - origin[idxC]) / spacing[idxC]));
if (outIdx < outExtent[idxC*2] || outIdx > outExtent[idxC*2+1])
{
// Out of bin range
outPtrC = NULL;
break;
}
outPtrC += (outIdx - outExtent[idxC*2]) * outIncs[idxC];
}
if (outPtrC)
{
++(*outPtrC);
}
}
}
cr1 = r2 + 1;
// break if no foreground extents left
if (rval == 0)
{
break;
}
if (self->GetReverseStencil())
{
// do unchanged portion
tempPtr = inPtr + (inInc2*(idZ - min2) +
inInc1*(idY - min1) +
numC*(r1 - min0));
for (idX = r1; idX <= r2; idX++)
{
// find the bin for this pixel.
outPtrC = outPtr;
for (idxC = 0; idxC < numC; ++idxC)
{
// Gather statistics
sum[idxC]+= *tempPtr;
if (*tempPtr > Max[idxC])
Max[idxC] = *tempPtr;
else if (*tempPtr < Min[idxC])
Min[idxC] = *tempPtr;
(*PixelCount)++;
// compute the index
outIdx = (int) floor((((double)*tempPtr++ - origin[idxC]) / spacing[idxC]));
if (outIdx < outExtent[idxC*2] || outIdx > outExtent[idxC*2+1])
{
// Out of bin range
outPtrC = NULL;
break;
}
outPtrC += (outIdx - outExtent[idxC*2]) * outIncs[idxC];
}
if (outPtrC)
{
++(*outPtrC);
}
}
}
}
}
}
}
if (*PixelCount) // avoid the div0
{
Mean[0] = sum[0] / (double)*PixelCount;
Mean[1] = sum[1] / (double)*PixelCount;
Mean[2] = sum[2] / (double)*PixelCount;
}
else
{
Mean[0]=Mean[1]=Mean[2] = 0.0;
}
}
//----------------------------------------------------------------------------
// This method is passed a input and output Data, and executes the filter
// algorithm to fill the output from the input.
// It just executes a switch statement to call the correct function for
// the Datas data types.
void vtkImageAccumulate::ExecuteData(vtkDataObject *vtkNotUsed(out))
{
void *inPtr;
void *outPtr;
vtkImageData *inData = this->GetInput();
vtkImageData *outData = this->GetOutput();
vtkDebugMacro(<<"Executing image accumulate");
// We need to allocate our own scalars since we are overriding
// the superclasses "Execute()" method.
outData->SetExtent(outData->GetWholeExtent());
outData->AllocateScalars();
inPtr = inData->GetScalarPointerForExtent(inData->GetUpdateExtent());
outPtr = outData->GetScalarPointer();
// Components turned into x, y and z
if (this->GetInput()->GetNumberOfScalarComponents() > 3)
{
vtkErrorMacro("This filter can handle upto 3 components");
return;
}
// this filter expects that output is type int.
if (outData->GetScalarType() != VTK_INT)
{
vtkErrorMacro(<< "Execute: out ScalarType " << outData->GetScalarType()
<< " must be int\n");
return;
}
switch (inData->GetScalarType())
{
vtkTemplateMacro9(vtkImageAccumulateExecute, this,
inData, (VTK_TT *)(inPtr),
outData, (int *)(outPtr),
this->Min, this->Max,
this->Mean, &this->PixelCount);
default:
vtkErrorMacro(<< "Execute: Unknown ScalarType");
return;
}
}
//----------------------------------------------------------------------------
void vtkImageAccumulate::ExecuteInformation(vtkImageData *input,
vtkImageData *output)
{
output->SetWholeExtent(this->ComponentExtent);
output->SetOrigin(this->ComponentOrigin);
output->SetSpacing(this->ComponentSpacing);
output->SetNumberOfScalarComponents(1);
output->SetScalarType(VTK_INT);
// See if we should be setting up some clipping extents
if (this->StencilFunction)
{
if (!this->ClippingExtents)
{
this->ClippingExtents = vtkImageClippingExtents::New();
}
this->ClippingExtents->SetClippingObject(this->StencilFunction);
}
if (this->ClippingExtents)
{
this->ClippingExtents->BuildExtents(input);
}
}
//----------------------------------------------------------------------------
// Get ALL of the input.
void vtkImageAccumulate::ComputeInputUpdateExtent(int inExt[6],
int outExt[6])
{
int *wholeExtent;
outExt = outExt;
wholeExtent = this->GetInput()->GetWholeExtent();
memcpy(inExt, wholeExtent, 6*sizeof(int));
}
void vtkImageAccumulate::PrintSelf(ostream& os, vtkIndent indent)
{
vtkImageToImageFilter::PrintSelf(os,indent);
os << indent << "ComponentOrigin: ( "
<< this->ComponentOrigin[0] << ", "
<< this->ComponentOrigin[1] << ", "
<< this->ComponentOrigin[2] << " )\n";
os << indent << "ComponentSpacing: ( "
<< this->ComponentSpacing[0] << ", "
<< this->ComponentSpacing[1] << ", "
<< this->ComponentSpacing[2] << " )\n";
os << indent << "ComponentExtent: ( "
<< this->ComponentExtent[0] << "," << this->ComponentExtent[1] << " "
<< this->ComponentExtent[2] << "," << this->ComponentExtent[3] << " "
<< this->ComponentExtent[4] << "," << this->ComponentExtent[5] << " }\n";
os << indent << "StencilFunction: " << this->StencilFunction << "\n";
os << indent << "ReverseStencil: " << (this->ReverseStencil ?
"On\n" : "Off\n");
os << indent << "ClippingExtents: " << this->ClippingExtents << "\n";
}
<|endoftext|>
|
<commit_before>#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
#include "nifty/graph/optimization/mincut/mincut_base.hxx"
#include "nifty/graph/optimization/mincut/mincut_visitor_base.hxx"
#include "nifty/python/graph/undirected_list_graph.hxx"
#include "nifty/python/graph/edge_contraction_graph.hxx"
#include "nifty/python/graph/optimization/mincut/mincut_objective.hxx"
#include "nifty/python/graph/optimization/mincut/py_mincut_visitor_base.hxx"
#include "nifty/python/converter.hxx"
namespace py = pybind11;
namespace nifty{
namespace graph{
using namespace py;
//PYBIND11_DECLARE_HOLDER_TYPE(McBase, std::shared_ptr<McBase>);
template<class OBJECTIVE>
void exportMincutVisitorBaseT(py::module & mincutModule) {
typedef OBJECTIVE ObjectiveType;
typedef PyMincutVisitorBase<ObjectiveType> PyMcVisitorBase;
typedef MincutVisitorBase<ObjectiveType> McVisitorBase;
const auto objName = MincutObjectiveName<ObjectiveType>::name();
const auto mcVisitorBaseClsName = std::string("MincutVisitorBase") + objName;
const auto mcVerboseVisitorClsName = std::string("MincutVerboseVisitor") + objName;
// base factory
py::class_<
McVisitorBase,
std::unique_ptr<McVisitorBase>,
PyMcVisitorBase
> mcVisitorBase(mincutModule, mcVisitorBaseClsName.c_str());
//mcVisitorBase
//;
// concrete visitors
typedef MincutVerboseVisitor<ObjectiveType> McVerboseVisitor;
py::class_<McVerboseVisitor, std::unique_ptr<McVerboseVisitor> >(mincutModule, mcVerboseVisitorClsName.c_str(), mcVisitorBase)
.def(py::init<const int, const double>(),
py::arg_t<int>("printNth",1),
py::arg_t<double>("timeLimit",std::numeric_limits<double>::infinity())
)
.def("stopOptimize",&McVerboseVisitor::stopOptimize)
;
}
void exportMincutVisitorBase(py::module & mincutModule) {
{
typedef PyUndirectedGraph GraphType;
typedef MincutObjective<GraphType, double> ObjectiveType;
exportMincutVisitorBaseT<ObjectiveType>(mincutModule);
}
{
typedef PyContractionGraph<PyUndirectedGraph> GraphType;
typedef MincutObjective<GraphType, double> ObjectiveType;
exportMincutVisitorBaseT<ObjectiveType>(mincutModule);
}
}
}
}
<commit_msg>minor changes<commit_after>#include <memory>
#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
#include "nifty/graph/optimization/mincut/mincut_base.hxx"
#include "nifty/graph/optimization/mincut/mincut_visitor_base.hxx"
#include "nifty/python/graph/undirected_list_graph.hxx"
#include "nifty/python/graph/edge_contraction_graph.hxx"
#include "nifty/python/graph/optimization/mincut/mincut_objective.hxx"
#include "nifty/python/graph/optimization/mincut/py_mincut_visitor_base.hxx"
#include "nifty/python/converter.hxx"
namespace py = pybind11;
namespace nifty{
namespace graph{
using namespace py;
//PYBIND11_DECLARE_HOLDER_TYPE(McBase, std::shared_ptr<McBase>);
template<class OBJECTIVE>
void exportMincutVisitorBaseT(py::module & module) {
typedef OBJECTIVE ObjectiveType;
typedef PyMincutVisitorBase<ObjectiveType> PyVisitorBase;
typedef MincutVisitorBase<ObjectiveType> VisitorBase;
const auto objName = MincutObjectiveName<ObjectiveType>::name();
const auto visitorBaseClsName = std::string("MincutVisitorBase") + objName;
const auto mcVerboseVisitorClsName = std::string("MincutVerboseVisitor") + objName;
// base factory
py::class_<
VisitorBase,
std::unique_ptr<VisitorBase>,
PyVisitorBase
> visitorBase(module, visitorBaseClsName.c_str());
//visitorBase
//;
// concrete visitors
{
const auto visitorClsName = std::string("VerboseVisitor") + objName;
typedef MincutVerboseVisitor<ObjectiveType> VisitorType;
py::class_<VisitorType, std::unique_ptr<VisitorType> >(module, visitorClsName.c_str(), visitorBase)
.def(py::init<const int, const double , const double>(),
py::arg_t<int>("visitNth",1),
py::arg_t<double>("timeLimitSolver",std::numeric_limits<double>::infinity()),
py::arg_t<double>("timeLimitTotal",std::numeric_limits<double>::infinity())
)
.def("stopOptimize",&VisitorType::stopOptimize)
.def_property_readonly("timeLimitSolver", &VisitorType::timeLimitSolver)
.def_property_readonly("timeLimitTotal", &VisitorType::timeLimitTotal)
.def_property_readonly("runtimeSolver", &VisitorType::runtimeSolver)
.def_property_readonly("runtimeTotal", &VisitorType::runtimeTotal)
;
}
}
void exportMincutVisitorBase(py::module & module) {
{
typedef PyUndirectedGraph GraphType;
typedef MincutObjective<GraphType, double> ObjectiveType;
exportMincutVisitorBaseT<ObjectiveType>(module);
}
{
typedef PyContractionGraph<PyUndirectedGraph> GraphType;
typedef MincutObjective<GraphType, double> ObjectiveType;
exportMincutVisitorBaseT<ObjectiveType>(module);
}
}
}
}
<|endoftext|>
|
<commit_before>/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-
Copyright 2014, 2015
Raffaello D. Di Napoli
This file is part of Abaclade.
Abaclade 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.
Abaclade is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
Public License for more details.
You should have received a copy of the GNU General Public License along with Abaclade. If not, see
<http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------------------------------*/
#include "coroutine-scheduler.hxx"
#include <abaclade.hxx>
#include <abaclade/coroutine.hxx>
#include <abaclade/thread.hxx>
#if ABC_HOST_API_POSIX
#include <errno.h> // EINVAL errno
#include <time.h> // nanosleep()
#if ABC_HOST_API_DARWIN
#include <dispatch/dispatch.h>
#else
#include <semaphore.h>
#if ABC_HOST_API_FREEBSD
#include <pthread_np.h> // pthread_getthreadid_np()
#elif ABC_HOST_API_LINUX
#include <sys/syscall.h> // SYS_*
#include <unistd.h> // syscall()
#endif
#endif
#endif
////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::thread
namespace abc {
class thread::impl {
private:
friend class thread;
public:
/*! Constructor
@param fnMain
Initial value for m_fnInnerMain.
*/
impl(std::function<void ()> fnMain) :
#if ABC_HOST_API_POSIX
m_id(0),
#elif ABC_HOST_API_WIN32
m_h(nullptr),
#else
#error "TODO: HOST_API"
#endif
m_fnInnerMain(std::move(fnMain)) {
}
//! Destructor.
~impl() {
#if ABC_HOST_API_WIN32
::CloseHandle(m_h);
#endif
}
//! Creates a thread to run outer_main().
void start(std::shared_ptr<impl> * ppimplThis) {
ABC_TRACE_FUNC(this);
#if ABC_HOST_API_DARWIN
m_dsemStarted = ::dispatch_semaphore_create(0);
if (!m_dsemStarted) {
exception::throw_os_error();
}
try {
if (int iErr = ::pthread_create(&m_h, nullptr, &outer_main, ppimplThis)) {
exception::throw_os_error(iErr);
}
// Block until the new thread is finished updating *this.
::dispatch_semaphore_wait(m_dsemStarted, DISPATCH_TIME_FOREVER);
} catch (...) {
// TODO: move this code to a “defer” lambda.
::dispatch_release(m_dsemStarted);
throw;
}
// TODO: move this code to a “defer” lambda.
::dispatch_release(m_dsemStarted);
#elif ABC_HOST_API_POSIX
if (::sem_init(&m_semStarted, 0, 0)) {
exception::throw_os_error();
}
try {
if (int iErr = ::pthread_create(&m_h, nullptr, &outer_main, ppimplThis)) {
exception::throw_os_error(iErr);
}
/* Block until the new thread is finished updating *this. The only possible failure is
EINTR, so we just keep on retrying. */
while (::sem_wait(&m_semStarted)) {
;
}
} catch (...) {
// TODO: move this code to a “defer” lambda.
::sem_destroy(&m_semStarted);
throw;
}
// TODO: move this code to a “defer” lambda.
::sem_destroy(&m_semStarted);
#elif ABC_HOST_API_WIN32
m_hStartedEvent = ::CreateEvent(nullptr, true, false, nullptr);
try {
m_h = ::CreateThread(nullptr, 0, &outer_main, ppimplThis, 0, nullptr);
if (!m_h) {
exception::throw_os_error();
}
// Block until the new thread is finished updating *this. Must not fail.
::WaitForSingleObject(m_hStartedEvent, INFINITE);
} catch (...) {
// TODO: move this code to a “defer” lambda.
::CloseHandle(m_hStartedEvent);
throw;
}
// TODO: move this code to a “defer” lambda.
::CloseHandle(m_hStartedEvent);
#else
#error "TODO: HOST_API"
#endif
}
private:
/*! Lower-level wrapper for the thread function passed to the constructor. Under POSIX, this is
also needed to assign the thread ID to the owning abc::thread instance.
@param p
*this.
@return
Unused.
*/
#if ABC_HOST_API_POSIX
static void * outer_main(void * p) {
#elif ABC_HOST_API_WIN32
static DWORD WINAPI outer_main(void * p) {
#else
#error "TODO: HOST_API"
#endif
/* Get a copy of the shared_ptr owning *this, so that members will be guaranteed to be
accessible even after start() returns, in the creating thread.
Dereferencing p is safe because the creating thread, which owns *p, is blocked, waiting for
this thread to signal that it’s finished starting. */
std::shared_ptr<impl> pimplThis(*static_cast<std::shared_ptr<impl> *>(p));
#if ABC_HOST_API_POSIX
pimplThis->m_id = this_thread::id();
#if ABC_HOST_API_DARWIN
::dispatch_semaphore_signal(pimplThis->m_dsemStarted);
#else
// Report that this thread is done with writing to *pthr.
::sem_post(&pimplThis->m_semStarted);
#endif
#elif ABC_HOST_API_WIN32
// Report that this thread is done with writing to *pthr.
::SetEvent(pimplThis->m_hStartedEvent);
#else
#error "TODO: HOST_API"
#endif
try {
pimplThis->m_fnInnerMain();
} catch (std::exception const & x) {
exception::write_with_scope_trace(nullptr, &x);
// TODO: kill every other thread.
} catch (...) {
exception::write_with_scope_trace();
// TODO: kill every other thread.
}
#if ABC_HOST_API_POSIX
return nullptr;
#elif ABC_HOST_API_WIN32
return 0;
#else
#error "TODO: HOST_API"
#endif
}
private:
//! OS-dependent ID/handle.
native_handle_type m_h;
#if ABC_HOST_API_DARWIN
//! Dispatch semaphore used by the new thread to report to its parent that it has started.
::dispatch_semaphore_t m_dsemStarted;
#elif ABC_HOST_API_POSIX
//! OS-dependent ID for use with OS-specific API (pthread_*_np() functions and other native API).
id_type m_id;
//! Semaphore used by the new thread to report to its parent that it has started.
::sem_t m_semStarted;
#elif ABC_HOST_API_WIN32
//! Event used by the new thread to report to its parent that it has started.
HANDLE m_hStartedEvent;
#else
#error "TODO: HOST_API"
#endif
//! Function to be executed in the thread.
std::function<void ()> m_fnInnerMain;
};
/*explicit*/ thread::thread(std::function<void ()> fnMain) :
m_pimpl(std::make_shared<impl>(std::move(fnMain))) {
ABC_TRACE_FUNC(this);
m_pimpl->start(&m_pimpl);
}
thread::~thread() {
if (joinable()) {
// TODO: std::terminate() or something similar.
}
}
thread::id_type thread::id() const {
ABC_TRACE_FUNC(this);
#if ABC_HOST_API_POSIX
return m_pimpl ? m_pimpl->m_id : 0;
#elif ABC_HOST_API_WIN32
if (m_pimpl) {
DWORD iTid = ::GetThreadId(m_pimpl->m_h);
if (iTid == 0) {
exception::throw_os_error();
}
return iTid;
} else {
return 0;
}
#else
#error "TODO: HOST_API"
#endif
}
void thread::join() {
ABC_TRACE_FUNC(this);
if (!m_pimpl) {
// TODO: use a better exception class.
ABC_THROW(argument_error, ());
}
#if ABC_HOST_API_POSIX
if (int iErr = ::pthread_join(m_pimpl->m_h, nullptr)) {
exception::throw_os_error(iErr);
}
#elif ABC_HOST_API_WIN32
DWORD iRet = ::WaitForSingleObject(m_pimpl->m_h, INFINITE);
if (iRet == WAIT_FAILED) {
exception::throw_os_error();
}
#else
#error "TODO: HOST_API"
#endif
// Release the impl instance; this will also make joinable() return false.
m_pimpl.reset();
}
thread::native_handle_type thread::native_handle() const {
return m_pimpl ? m_pimpl->m_h : native_handle_type();
}
} //namespace abc
////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::to_str_backend – specialization for abc::thread
namespace abc {
to_str_backend<thread>::to_str_backend() {
}
to_str_backend<thread>::~to_str_backend() {
}
void to_str_backend<thread>::set_format(istr const & sFormat) {
ABC_TRACE_FUNC(this, sFormat);
auto it(sFormat.cbegin());
// Add parsing of the format string here.
// If we still have any characters, they are garbage.
if (it != sFormat.cend()) {
ABC_THROW(syntax_error, (
ABC_SL("unexpected character"), sFormat, static_cast<unsigned>(it - sFormat.cbegin())
));
}
}
void to_str_backend<thread>::write(thread const & thr, io::text::writer * ptwOut) {
ABC_TRACE_FUNC(this/*, thr*/, ptwOut);
if (thread::id_type id = thr.id()) {
m_tsbStr.write(istr(ABC_SL("TID:")), ptwOut);
m_tsbId.write(id, ptwOut);
} else {
m_tsbStr.write(istr(ABC_SL("TID:-")), ptwOut);
}
}
} //namespace abc
////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::this_thread
namespace abc {
namespace this_thread {
std::shared_ptr<coroutine::scheduler> const & attach_coroutine_scheduler(
std::shared_ptr<coroutine::scheduler> pcorosched /*= nullptr*/
) {
ABC_TRACE_FUNC(pcorosched);
std::shared_ptr<coroutine::scheduler> & pcoroschedCurr = coroutine::scheduler::sm_pcorosched;
if (pcorosched) {
if (pcoroschedCurr) {
// The current thread already has a coroutine scheduler.
// TODO: use a better exception class.
ABC_THROW(generic_error, ());
}
pcoroschedCurr = std::move(pcorosched);
} else {
// Create and set a new coroutine scheduler if the current thread didn’t already have one.
if (!pcoroschedCurr) {
pcoroschedCurr = std::make_shared<coroutine::scheduler>();
}
}
return pcoroschedCurr;
}
std::shared_ptr<coroutine::scheduler> const & get_coroutine_scheduler() {
return coroutine::scheduler::sm_pcorosched;
}
thread::id_type id() {
#if ABC_HOST_API_DARWIN
thread::id_type id;
::pthread_threadid_np(nullptr, &id);
return id;
#elif ABC_HOST_API_FREEBSD
static_assert(
sizeof(thread::id_type) == sizeof(decltype(::pthread_getthreadid_np())),
"return type of ::pthread_getthreadid_np() must be the same size as thread::id_type"
);
return ::pthread_getthreadid_np();
#elif ABC_HOST_API_LINUX
static_assert(
sizeof(thread::id_type) == sizeof(::pid_t), "::pid_t must be the same size as thread::id_type"
);
// This is a call to ::gettid().
return static_cast< ::pid_t>(::syscall(SYS_gettid));
#elif ABC_HOST_API_WIN32
return ::GetCurrentThreadId();
#else
#error "TODO: HOST_API"
#endif
}
void run_coroutines() {
if (auto & pcorosched = get_coroutine_scheduler()) {
pcorosched->run();
}
}
void sleep_for_ms(unsigned iMillisecs) {
#if ABC_HOST_API_POSIX
::timespec tsRequested, tsRemaining;
tsRequested.tv_sec = static_cast< ::time_t>(iMillisecs / 1000u);
tsRequested.tv_nsec = static_cast<long>(
static_cast<unsigned long>(iMillisecs % 1000u) * 1000000u
);
/* This loop will only repeat in case of EINTR. Technically ::nanosleep() may fail with EINVAL,
but the calculation above makes that impossible. */
while (::nanosleep(&tsRequested, &tsRemaining) < 0) {
// Set the new requested time to whatever we didn’t get to sleep in the last nanosleep() call.
tsRequested = tsRemaining;
}
#elif ABC_HOST_API_WIN32
::Sleep(iMillisecs);
#else
#error "TODO: HOST_API"
#endif
}
} //namespace this_thread
} //namespace abc
////////////////////////////////////////////////////////////////////////////////////////////////////
<commit_msg>Move thread started event logic into new abc::detail::simple_event class<commit_after>/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-
Copyright 2014, 2015
Raffaello D. Di Napoli
This file is part of Abaclade.
Abaclade 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.
Abaclade is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
Public License for more details.
You should have received a copy of the GNU General Public License along with Abaclade. If not, see
<http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------------------------------*/
#include "coroutine-scheduler.hxx"
#include <abaclade.hxx>
#include <abaclade/coroutine.hxx>
#include <abaclade/thread.hxx>
#if ABC_HOST_API_POSIX
#include <errno.h> // EINVAL errno
#include <time.h> // nanosleep()
#if ABC_HOST_API_DARWIN
#include <dispatch/dispatch.h>
#else
#include <semaphore.h>
#if ABC_HOST_API_FREEBSD
#include <pthread_np.h> // pthread_getthreadid_np()
#elif ABC_HOST_API_LINUX
#include <sys/syscall.h> // SYS_*
#include <unistd.h> // syscall()
#endif
#endif
#endif
////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::detail::simple_event
/*! Event that can be waited for. Not compatible with coroutines, since it doesn’t yield to a
coroutine::scheduler. */
// TODO: make this a non-coroutine-friendly general-purpose event.
namespace abc {
namespace detail {
class simple_event : public noncopyable {
public:
//! Constructor.
simple_event() {
#if ABC_HOST_API_DARWIN
m_dsem = ::dispatch_semaphore_create(0);
if (!m_dsem) {
exception::throw_os_error();
}
#elif ABC_HOST_API_POSIX
if (::sem_init(&m_sem, 0, 0)) {
exception::throw_os_error();
}
#elif ABC_HOST_API_WIN32
m_hEvent = ::CreateEvent(nullptr, true, false, nullptr);
if (!m_hEvent) {
exception::throw_os_error();
}
#else
#error "TODO: HOST_API"
#endif
}
//! Destructor.
~simple_event() {
#if ABC_HOST_API_DARWIN
::dispatch_release(m_dsem);
#elif ABC_HOST_API_POSIX
::sem_destroy(&m_sem);
#elif ABC_HOST_API_WIN32
::CloseHandle(m_hEvent);
#else
#error "TODO: HOST_API"
#endif
}
//! Raises the event.
void raise() {
#if ABC_HOST_API_DARWIN
::dispatch_semaphore_signal(m_dsem);
#elif ABC_HOST_API_POSIX
::sem_post(&m_sem);
#elif ABC_HOST_API_WIN32
::SetEvent(m_hEvent);
#else
#error "TODO: HOST_API"
#endif
}
//! Waits for the event to be raised by another thread.
void wait() {
#if ABC_HOST_API_DARWIN
::dispatch_semaphore_wait(m_dsem, DISPATCH_TIME_FOREVER);
#elif ABC_HOST_API_POSIX
/* Block until the new thread is finished updating *this. The only possible failure is EINTR,
so we just keep on retrying. */
while (::sem_wait(&m_sem)) {
;
}
#elif ABC_HOST_API_WIN32
::WaitForSingleObject(m_hEvent, INFINITE);
#else
#error "TODO: HOST_API"
#endif
}
private:
#if ABC_HOST_API_DARWIN
//! Underlying dispatch semaphore.
::dispatch_semaphore_t m_dsem;
#elif ABC_HOST_API_POSIX
//! Underlying POSIX semaphore.
::sem_t m_sem;
#elif ABC_HOST_API_WIN32
//! Underlying event.
::HANDLE m_hEvent;
#else
#error "TODO: HOST_API"
#endif
};
} //namespace detail
} //namespace abc
////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::thread
namespace abc {
class thread::impl {
private:
friend class thread;
public:
/*! Constructor
@param fnMain
Initial value for m_fnInnerMain.
*/
impl(std::function<void ()> fnMain) :
#if ABC_HOST_API_POSIX
m_id(0),
#elif ABC_HOST_API_WIN32
m_h(nullptr),
#else
#error "TODO: HOST_API"
#endif
m_pseStarted(nullptr),
m_fnInnerMain(std::move(fnMain)) {
}
//! Destructor.
~impl() {
#if ABC_HOST_API_WIN32
::CloseHandle(m_h);
#endif
}
//! Creates a thread to run outer_main().
void start(std::shared_ptr<impl> * ppimplThis) {
ABC_TRACE_FUNC(this);
detail::simple_event seStarted;
m_pseStarted = &seStarted;
try {
#if ABC_HOST_API_POSIX
if (int iErr = ::pthread_create(&m_h, nullptr, &outer_main, ppimplThis)) {
exception::throw_os_error(iErr);
}
#elif ABC_HOST_API_WIN32
m_h = ::CreateThread(nullptr, 0, &outer_main, ppimplThis, 0, nullptr);
if (!m_h) {
exception::throw_os_error();
}
#else
#error "TODO: HOST_API"
#endif
// Block until the new thread is finished updating *this.
seStarted.wait();
} catch (...) {
m_pseStarted = nullptr;
throw;
}
m_pseStarted = nullptr;
}
private:
/*! Lower-level wrapper for the thread function passed to the constructor. Under POSIX, this is
also needed to assign the thread ID to the owning abc::thread instance.
@param p
*this.
@return
Unused.
*/
#if ABC_HOST_API_POSIX
static void * outer_main(void * p) {
#elif ABC_HOST_API_WIN32
static DWORD WINAPI outer_main(void * p) {
#else
#error "TODO: HOST_API"
#endif
/* Get a copy of the shared_ptr owning *this, so that members will be guaranteed to be
accessible even after start() returns, in the creating thread.
Dereferencing p is safe because the creating thread, which owns *p, is blocked, waiting for
this thread to signal that it’s finished starting. */
std::shared_ptr<impl> pimplThis(*static_cast<std::shared_ptr<impl> *>(p));
#if ABC_HOST_API_POSIX
pimplThis->m_id = this_thread::id();
#endif
// Report that this thread is done with writing to *pthr.
pimplThis->m_pseStarted->raise();
try {
pimplThis->m_fnInnerMain();
} catch (std::exception const & x) {
exception::write_with_scope_trace(nullptr, &x);
// TODO: kill every other thread.
} catch (...) {
exception::write_with_scope_trace();
// TODO: kill every other thread.
}
#if ABC_HOST_API_POSIX
return nullptr;
#elif ABC_HOST_API_WIN32
return 0;
#else
#error "TODO: HOST_API"
#endif
}
private:
//! OS-dependent ID/handle.
native_handle_type m_h;
#if ABC_HOST_API_POSIX
//! OS-dependent ID for use with OS-specific API (pthread_*_np() functions and other native API).
id_type m_id;
#endif
/*! Pointer to an event used by the new thread to report to its parent that it has started. Only
non-nullptr during the execution of start(). */
detail::simple_event * m_pseStarted;
//! Function to be executed in the thread.
std::function<void ()> m_fnInnerMain;
};
/*explicit*/ thread::thread(std::function<void ()> fnMain) :
m_pimpl(std::make_shared<impl>(std::move(fnMain))) {
ABC_TRACE_FUNC(this);
m_pimpl->start(&m_pimpl);
}
thread::~thread() {
if (joinable()) {
// TODO: std::terminate() or something similar.
}
}
thread::id_type thread::id() const {
ABC_TRACE_FUNC(this);
#if ABC_HOST_API_POSIX
return m_pimpl ? m_pimpl->m_id : 0;
#elif ABC_HOST_API_WIN32
if (m_pimpl) {
DWORD iTid = ::GetThreadId(m_pimpl->m_h);
if (iTid == 0) {
exception::throw_os_error();
}
return iTid;
} else {
return 0;
}
#else
#error "TODO: HOST_API"
#endif
}
void thread::join() {
ABC_TRACE_FUNC(this);
if (!m_pimpl) {
// TODO: use a better exception class.
ABC_THROW(argument_error, ());
}
#if ABC_HOST_API_POSIX
if (int iErr = ::pthread_join(m_pimpl->m_h, nullptr)) {
exception::throw_os_error(iErr);
}
#elif ABC_HOST_API_WIN32
DWORD iRet = ::WaitForSingleObject(m_pimpl->m_h, INFINITE);
if (iRet == WAIT_FAILED) {
exception::throw_os_error();
}
#else
#error "TODO: HOST_API"
#endif
// Release the impl instance; this will also make joinable() return false.
m_pimpl.reset();
}
thread::native_handle_type thread::native_handle() const {
return m_pimpl ? m_pimpl->m_h : native_handle_type();
}
} //namespace abc
////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::to_str_backend – specialization for abc::thread
namespace abc {
to_str_backend<thread>::to_str_backend() {
}
to_str_backend<thread>::~to_str_backend() {
}
void to_str_backend<thread>::set_format(istr const & sFormat) {
ABC_TRACE_FUNC(this, sFormat);
auto it(sFormat.cbegin());
// Add parsing of the format string here.
// If we still have any characters, they are garbage.
if (it != sFormat.cend()) {
ABC_THROW(syntax_error, (
ABC_SL("unexpected character"), sFormat, static_cast<unsigned>(it - sFormat.cbegin())
));
}
}
void to_str_backend<thread>::write(thread const & thr, io::text::writer * ptwOut) {
ABC_TRACE_FUNC(this/*, thr*/, ptwOut);
if (thread::id_type id = thr.id()) {
m_tsbStr.write(istr(ABC_SL("TID:")), ptwOut);
m_tsbId.write(id, ptwOut);
} else {
m_tsbStr.write(istr(ABC_SL("TID:-")), ptwOut);
}
}
} //namespace abc
////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::this_thread
namespace abc {
namespace this_thread {
std::shared_ptr<coroutine::scheduler> const & attach_coroutine_scheduler(
std::shared_ptr<coroutine::scheduler> pcorosched /*= nullptr*/
) {
ABC_TRACE_FUNC(pcorosched);
std::shared_ptr<coroutine::scheduler> & pcoroschedCurr = coroutine::scheduler::sm_pcorosched;
if (pcorosched) {
if (pcoroschedCurr) {
// The current thread already has a coroutine scheduler.
// TODO: use a better exception class.
ABC_THROW(generic_error, ());
}
pcoroschedCurr = std::move(pcorosched);
} else {
// Create and set a new coroutine scheduler if the current thread didn’t already have one.
if (!pcoroschedCurr) {
pcoroschedCurr = std::make_shared<coroutine::scheduler>();
}
}
return pcoroschedCurr;
}
std::shared_ptr<coroutine::scheduler> const & get_coroutine_scheduler() {
return coroutine::scheduler::sm_pcorosched;
}
thread::id_type id() {
#if ABC_HOST_API_DARWIN
thread::id_type id;
::pthread_threadid_np(nullptr, &id);
return id;
#elif ABC_HOST_API_FREEBSD
static_assert(
sizeof(thread::id_type) == sizeof(decltype(::pthread_getthreadid_np())),
"return type of ::pthread_getthreadid_np() must be the same size as thread::id_type"
);
return ::pthread_getthreadid_np();
#elif ABC_HOST_API_LINUX
static_assert(
sizeof(thread::id_type) == sizeof(::pid_t), "::pid_t must be the same size as thread::id_type"
);
// This is a call to ::gettid().
return static_cast< ::pid_t>(::syscall(SYS_gettid));
#elif ABC_HOST_API_WIN32
return ::GetCurrentThreadId();
#else
#error "TODO: HOST_API"
#endif
}
void run_coroutines() {
if (auto & pcorosched = get_coroutine_scheduler()) {
pcorosched->run();
}
}
void sleep_for_ms(unsigned iMillisecs) {
#if ABC_HOST_API_POSIX
::timespec tsRequested, tsRemaining;
tsRequested.tv_sec = static_cast< ::time_t>(iMillisecs / 1000u);
tsRequested.tv_nsec = static_cast<long>(
static_cast<unsigned long>(iMillisecs % 1000u) * 1000000u
);
/* This loop will only repeat in case of EINTR. Technically ::nanosleep() may fail with EINVAL,
but the calculation above makes that impossible. */
while (::nanosleep(&tsRequested, &tsRemaining) < 0) {
// Set the new requested time to whatever we didn’t get to sleep in the last nanosleep() call.
tsRequested = tsRemaining;
}
#elif ABC_HOST_API_WIN32
::Sleep(iMillisecs);
#else
#error "TODO: HOST_API"
#endif
}
} //namespace this_thread
} //namespace abc
////////////////////////////////////////////////////////////////////////////////////////////////////
<|endoftext|>
|
<commit_before>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2015-2016 Esteban Tovagliari, The appleseedhq Organization
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// Interface header.
#include "normalizeddiffusionbssrdf.h"
// appleseed.renderer headers.
#include "renderer/modeling/bssrdf/bssrdfsample.h"
#include "renderer/modeling/bssrdf/separablebssrdf.h"
#include "renderer/modeling/bssrdf/sss.h"
#include "renderer/modeling/input/inputevaluator.h"
// appleseed.foundation headers.
#include "foundation/image/colorspace.h"
#include "foundation/math/cdf.h"
#include "foundation/math/scalar.h"
#include "foundation/math/vector.h"
#include "foundation/utility/containers/dictionary.h"
#include "foundation/utility/containers/specializedarrays.h"
#include "foundation/utility/memory.h"
// Standard headers.
#include <cmath>
#include <cstddef>
// Forward declarations.
namespace renderer { class Assembly; }
namespace renderer { class ShadingContext; }
using namespace foundation;
using namespace std;
namespace renderer
{
namespace
{
//
// Normalized diffusion BSSRDF.
//
// Reference:
//
// Approximate Reflectance Profiles for Efficient Subsurface Scattering
// Per H. Christensen, Brent Burley
// http://graphics.pixar.com/library/ApproxBSSRDF/paper.pdf
//
const char* Model = "normalized_diffusion_bssrdf";
class NormalizedDiffusionBSSRDF
: public SeparableBSSRDF
{
public:
NormalizedDiffusionBSSRDF(
const char* name,
const ParamArray& params)
: SeparableBSSRDF(name, params)
{
m_inputs.declare("weight", InputFormatScalar, "1.0");
m_inputs.declare("reflectance", InputFormatSpectralReflectance);
m_inputs.declare("reflectance_multiplier", InputFormatScalar, "1.0");
m_inputs.declare("dmfp", InputFormatSpectralReflectance);
m_inputs.declare("dmfp_multiplier", InputFormatScalar, "1.0");
m_inputs.declare("outside_ior", InputFormatScalar);
m_inputs.declare("inside_ior", InputFormatScalar);
}
virtual void release() APPLESEED_OVERRIDE
{
delete this;
}
virtual const char* get_model() const APPLESEED_OVERRIDE
{
return Model;
}
virtual size_t compute_input_data_size(
const Assembly& assembly) const APPLESEED_OVERRIDE
{
return align(sizeof(NormalizedDiffusionBSSRDFInputValues), 16);
}
virtual void prepare_inputs(void* data) const APPLESEED_OVERRIDE
{
NormalizedDiffusionBSSRDFInputValues* values =
reinterpret_cast<NormalizedDiffusionBSSRDFInputValues*>(data);
// Precompute the relative index of refraction.
values->m_eta = values->m_outside_ior / values->m_inside_ior;
// Apply multipliers.
values->m_reflectance *= static_cast<float>(values->m_reflectance_multiplier);
values->m_dmfp *= static_cast<float>(values->m_dmfp_multiplier);
if (values->m_reflectance.size() != values->m_dmfp.size())
{
// Since it does not really make sense to convert a dmfp,
// a per channel distance, as if it were a color,
// we instead always convert the reflectance to match the
// size of the dmfp.
if (values->m_dmfp.is_spectral())
{
Spectrum::upgrade(
values->m_reflectance,
values->m_reflectance);
}
else
{
Spectrum::downgrade(
m_lighting_conditions,
values->m_reflectance,
values->m_reflectance);
}
}
// Clamp input values.
values->m_reflectance = clamp(values->m_reflectance, 0.001f, 0.999f);
values->m_dmfp = clamp_low(values->m_dmfp, 1.0e-5f);
// Build a CDF for channel sampling.
values->m_s.resize(values->m_reflectance.size());
values->m_channel_pdf.resize(values->m_reflectance.size());
values->m_channel_cdf.resize(values->m_reflectance.size());
float cumulated_pdf = 0.0f;
for (size_t i = 0, e = values->m_channel_pdf.size(); i < e; ++i)
{
const double a = static_cast<double>(values->m_reflectance[i]);
const double s = normalized_diffusion_s(a);
values->m_s[i] = static_cast<float>(s);
const double l = values->m_dmfp[i];
const float pdf = static_cast<float>(s / l);
values->m_channel_pdf[i] = pdf;
cumulated_pdf += pdf;
values->m_channel_cdf[i] = cumulated_pdf;
}
const float rcp_cumulated_pdf = 1.0f / cumulated_pdf;
values->m_channel_pdf *= rcp_cumulated_pdf;
values->m_channel_cdf *= rcp_cumulated_pdf;
values->m_channel_cdf[values->m_channel_cdf.size() - 1] = 1.0f;
// Precompute the (square of the) max radius.
values->m_rmax2 = 0.0;
for (size_t i = 0, e = values->m_dmfp.size(); i < e; ++i)
{
const double l = static_cast<double>(values->m_dmfp[i]);
values->m_rmax2 =
max(
normalized_diffusion_max_radius(l, values->m_s[i]),
values->m_rmax2);
}
values->m_rmax2 *= values->m_rmax2;
}
virtual bool sample(
SamplingContext& sampling_context,
const void* data,
BSSRDFSample& sample) const APPLESEED_OVERRIDE
{
const NormalizedDiffusionBSSRDFInputValues* values =
reinterpret_cast<const NormalizedDiffusionBSSRDFInputValues*>(data);
if (values->m_weight == 0.0)
return false;
sampling_context.split_in_place(3, 1);
const Vector3d s = sampling_context.next_vector2<3>();
// Sample a channel.
const float* cdf_begin = &values->m_channel_cdf[0];
const size_t channel =
sample_cdf(
cdf_begin,
cdf_begin + values->m_channel_cdf.size(),
s[0]);
// Sample a radius.
const double l = values->m_dmfp[channel];
const double radius =
normalized_diffusion_sample(s[1], l, values->m_s[channel]);
// Sample an angle.
const double phi = TwoPi * s[2];
sample.m_eta = values->m_eta;
sample.m_channel = channel;
sample.m_point = Vector2d(radius * cos(phi), radius * sin(phi));
sample.m_rmax2 = values->m_rmax2;
return true;
}
virtual double get_eta(
const void* data) const APPLESEED_OVERRIDE
{
return reinterpret_cast<const NormalizedDiffusionBSSRDFInputValues*>(data)->m_eta;
}
virtual void evaluate_profile(
const void* data,
const double square_radius,
Spectrum& value) const APPLESEED_OVERRIDE
{
const NormalizedDiffusionBSSRDFInputValues* values =
reinterpret_cast<const NormalizedDiffusionBSSRDFInputValues*>(data);
const double radius = sqrt(square_radius);
value.resize(values->m_reflectance.size());
for (size_t i = 0, e = value.size(); i < e; ++i)
{
const double a = values->m_reflectance[i];
const double s = values->m_s[i];
const double l = values->m_dmfp[i];
value[i] = static_cast<float>(normalized_diffusion_profile(radius, l, s, a));
}
// Return r * R(r) * weight.
value *= static_cast<float>(radius * values->m_weight);
}
virtual double evaluate_pdf(
const void* data,
const size_t channel,
const double radius) const APPLESEED_OVERRIDE
{
const NormalizedDiffusionBSSRDFInputValues* values =
reinterpret_cast<const NormalizedDiffusionBSSRDFInputValues*>(data);
// PDF of the sampled radius.
double pdf_radius = 0.0;
for (size_t i = 0, e = values->m_reflectance.size(); i < e; ++i)
{
const double l = values->m_dmfp[i];
pdf_radius +=
normalized_diffusion_pdf(
radius,
l,
values->m_s[i])
* values->m_channel_pdf[i];
}
// PDF of the sampled angle.
const double pdf_angle = RcpTwoPi;
// Compute and return the final PDF.
return pdf_radius * pdf_angle;
}
private:
static const LightingConditions m_lighting_conditions;
};
const LightingConditions NormalizedDiffusionBSSRDF::m_lighting_conditions(
IlluminantCIED65,
XYZCMFCIE196410Deg);
}
//
// NormalizedDiffusionBSSRDFFactory class implementation.
//
const char* NormalizedDiffusionBSSRDFFactory::get_model() const
{
return Model;
}
Dictionary NormalizedDiffusionBSSRDFFactory::get_model_metadata() const
{
return
Dictionary()
.insert("name", Model)
.insert("label", "Normalized Diffusion BSSRDF");
}
DictionaryArray NormalizedDiffusionBSSRDFFactory::get_input_metadata() const
{
DictionaryArray metadata;
metadata.push_back(
Dictionary()
.insert("name", "weight")
.insert("label", "Weight")
.insert("type", "colormap")
.insert("entity_types",
Dictionary().insert("texture_instance", "Textures"))
.insert("use", "optional")
.insert("default", "1.0"));
metadata.push_back(
Dictionary()
.insert("name", "reflectance")
.insert("label", "Diffuse Surface Reflectance")
.insert("type", "colormap")
.insert("entity_types",
Dictionary()
.insert("color", "Colors")
.insert("texture_instance", "Textures"))
.insert("use", "required")
.insert("default", "0.5"));
metadata.push_back(
Dictionary()
.insert("name", "reflectance_multiplier")
.insert("label", "Diffuse Surface Reflectance Multiplier")
.insert("type", "colormap")
.insert("entity_types",
Dictionary().insert("texture_instance", "Textures"))
.insert("use", "optional")
.insert("default", "1.0"));
metadata.push_back(
Dictionary()
.insert("name", "dmfp")
.insert("label", "Diffuse Mean Free Path")
.insert("type", "colormap")
.insert("entity_types",
Dictionary()
.insert("color", "Colors")
.insert("texture_instance", "Textures"))
.insert("use", "required")
.insert("default", "0.5"));
metadata.push_back(
Dictionary()
.insert("name", "dmfp_multiplier")
.insert("label", "Diffuse Mean Free Path Multiplier")
.insert("type", "colormap")
.insert("entity_types",
Dictionary().insert("texture_instance", "Textures"))
.insert("use", "optional")
.insert("default", "1.0"));
metadata.push_back(
Dictionary()
.insert("name", "outside_ior")
.insert("label", "Outside Index of Refraction")
.insert("type", "numeric")
.insert("min_value", "1.0")
.insert("max_value", "2.5")
.insert("use", "required")
.insert("default", "1.0"));
metadata.push_back(
Dictionary()
.insert("name", "inside_ior")
.insert("label", "Inside Index of Refraction")
.insert("type", "numeric")
.insert("min_value", "1.0")
.insert("max_value", "2.5")
.insert("use", "required")
.insert("default", "1.3"));
return metadata;
}
auto_release_ptr<BSSRDF> NormalizedDiffusionBSSRDFFactory::create(
const char* name,
const ParamArray& params) const
{
return auto_release_ptr<BSSRDF>(new NormalizedDiffusionBSSRDF(name, params));
}
auto_release_ptr<BSSRDF> NormalizedDiffusionBSSRDFFactory::static_create(
const char* name,
const ParamArray& params)
{
return auto_release_ptr<BSSRDF>(new NormalizedDiffusionBSSRDF(name, params));
}
} // namespace renderer
<commit_msg>Fix race condition during initialization of static variables<commit_after>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2015-2016 Esteban Tovagliari, The appleseedhq Organization
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// Interface header.
#include "normalizeddiffusionbssrdf.h"
// appleseed.renderer headers.
#include "renderer/modeling/bssrdf/bssrdfsample.h"
#include "renderer/modeling/bssrdf/separablebssrdf.h"
#include "renderer/modeling/bssrdf/sss.h"
#include "renderer/modeling/input/inputevaluator.h"
// appleseed.foundation headers.
#include "foundation/image/colorspace.h"
#include "foundation/math/cdf.h"
#include "foundation/math/scalar.h"
#include "foundation/math/vector.h"
#include "foundation/utility/containers/dictionary.h"
#include "foundation/utility/containers/specializedarrays.h"
#include "foundation/utility/memory.h"
// Standard headers.
#include <cmath>
#include <cstddef>
// Forward declarations.
namespace renderer { class Assembly; }
namespace renderer { class ShadingContext; }
using namespace foundation;
using namespace std;
namespace renderer
{
namespace
{
//
// Normalized diffusion BSSRDF.
//
// Reference:
//
// Approximate Reflectance Profiles for Efficient Subsurface Scattering
// Per H. Christensen, Brent Burley
// http://graphics.pixar.com/library/ApproxBSSRDF/paper.pdf
//
const char* Model = "normalized_diffusion_bssrdf";
class NormalizedDiffusionBSSRDF
: public SeparableBSSRDF
{
public:
NormalizedDiffusionBSSRDF(
const char* name,
const ParamArray& params)
: SeparableBSSRDF(name, params)
, m_lighting_conditions(IlluminantCIED65, XYZCMFCIE196410Deg)
{
m_inputs.declare("weight", InputFormatScalar, "1.0");
m_inputs.declare("reflectance", InputFormatSpectralReflectance);
m_inputs.declare("reflectance_multiplier", InputFormatScalar, "1.0");
m_inputs.declare("dmfp", InputFormatSpectralReflectance);
m_inputs.declare("dmfp_multiplier", InputFormatScalar, "1.0");
m_inputs.declare("outside_ior", InputFormatScalar);
m_inputs.declare("inside_ior", InputFormatScalar);
}
virtual void release() APPLESEED_OVERRIDE
{
delete this;
}
virtual const char* get_model() const APPLESEED_OVERRIDE
{
return Model;
}
virtual size_t compute_input_data_size(
const Assembly& assembly) const APPLESEED_OVERRIDE
{
return align(sizeof(NormalizedDiffusionBSSRDFInputValues), 16);
}
virtual void prepare_inputs(void* data) const APPLESEED_OVERRIDE
{
NormalizedDiffusionBSSRDFInputValues* values =
reinterpret_cast<NormalizedDiffusionBSSRDFInputValues*>(data);
// Precompute the relative index of refraction.
values->m_eta = values->m_outside_ior / values->m_inside_ior;
// Apply multipliers.
values->m_reflectance *= static_cast<float>(values->m_reflectance_multiplier);
values->m_dmfp *= static_cast<float>(values->m_dmfp_multiplier);
if (values->m_reflectance.size() != values->m_dmfp.size())
{
// Since it does not really make sense to convert a dmfp,
// a per channel distance, as if it were a color,
// we instead always convert the reflectance to match the
// size of the dmfp.
if (values->m_dmfp.is_spectral())
{
Spectrum::upgrade(
values->m_reflectance,
values->m_reflectance);
}
else
{
Spectrum::downgrade(
m_lighting_conditions,
values->m_reflectance,
values->m_reflectance);
}
}
// Clamp input values.
values->m_reflectance = clamp(values->m_reflectance, 0.001f, 0.999f);
values->m_dmfp = clamp_low(values->m_dmfp, 1.0e-5f);
// Build a CDF for channel sampling.
values->m_s.resize(values->m_reflectance.size());
values->m_channel_pdf.resize(values->m_reflectance.size());
values->m_channel_cdf.resize(values->m_reflectance.size());
float cumulated_pdf = 0.0f;
for (size_t i = 0, e = values->m_channel_pdf.size(); i < e; ++i)
{
const double a = static_cast<double>(values->m_reflectance[i]);
const double s = normalized_diffusion_s(a);
values->m_s[i] = static_cast<float>(s);
const double l = values->m_dmfp[i];
const float pdf = static_cast<float>(s / l);
values->m_channel_pdf[i] = pdf;
cumulated_pdf += pdf;
values->m_channel_cdf[i] = cumulated_pdf;
}
const float rcp_cumulated_pdf = 1.0f / cumulated_pdf;
values->m_channel_pdf *= rcp_cumulated_pdf;
values->m_channel_cdf *= rcp_cumulated_pdf;
values->m_channel_cdf[values->m_channel_cdf.size() - 1] = 1.0f;
// Precompute the (square of the) max radius.
values->m_rmax2 = 0.0;
for (size_t i = 0, e = values->m_dmfp.size(); i < e; ++i)
{
const double l = static_cast<double>(values->m_dmfp[i]);
values->m_rmax2 =
max(
normalized_diffusion_max_radius(l, values->m_s[i]),
values->m_rmax2);
}
values->m_rmax2 *= values->m_rmax2;
}
virtual bool sample(
SamplingContext& sampling_context,
const void* data,
BSSRDFSample& sample) const APPLESEED_OVERRIDE
{
const NormalizedDiffusionBSSRDFInputValues* values =
reinterpret_cast<const NormalizedDiffusionBSSRDFInputValues*>(data);
if (values->m_weight == 0.0)
return false;
sampling_context.split_in_place(3, 1);
const Vector3d s = sampling_context.next_vector2<3>();
// Sample a channel.
const float* cdf_begin = &values->m_channel_cdf[0];
const size_t channel =
sample_cdf(
cdf_begin,
cdf_begin + values->m_channel_cdf.size(),
s[0]);
// Sample a radius.
const double l = values->m_dmfp[channel];
const double radius =
normalized_diffusion_sample(s[1], l, values->m_s[channel]);
// Sample an angle.
const double phi = TwoPi * s[2];
sample.m_eta = values->m_eta;
sample.m_channel = channel;
sample.m_point = Vector2d(radius * cos(phi), radius * sin(phi));
sample.m_rmax2 = values->m_rmax2;
return true;
}
virtual double get_eta(
const void* data) const APPLESEED_OVERRIDE
{
return reinterpret_cast<const NormalizedDiffusionBSSRDFInputValues*>(data)->m_eta;
}
virtual void evaluate_profile(
const void* data,
const double square_radius,
Spectrum& value) const APPLESEED_OVERRIDE
{
const NormalizedDiffusionBSSRDFInputValues* values =
reinterpret_cast<const NormalizedDiffusionBSSRDFInputValues*>(data);
const double radius = sqrt(square_radius);
value.resize(values->m_reflectance.size());
for (size_t i = 0, e = value.size(); i < e; ++i)
{
const double a = values->m_reflectance[i];
const double s = values->m_s[i];
const double l = values->m_dmfp[i];
value[i] = static_cast<float>(normalized_diffusion_profile(radius, l, s, a));
}
// Return r * R(r) * weight.
value *= static_cast<float>(radius * values->m_weight);
}
virtual double evaluate_pdf(
const void* data,
const size_t channel,
const double radius) const APPLESEED_OVERRIDE
{
const NormalizedDiffusionBSSRDFInputValues* values =
reinterpret_cast<const NormalizedDiffusionBSSRDFInputValues*>(data);
// PDF of the sampled radius.
double pdf_radius = 0.0;
for (size_t i = 0, e = values->m_reflectance.size(); i < e; ++i)
{
const double l = values->m_dmfp[i];
pdf_radius +=
normalized_diffusion_pdf(
radius,
l,
values->m_s[i])
* values->m_channel_pdf[i];
}
// PDF of the sampled angle.
const double pdf_angle = RcpTwoPi;
// Compute and return the final PDF.
return pdf_radius * pdf_angle;
}
private:
const LightingConditions m_lighting_conditions;
};
}
//
// NormalizedDiffusionBSSRDFFactory class implementation.
//
const char* NormalizedDiffusionBSSRDFFactory::get_model() const
{
return Model;
}
Dictionary NormalizedDiffusionBSSRDFFactory::get_model_metadata() const
{
return
Dictionary()
.insert("name", Model)
.insert("label", "Normalized Diffusion BSSRDF");
}
DictionaryArray NormalizedDiffusionBSSRDFFactory::get_input_metadata() const
{
DictionaryArray metadata;
metadata.push_back(
Dictionary()
.insert("name", "weight")
.insert("label", "Weight")
.insert("type", "colormap")
.insert("entity_types",
Dictionary().insert("texture_instance", "Textures"))
.insert("use", "optional")
.insert("default", "1.0"));
metadata.push_back(
Dictionary()
.insert("name", "reflectance")
.insert("label", "Diffuse Surface Reflectance")
.insert("type", "colormap")
.insert("entity_types",
Dictionary()
.insert("color", "Colors")
.insert("texture_instance", "Textures"))
.insert("use", "required")
.insert("default", "0.5"));
metadata.push_back(
Dictionary()
.insert("name", "reflectance_multiplier")
.insert("label", "Diffuse Surface Reflectance Multiplier")
.insert("type", "colormap")
.insert("entity_types",
Dictionary().insert("texture_instance", "Textures"))
.insert("use", "optional")
.insert("default", "1.0"));
metadata.push_back(
Dictionary()
.insert("name", "dmfp")
.insert("label", "Diffuse Mean Free Path")
.insert("type", "colormap")
.insert("entity_types",
Dictionary()
.insert("color", "Colors")
.insert("texture_instance", "Textures"))
.insert("use", "required")
.insert("default", "0.5"));
metadata.push_back(
Dictionary()
.insert("name", "dmfp_multiplier")
.insert("label", "Diffuse Mean Free Path Multiplier")
.insert("type", "colormap")
.insert("entity_types",
Dictionary().insert("texture_instance", "Textures"))
.insert("use", "optional")
.insert("default", "1.0"));
metadata.push_back(
Dictionary()
.insert("name", "outside_ior")
.insert("label", "Outside Index of Refraction")
.insert("type", "numeric")
.insert("min_value", "1.0")
.insert("max_value", "2.5")
.insert("use", "required")
.insert("default", "1.0"));
metadata.push_back(
Dictionary()
.insert("name", "inside_ior")
.insert("label", "Inside Index of Refraction")
.insert("type", "numeric")
.insert("min_value", "1.0")
.insert("max_value", "2.5")
.insert("use", "required")
.insert("default", "1.3"));
return metadata;
}
auto_release_ptr<BSSRDF> NormalizedDiffusionBSSRDFFactory::create(
const char* name,
const ParamArray& params) const
{
return auto_release_ptr<BSSRDF>(new NormalizedDiffusionBSSRDF(name, params));
}
auto_release_ptr<BSSRDF> NormalizedDiffusionBSSRDFFactory::static_create(
const char* name,
const ParamArray& params)
{
return auto_release_ptr<BSSRDF>(new NormalizedDiffusionBSSRDF(name, params));
}
} // namespace renderer
<|endoftext|>
|
<commit_before>#pragma once
#include <functional>
#include <gcl_cpp/type_info.hpp>
namespace gcl::functionnal
{
template <class F>
class trait
{ // todo : multiple operator()
using base_type = std::decay_t<F>;
using base_operator_type = decltype(&base_type::operator());
template <typename return_t, typename ... args_t>
static constexpr auto deduce(return_t(base_type::*)(args_t...) const)
{
struct deduce_t
{
constexpr deduce_t() = default;
using return_type = return_t;
using arguments_type = gcl::type_info::pack<args_t...>;
};
return deduce_t{};
}
using deducer = decltype(deduce(&base_type::operator()));
public:
using return_type = typename deducer::return_type;
using arguments_type = typename deducer::arguments_type;
};
//template <typename T, typename = void>
//struct is_callable : std::false_type {};
//template <typename T>
//struct is_callable<T, std::void_t<decltype(std::declval<T>().operator())>> : std::true_type {}; // std::decay_t
template <typename ... Fs, typename ... args_t>
auto combine_impl(gcl::type_info::pack<args_t...>, Fs && ... funcs)
{
if constexpr (sizeof...(args_t) == 0)
return [=]()
{
[[maybe_unused]] int _[] = { (funcs(), 0)... };
};
else
return [=](args_t ... args)
{
[[maybe_unused]] int _[] = { (funcs(args...), 0)... };
};
}
template <typename ... Fs>
auto combine(Fs && ... funcs)
{
using type = typename std::tuple_element<0, std::tuple<Fs...>>::type;
using trait = trait<type>;
// todo : static_assert(is_all<...>, "failed to combine heterogenous functions types");
return combine_impl(typename trait::arguments_type{}, std::forward<Fs>(funcs)...);
}
template <>
auto combine() { return []() {}; }
namespace deprecated
{
struct finally : public std::function<void()>
{
explicit finally(std::function<void()> && func)
{
func.swap(*this);
}
finally(const finally & w)
{
const_cast<finally &>(w).swap(*this);
}
~finally()
{
if (*this)
(*this)();
}
};
}
}
template
<
class F1, class F2,
typename std::enable_if_t
<
std::is_invocable_v<F1> &&
std::is_invocable_v<F2>
, int
> = 0
>
static auto operator+(F1 && f1, F2 && f2)
{
return gcl::functionnal::combine(std::forward<F1>(f1), std::forward<F2>(f2));
}
<commit_msg>gcl::functionnal : improve gcl::functionnal::combine to add homogeneous and hetegeneous combination<commit_after>#pragma once
#include <functional>
#include <gcl_cpp/type_info.hpp>
namespace gcl::functionnal
{
template <class F>
class trait
{ // todo : multiple operator()
using base_type = std::decay_t<F>;
using base_operator_type = decltype(&base_type::operator());
template <typename return_t, typename ... args_t>
static constexpr auto deduce(return_t(base_type::*)(args_t...) const)
{
struct deduce_t
{
constexpr deduce_t() = default;
using return_type = return_t;
using arguments_type = gcl::type_info::pack<args_t...>;
};
return deduce_t{};
}
using deducer = decltype(deduce(&base_type::operator()));
public:
using return_type = typename deducer::return_type;
using arguments_type = typename deducer::arguments_type;
};
//template <typename T, typename = void>
//struct is_callable : std::false_type {};
//template <typename T>
//struct is_callable<T, std::void_t<decltype(std::declval<T>().operator())>> : std::true_type {}; // std::decay_t
template <typename ... Fs, typename ... args_t>
auto combine_homogeneous_impl(gcl::type_info::pack<args_t...>, Fs && ... funcs)
{
if constexpr (sizeof...(args_t) == 0)
return [=]()
{
[[maybe_unused]] int _[] = { (funcs(), 0)... };
};
else
return [=](args_t ... args)
{
[[maybe_unused]] int _[] = { (funcs(args...), 0)... };
};
}
template <typename ... Fs>
auto combine_homogeneous(Fs && ... funcs)
{
using type = typename std::tuple_element<0, std::tuple<Fs...>>::type;
using trait = trait<type>;
// todo : static_assert(is_all<...>, "failed to combine heterogenous functions types");
// or constexpr if that call combine_heterogeneous
return combine_homogeneous_impl(typename trait::arguments_type{}, std::forward<Fs>(funcs)...);
}
template <>
auto combine_homogeneous() { return []() {}; }
template <typename ... Fs>
auto combine_heterogeneous(Fs ... funcs)
{
struct adapter : std::decay_t<Fs>...
{
adapter(std::decay_t<Fs> ... values)
: std::decay_t<Fs>(std::move(values))...
{}
using Fs::operator()...;
};
return adapter{ std::forward<Fs>(funcs)... };
}
// todo : combine(Fs ... funcs)
namespace deprecated
{
struct finally : public std::function<void()>
{
explicit finally(std::function<void()> && func)
{
func.swap(*this);
}
finally(const finally & w)
{
const_cast<finally &>(w).swap(*this);
}
~finally()
{
if (*this)
(*this)();
}
};
}
}
template
<
class F1, class F2,
typename std::enable_if_t
<
std::is_invocable_v<F1> &&
std::is_invocable_v<F2>
, int
> = 0
>
static auto operator+(F1 && f1, F2 && f2)
{
return gcl::functionnal::combine_homogeneous(std::forward<F1>(f1), std::forward<F2>(f2));
}
<|endoftext|>
|
<commit_before>#ifndef CCHRONO_TIMER
#define CCHRONO_TIMER
#include<chrono>
namespace nTool
{
class CChrono_timer
{
std::chrono::high_resolution_clock::time_point begin_;
std::chrono::high_resolution_clock::time_point end_;
public:
constexpr std::chrono::hours::rep duration_hours() const
{
return std::chrono::duration_cast<std::chrono::hours>(end_-begin_).count();
}
constexpr std::chrono::minutes::rep duration_minutes() const
{
return std::chrono::duration_cast<std::chrono::minutes>(end_-begin_).count();
}
constexpr std::chrono::seconds::rep duration_seconds() const
{
return std::chrono::duration_cast<std::chrono::seconds>(end_-begin_).count();
}
constexpr std::chrono::milliseconds::rep duration_milliseconds() const
{
return std::chrono::duration_cast<std::chrono::milliseconds>(end_-begin_).count();
}
constexpr std::chrono::microseconds::rep duration_microseconds() const
{
return std::chrono::duration_cast<std::chrono::microseconds>(end_-begin_).count();
}
constexpr std::chrono::nanoseconds::rep duration_nanoseconds() const
{
return std::chrono::duration_cast<std::chrono::nanoseconds>(end_-begin_).count();
}
inline void start() noexcept
{
begin_=std::chrono::high_resolution_clock::now();
}
inline void stop() noexcept
{
end_=std::chrono::high_resolution_clock::now();
}
};
}
#endif<commit_msg>add calc_time<commit_after>#ifndef CCHRONO_TIMER
#define CCHRONO_TIMER
#include<chrono>
namespace nTool
{
class CChrono_timer
{
std::chrono::high_resolution_clock::time_point begin_;
std::chrono::high_resolution_clock::time_point end_;
public:
constexpr std::chrono::hours::rep duration_hours() const
{
return std::chrono::duration_cast<std::chrono::hours>(end_-begin_).count();
}
constexpr std::chrono::minutes::rep duration_minutes() const
{
return std::chrono::duration_cast<std::chrono::minutes>(end_-begin_).count();
}
constexpr std::chrono::seconds::rep duration_seconds() const
{
return std::chrono::duration_cast<std::chrono::seconds>(end_-begin_).count();
}
constexpr std::chrono::milliseconds::rep duration_milliseconds() const
{
return std::chrono::duration_cast<std::chrono::milliseconds>(end_-begin_).count();
}
constexpr std::chrono::microseconds::rep duration_microseconds() const
{
return std::chrono::duration_cast<std::chrono::microseconds>(end_-begin_).count();
}
constexpr std::chrono::nanoseconds::rep duration_nanoseconds() const
{
return std::chrono::duration_cast<std::chrono::nanoseconds>(end_-begin_).count();
}
inline void start() noexcept
{
begin_=std::chrono::high_resolution_clock::now();
}
inline void stop() noexcept
{
end_=std::chrono::high_resolution_clock::now();
}
};
template<class Func,class ... Args>
CChrono_timer calc_time(const Func func,Args &&...args)
{
CChrono_timer timer;
timer.start();
func(std::forward<Args>(args)...);
timer.stop();
return timer;
}
}
#endif<|endoftext|>
|
<commit_before>#include <mill/util/logger.hpp>
#include <mill/util/file_extension.hpp>
#include <mill/traj.hpp>
#include "mode_traj_projection.hpp"
#include <iostream>
namespace mill
{
const char* mode_traj_projection_usage() noexcept
{
return "usage: mill traj projection [trajfile] [axes] [origin]\n"
" project trajectory onto a 3N-dimensional vector (axes).\n"
" To pass a 3N dimensional vector, trajectory file can be used.\n"
" The file should have the same number of elements as the traj file.\n";
}
int mode_traj_projection(std::deque<std::string_view> args)
{
using namespace std::literals::string_view_literals;
using namespace std::literals::string_literals;
if(args.empty())
{
log::error("mill traj projection: too few arguments");
log::error(mode_traj_projection_usage());
return 1;
}
const auto traj = args.front(); args.pop_front();
if(traj == "help")
{
log::info(mode_traj_projection_usage());
return 0;
}
else if(args.size() < 2)
{
log::error("mill traj projection: too few arguments");
log::info(mode_traj_projection_usage());
return 1;
}
const auto axes_file = args.front(); args.pop_front();
const auto orig_file = args.front(); args.pop_front();
const auto origin_traj = reader(orig_file).read();
const auto axes = reader(axes_file).read();
if(1 < origin_traj.size())
{
log::warn("mill traj projection: origin file (", orig_file, ") has ",
"multiple (", origin_traj.size(), ") number of structures. Only "
"the first frame is used as the origin.");
return 1;
}
const auto origin = origin_traj.at(0);
const auto output = std::string(base_name_of(traj)) + "_projected_"s +
std::string(extension_of(traj));
std::ofstream ofs(output);
if(!ofs.good())
{
log::error("mill traj projection: file open error -> ", output);
return 1;
}
ofs << "# [frame index], [coordinate along 1st axis], [coordinate along 2nd axis], ...\n";
std::size_t t = 0;
for(auto frame : reader(traj))
{
ofs << std::setw(8) << std::right << t ;
for(const auto& axis : axes)
{
if(frame.size() != axis.size())
{
log::fatal("mill traj projection: number of particles in a frame"
" differs from that of the axis");
}
if(frame.size() != origin.size())
{
log::fatal("mill traj projection: number of particles in a frame"
" differs from that of the origin");
}
double coord = 0;
for(std::size_t i=0; i<frame.size(); ++i)
{
coord += mill::dot_product(frame.at(i).position() - origin.at(i).position(), axis.at(i).position());
}
ofs << ' ' << std::setprecision(10) << coord << std::endl;
}
ofs << '\n';
}
return 0;
}
} // mill
<commit_msg>:bug: fix output format<commit_after>#include <mill/util/logger.hpp>
#include <mill/util/file_extension.hpp>
#include <mill/traj.hpp>
#include "mode_traj_projection.hpp"
#include <iostream>
namespace mill
{
const char* mode_traj_projection_usage() noexcept
{
return "usage: mill traj projection [trajfile] [axes] [origin]\n"
" project trajectory onto a 3N-dimensional vector (axes).\n"
" To pass a 3N dimensional vector, trajectory file can be used.\n"
" The file should have the same number of elements as the traj file.\n";
}
int mode_traj_projection(std::deque<std::string_view> args)
{
using namespace std::literals::string_view_literals;
using namespace std::literals::string_literals;
if(args.empty())
{
log::error("mill traj projection: too few arguments");
log::error(mode_traj_projection_usage());
return 1;
}
const auto traj = args.front(); args.pop_front();
if(traj == "help")
{
log::info(mode_traj_projection_usage());
return 0;
}
else if(args.size() < 2)
{
log::error("mill traj projection: too few arguments");
log::info(mode_traj_projection_usage());
return 1;
}
const auto axes_file = args.front(); args.pop_front();
const auto orig_file = args.front(); args.pop_front();
const auto origin_traj = reader(orig_file).read();
const auto axes = reader(axes_file).read();
if(1 < origin_traj.size())
{
log::warn("mill traj projection: origin file (", orig_file, ") has ",
"multiple (", origin_traj.size(), ") number of structures. Only "
"the first frame is used as the origin.");
return 1;
}
const auto origin = origin_traj.at(0);
const auto output = std::string(base_name_of(traj)) + "_projected_"s +
std::string(extension_of(traj));
std::ofstream ofs(output);
if(!ofs.good())
{
log::error("mill traj projection: file open error -> ", output);
return 1;
}
ofs << "# [frame index], [coordinate along 1st axis], [coordinate along 2nd axis], ...\n";
std::size_t t = 0;
for(auto frame : reader(traj))
{
ofs << std::setw(8) << std::right << t ;
for(const auto& axis : axes)
{
if(frame.size() != axis.size())
{
log::fatal("mill traj projection: number of particles in a frame"
" differs from that of the axis");
}
if(frame.size() != origin.size())
{
log::fatal("mill traj projection: number of particles in a frame"
" differs from that of the origin");
}
double coord = 0;
for(std::size_t i=0; i<frame.size(); ++i)
{
coord += mill::dot_product(frame.at(i).position() - origin.at(i).position(), axis.at(i).position());
}
ofs << ' ' << std::setprecision(10) << coord;
}
ofs << '\n';
}
return 0;
}
} // mill
<|endoftext|>
|
<commit_before>// The MIT License(MIT)
// Copyright(c) 2016 Jeff Rebacz
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files(the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and / or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions :
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#ifndef COLORWIN_HPP_INCLUDED
#define COLORWIN_HPP_INCLUDED
#include <Windows.h>
#include <iostream>
#include <stack>
namespace colorwin
{
// mix colors from wincon.h
//#define FOREGROUND_BLUE 0x0001 // text color contains blue.
//#define FOREGROUND_GREEN 0x0002 // text color contains green.
//#define FOREGROUND_RED 0x0004 // text color contains red.
//#define FOREGROUND_INTENSITY 0x0008 // text color is intensified.
enum CW_COLORS
{
red = FOREGROUND_RED | FOREGROUND_INTENSITY,
yellow = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY,
green = FOREGROUND_GREEN | FOREGROUND_INTENSITY,
cyan = FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY,
blue = FOREGROUND_BLUE | FOREGROUND_INTENSITY,
magenta = FOREGROUND_BLUE | FOREGROUND_RED | FOREGROUND_INTENSITY,
white = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY,
gray = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE,
grey = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE,
dark_gray = FOREGROUND_INTENSITY,
dark_grey = FOREGROUND_INTENSITY,
/* The following dark colors are unreadable, but comment them in and use them if you want. */
/*
dark_red = FOREGROUND_RED,
dark_yellow = FOREGROUND_RED | FOREGROUND_GREEN,
dark_green = FOREGROUND_GREEN,
dark_cyan = FOREGROUND_GREEN | FOREGROUND_BLUE,
dark_blue = FOREGROUND_BLUE,
dark_magenta = FOREGROUND_BLUE | FOREGROUND_RED,
*/
};
// Example usage: std::cout << color(yellow) << "This is a warning color!\n";
class color
{
public:
color(CW_COLORS color) : m_color(color), m_console_handle(INVALID_HANDLE_VALUE)
{
CONSOLE_SCREEN_BUFFER_INFO console_info;
m_console_handle = GetStdHandle(STD_OUTPUT_HANDLE);
if (!GetConsoleScreenBufferInfo(m_console_handle, &console_info))
{
m_console_handle = GetStdHandle(STD_ERROR_HANDLE);
if (!GetConsoleScreenBufferInfo(m_console_handle, &console_info)) // maybe standard output device has been redirected, try the standard error device
{
m_console_handle = INVALID_HANDLE_VALUE;
}
}
}
~color()
{
if (m_console_handle != INVALID_HANDLE_VALUE)
{
// Restore the previous color.
SetConsoleTextAttribute(m_console_handle, get_color_stack().top());
get_color_stack().pop();
}
}
private:
void change_color() const
{
if (m_console_handle == INVALID_HANDLE_VALUE)
return; // Can't get console info, can't change color.
CONSOLE_SCREEN_BUFFER_INFO console_info;
GetConsoleScreenBufferInfo(m_console_handle, &console_info);
// save the current attributes for restoration on destruction.
get_color_stack().push(console_info.wAttributes);
SetConsoleTextAttribute(m_console_handle, 0x0F & m_color);
}
color(color &);
color& operator=(color);
static std::stack<WORD>& get_color_stack()
{
// Use this instead of static member to avoid multiply defined symbols.
static std::stack<WORD> color_stack;
return color_stack;
}
HANDLE m_console_handle;
const CW_COLORS m_color;
friend class withcolor;
template<typename charT, typename traits> friend std::basic_ostream<charT, traits> & operator<<(std::basic_ostream<charT, traits> &lhs, colorwin::color const &rhs);
};
// Example usage :
// {
// withcolor scoped(yellow);
// cout << "This is a yellow warning!\n";
// cout << "This is a second yellow warning!\n";
// }
// -- or --
// withcolor(yellow).printf("This will be yellow\n");
class withcolor
{
public:
withcolor(CW_COLORS color) : m_color(color)
{
m_color.change_color();
}
int printf(const char* format, ...)
{
va_list vlist;
va_start(vlist, format);
int ret = vprintf(format, vlist);
va_end(vlist);
return ret;
}
#if _MSC_VER >= 1400 // printf_s offered in Visual Studio 2005
int printf_s(const char *format, ...)
{
va_list vlist;
va_start(vlist, format);
int ret = vprintf_s(format, vlist);
va_end(vlist);
return ret;
}
#endif
private:
withcolor(withcolor &);
withcolor& operator=(withcolor);
color m_color;
};
// cout << color(red) -> operator<<(cout, colorwin::color(red))
template<typename charT, typename traits> std::basic_ostream<charT, traits> & operator<<(std::basic_ostream<charT, traits> &lhs, colorwin::color const &rhs)
{
rhs.change_color();
return lhs;
}
}
#endif // COLORWIN_HPP_INCLUDED<commit_msg>When applying the color attribute, include the previous background color. Noticed that a black background was appearing in the sample code when it ran from powershell (blue background turning into a black background).<commit_after>// The MIT License(MIT)
// Copyright(c) 2016 Jeff Rebacz
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files(the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and / or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions :
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#ifndef COLORWIN_HPP_INCLUDED
#define COLORWIN_HPP_INCLUDED
#include <Windows.h>
#include <iostream>
#include <stack>
namespace colorwin
{
// mix colors from wincon.h
//#define FOREGROUND_BLUE 0x0001 // text color contains blue.
//#define FOREGROUND_GREEN 0x0002 // text color contains green.
//#define FOREGROUND_RED 0x0004 // text color contains red.
//#define FOREGROUND_INTENSITY 0x0008 // text color is intensified.
enum CW_COLORS
{
red = FOREGROUND_RED | FOREGROUND_INTENSITY,
yellow = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY,
green = FOREGROUND_GREEN | FOREGROUND_INTENSITY,
cyan = FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY,
blue = FOREGROUND_BLUE | FOREGROUND_INTENSITY,
magenta = FOREGROUND_BLUE | FOREGROUND_RED | FOREGROUND_INTENSITY,
white = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY,
gray = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE,
grey = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE,
dark_gray = FOREGROUND_INTENSITY,
dark_grey = FOREGROUND_INTENSITY,
/* The following dark colors are unreadable, but comment them in and use them if you want. */
/*
dark_red = FOREGROUND_RED,
dark_yellow = FOREGROUND_RED | FOREGROUND_GREEN,
dark_green = FOREGROUND_GREEN,
dark_cyan = FOREGROUND_GREEN | FOREGROUND_BLUE,
dark_blue = FOREGROUND_BLUE,
dark_magenta = FOREGROUND_BLUE | FOREGROUND_RED,
*/
};
// Example usage: std::cout << color(yellow) << "This is a warning color!\n";
class color
{
public:
color(CW_COLORS color) : m_color(color), m_console_handle(INVALID_HANDLE_VALUE)
{
CONSOLE_SCREEN_BUFFER_INFO console_info;
m_console_handle = GetStdHandle(STD_OUTPUT_HANDLE);
if (!GetConsoleScreenBufferInfo(m_console_handle, &console_info))
{
m_console_handle = GetStdHandle(STD_ERROR_HANDLE);
if (!GetConsoleScreenBufferInfo(m_console_handle, &console_info)) // maybe standard output device has been redirected, try the standard error device
{
m_console_handle = INVALID_HANDLE_VALUE;
}
}
}
~color()
{
if (m_console_handle != INVALID_HANDLE_VALUE)
{
// Restore the previous color.
SetConsoleTextAttribute(m_console_handle, get_color_stack().top());
get_color_stack().pop();
}
}
private:
void change_color() const
{
if (m_console_handle == INVALID_HANDLE_VALUE)
return; // Can't get console info, can't change color.
CONSOLE_SCREEN_BUFFER_INFO console_info;
GetConsoleScreenBufferInfo(m_console_handle, &console_info);
// save the current attributes for restoration on destruction.
get_color_stack().push(console_info.wAttributes);
SetConsoleTextAttribute(m_console_handle, 0x0F & m_color | 0xf0 & console_info.wAttributes); // save the background color
}
color(color &);
color& operator=(color);
static std::stack<WORD>& get_color_stack()
{
// Use this instead of static member to avoid multiply defined symbols.
static std::stack<WORD> color_stack;
return color_stack;
}
HANDLE m_console_handle;
const CW_COLORS m_color;
friend class withcolor;
template<typename charT, typename traits> friend std::basic_ostream<charT, traits> & operator<<(std::basic_ostream<charT, traits> &lhs, colorwin::color const &rhs);
};
// Example usage :
// {
// withcolor scoped(yellow);
// cout << "This is a yellow warning!\n";
// cout << "This is a second yellow warning!\n";
// }
// -- or --
// withcolor(yellow).printf("This will be yellow\n");
class withcolor
{
public:
withcolor(CW_COLORS color) : m_color(color)
{
m_color.change_color();
}
int printf(const char* format, ...)
{
va_list vlist;
va_start(vlist, format);
int ret = vprintf(format, vlist);
va_end(vlist);
return ret;
}
#if _MSC_VER >= 1400 // printf_s offered in Visual Studio 2005
int printf_s(const char *format, ...)
{
va_list vlist;
va_start(vlist, format);
int ret = vprintf_s(format, vlist);
va_end(vlist);
return ret;
}
#endif
private:
withcolor(withcolor &);
withcolor& operator=(withcolor);
color m_color;
};
// cout << color(red) -> operator<<(cout, colorwin::color(red))
template<typename charT, typename traits> std::basic_ostream<charT, traits> & operator<<(std::basic_ostream<charT, traits> &lhs, colorwin::color const &rhs)
{
rhs.change_color();
return lhs;
}
}
#endif // COLORWIN_HPP_INCLUDED<|endoftext|>
|
<commit_before>// Copyright (c) 2011-2012 Ryan Prichard
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
#include <string.h>
#include <algorithm>
#include "EventLoop.h"
#include "NamedPipe.h"
#include "../shared/DebugClient.h"
#include "../shared/StringUtil.h"
#include "../shared/WindowsSecurity.h"
#include "../shared/WinptyAssert.h"
// Returns true if anything happens (data received, data sent, pipe error).
bool NamedPipe::serviceIo(std::vector<HANDLE> *waitHandles)
{
bool justConnected = false;
const auto kError = ServiceResult::Error;
const auto kProgress = ServiceResult::Progress;
const auto kNoProgress = ServiceResult::NoProgress;
if (m_handle == NULL) {
return false;
}
if (m_connectEvent.get() != nullptr) {
// We're still connecting this server pipe. Check whether the pipe is
// now connected. If it isn't, add the pipe to the list of handles to
// wait on.
DWORD actual = 0;
BOOL success =
GetOverlappedResult(m_handle, &m_connectOver, &actual, FALSE);
if (!success && GetLastError() == ERROR_PIPE_CONNECTED) {
// I'm not sure this can happen, but it's easy to handle if it
// does.
success = TRUE;
}
if (!success) {
ASSERT(GetLastError() == ERROR_IO_INCOMPLETE &&
"Pended ConnectNamedPipe call failed");
waitHandles->push_back(m_connectEvent.get());
} else {
TRACE("Server pipe [%s] connected",
utf8FromWide(m_name).c_str());
m_connectEvent.dispose();
startPipeWorkers();
justConnected = true;
}
}
const auto readProgress = m_inputWorker ? m_inputWorker->service() : kNoProgress;
const auto writeProgress = m_outputWorker ? m_outputWorker->service() : kNoProgress;
if (readProgress == kError || writeProgress == kError) {
closePipe();
return true;
}
if (m_inputWorker && m_inputWorker->getWaitEvent() != nullptr) {
waitHandles->push_back(m_inputWorker->getWaitEvent());
}
if (m_outputWorker && m_outputWorker->getWaitEvent() != nullptr) {
waitHandles->push_back(m_outputWorker->getWaitEvent());
}
return justConnected
|| readProgress == kProgress
|| writeProgress == kProgress;
}
// manual reset, initially unset
static OwnedHandle createEvent() {
HANDLE ret = CreateEventW(nullptr, TRUE, FALSE, nullptr);
ASSERT(ret != nullptr && "CreateEventW failed");
return OwnedHandle(ret);
}
NamedPipe::IoWorker::IoWorker(NamedPipe &namedPipe) :
m_namedPipe(namedPipe),
m_event(createEvent())
{
}
NamedPipe::ServiceResult NamedPipe::IoWorker::service()
{
ServiceResult progress = ServiceResult::NoProgress;
if (m_pending) {
DWORD actual = 0;
BOOL ret = GetOverlappedResult(m_namedPipe.m_handle, &m_over, &actual, FALSE);
if (!ret) {
if (GetLastError() == ERROR_IO_INCOMPLETE) {
// There is a pending I/O.
return progress;
} else {
// Pipe error.
return ServiceResult::Error;
}
}
ResetEvent(m_event.get());
m_pending = false;
completeIo(actual);
m_currentIoSize = 0;
progress = ServiceResult::Progress;
}
DWORD nextSize = 0;
bool isRead = false;
while (shouldIssueIo(&nextSize, &isRead)) {
m_currentIoSize = nextSize;
DWORD actual = 0;
memset(&m_over, 0, sizeof(m_over));
m_over.hEvent = m_event.get();
BOOL ret = isRead
? ReadFile(m_namedPipe.m_handle, m_buffer, nextSize, &actual, &m_over)
: WriteFile(m_namedPipe.m_handle, m_buffer, nextSize, &actual, &m_over);
if (!ret) {
if (GetLastError() == ERROR_IO_PENDING) {
// There is a pending I/O.
m_pending = true;
return progress;
} else {
// Pipe error.
return ServiceResult::Error;
}
}
ResetEvent(m_event.get());
completeIo(actual);
m_currentIoSize = 0;
progress = ServiceResult::Progress;
}
return progress;
}
// This function is called after CancelIo has returned. We need to block until
// the I/O operations have completed, which should happen very quickly.
// https://blogs.msdn.microsoft.com/oldnewthing/20110202-00/?p=11613
void NamedPipe::IoWorker::waitForCanceledIo()
{
if (m_pending) {
DWORD actual = 0;
GetOverlappedResult(m_namedPipe.m_handle, &m_over, &actual, TRUE);
m_pending = false;
}
}
HANDLE NamedPipe::IoWorker::getWaitEvent()
{
return m_pending ? m_event.get() : NULL;
}
void NamedPipe::InputWorker::completeIo(DWORD size)
{
m_namedPipe.m_inQueue.append(m_buffer, size);
}
bool NamedPipe::InputWorker::shouldIssueIo(DWORD *size, bool *isRead)
{
*isRead = true;
ASSERT(!m_namedPipe.isConnecting());
if (m_namedPipe.isClosed()) {
return false;
} else if (m_namedPipe.m_inQueue.size() < m_namedPipe.readBufferSize()) {
*size = kIoSize;
return true;
} else {
return false;
}
}
void NamedPipe::OutputWorker::completeIo(DWORD size)
{
ASSERT(size == m_currentIoSize);
}
bool NamedPipe::OutputWorker::shouldIssueIo(DWORD *size, bool *isRead)
{
*isRead = false;
if (!m_namedPipe.m_outQueue.empty()) {
auto &out = m_namedPipe.m_outQueue;
const DWORD writeSize = std::min<size_t>(out.size(), kIoSize);
std::copy(&out[0], &out[writeSize], m_buffer);
out.erase(0, writeSize);
*size = writeSize;
return true;
} else {
return false;
}
}
DWORD NamedPipe::OutputWorker::getPendingIoSize()
{
return m_pending ? m_currentIoSize : 0;
}
void NamedPipe::openServerPipe(LPCWSTR pipeName, OpenMode::t openMode,
int outBufferSize, int inBufferSize) {
ASSERT(isClosed());
ASSERT((openMode & OpenMode::Duplex) != 0);
const DWORD winOpenMode =
((openMode & OpenMode::Reading) ? PIPE_ACCESS_INBOUND : 0)
| ((openMode & OpenMode::Writing) ? PIPE_ACCESS_OUTBOUND : 0)
| FILE_FLAG_FIRST_PIPE_INSTANCE
| FILE_FLAG_OVERLAPPED;
const auto sd = createPipeSecurityDescriptorOwnerFullControl();
ASSERT(sd && "error creating data pipe SECURITY_DESCRIPTOR");
SECURITY_ATTRIBUTES sa = {};
sa.nLength = sizeof(sa);
sa.lpSecurityDescriptor = sd.get();
HANDLE handle = CreateNamedPipeW(
pipeName,
/*dwOpenMode=*/winOpenMode,
/*dwPipeMode=*/rejectRemoteClientsPipeFlag(),
/*nMaxInstances=*/1,
/*nOutBufferSize=*/outBufferSize,
/*nInBufferSize=*/inBufferSize,
/*nDefaultTimeOut=*/30000,
&sa);
TRACE("opened server pipe [%s], handle == %p",
utf8FromWide(pipeName).c_str(), handle);
ASSERT(handle != INVALID_HANDLE_VALUE && "Could not open server pipe");
m_name = pipeName;
m_handle = handle;
m_openMode = openMode;
// Start an asynchronous connection attempt.
m_connectEvent = createEvent();
memset(&m_connectOver, 0, sizeof(m_connectOver));
m_connectOver.hEvent = m_connectEvent.get();
BOOL success = ConnectNamedPipe(m_handle, &m_connectOver);
const auto err = GetLastError();
if (!success && err == ERROR_PIPE_CONNECTED) {
success = TRUE;
}
if (success) {
TRACE("Server pipe [%s] connected", utf8FromWide(pipeName).c_str());
m_connectEvent.dispose();
startPipeWorkers();
} else if (err != ERROR_IO_PENDING) {
ASSERT(false && "ConnectNamedPipe call failed");
}
}
void NamedPipe::connectToServer(LPCWSTR pipeName, OpenMode::t openMode)
{
ASSERT(isClosed());
ASSERT((openMode & OpenMode::Duplex) != 0);
HANDLE handle = CreateFileW(
pipeName,
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
OPEN_EXISTING,
SECURITY_SQOS_PRESENT | SECURITY_IDENTIFICATION | FILE_FLAG_OVERLAPPED,
NULL);
TRACE("connected to [%s], handle == %p",
utf8FromWide(pipeName).c_str(), handle);
ASSERT(handle != INVALID_HANDLE_VALUE && "Could not connect to pipe");
m_name = pipeName;
m_handle = handle;
m_openMode = openMode;
startPipeWorkers();
}
void NamedPipe::startPipeWorkers()
{
if (m_openMode & OpenMode::Reading) {
m_inputWorker.reset(new InputWorker(*this));
}
if (m_openMode & OpenMode::Writing) {
m_outputWorker.reset(new OutputWorker(*this));
}
}
size_t NamedPipe::bytesToSend()
{
ASSERT(m_openMode & OpenMode::Writing);
auto ret = m_outQueue.size();
if (m_outputWorker != NULL) {
ret += m_outputWorker->getPendingIoSize();
}
return ret;
}
void NamedPipe::write(const void *data, size_t size)
{
ASSERT(m_openMode & OpenMode::Writing);
m_outQueue.append(reinterpret_cast<const char*>(data), size);
}
void NamedPipe::write(const char *text)
{
write(text, strlen(text));
}
size_t NamedPipe::readBufferSize()
{
ASSERT(m_openMode & OpenMode::Reading);
return m_readBufferSize;
}
void NamedPipe::setReadBufferSize(size_t size)
{
ASSERT(m_openMode & OpenMode::Reading);
m_readBufferSize = size;
}
size_t NamedPipe::bytesAvailable()
{
ASSERT(m_openMode & OpenMode::Reading);
return m_inQueue.size();
}
size_t NamedPipe::peek(void *data, size_t size)
{
ASSERT(m_openMode & OpenMode::Reading);
const auto out = reinterpret_cast<char*>(data);
const size_t ret = std::min(size, m_inQueue.size());
std::copy(&m_inQueue[0], &m_inQueue[size], out);
return ret;
}
size_t NamedPipe::read(void *data, size_t size)
{
size_t ret = peek(data, size);
m_inQueue.erase(0, ret);
return ret;
}
std::string NamedPipe::readToString(size_t size)
{
ASSERT(m_openMode & OpenMode::Reading);
size_t retSize = std::min(size, m_inQueue.size());
std::string ret = m_inQueue.substr(0, retSize);
m_inQueue.erase(0, retSize);
return ret;
}
std::string NamedPipe::readAllToString()
{
ASSERT(m_openMode & OpenMode::Reading);
std::string ret = m_inQueue;
m_inQueue.clear();
return ret;
}
void NamedPipe::closePipe()
{
if (m_handle == NULL) {
return;
}
CancelIo(m_handle);
if (m_connectEvent.get() != nullptr) {
DWORD actual = 0;
GetOverlappedResult(m_handle, &m_connectOver, &actual, TRUE);
m_connectEvent.dispose();
}
if (m_inputWorker) {
m_inputWorker->waitForCanceledIo();
m_inputWorker.reset();
}
if (m_outputWorker) {
m_outputWorker->waitForCanceledIo();
m_outputWorker.reset();
}
CloseHandle(m_handle);
m_handle = NULL;
}
<commit_msg>Fix a read-from-end-of-buffer issue<commit_after>// Copyright (c) 2011-2012 Ryan Prichard
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
#include <string.h>
#include <algorithm>
#include "EventLoop.h"
#include "NamedPipe.h"
#include "../shared/DebugClient.h"
#include "../shared/StringUtil.h"
#include "../shared/WindowsSecurity.h"
#include "../shared/WinptyAssert.h"
// Returns true if anything happens (data received, data sent, pipe error).
bool NamedPipe::serviceIo(std::vector<HANDLE> *waitHandles)
{
bool justConnected = false;
const auto kError = ServiceResult::Error;
const auto kProgress = ServiceResult::Progress;
const auto kNoProgress = ServiceResult::NoProgress;
if (m_handle == NULL) {
return false;
}
if (m_connectEvent.get() != nullptr) {
// We're still connecting this server pipe. Check whether the pipe is
// now connected. If it isn't, add the pipe to the list of handles to
// wait on.
DWORD actual = 0;
BOOL success =
GetOverlappedResult(m_handle, &m_connectOver, &actual, FALSE);
if (!success && GetLastError() == ERROR_PIPE_CONNECTED) {
// I'm not sure this can happen, but it's easy to handle if it
// does.
success = TRUE;
}
if (!success) {
ASSERT(GetLastError() == ERROR_IO_INCOMPLETE &&
"Pended ConnectNamedPipe call failed");
waitHandles->push_back(m_connectEvent.get());
} else {
TRACE("Server pipe [%s] connected",
utf8FromWide(m_name).c_str());
m_connectEvent.dispose();
startPipeWorkers();
justConnected = true;
}
}
const auto readProgress = m_inputWorker ? m_inputWorker->service() : kNoProgress;
const auto writeProgress = m_outputWorker ? m_outputWorker->service() : kNoProgress;
if (readProgress == kError || writeProgress == kError) {
closePipe();
return true;
}
if (m_inputWorker && m_inputWorker->getWaitEvent() != nullptr) {
waitHandles->push_back(m_inputWorker->getWaitEvent());
}
if (m_outputWorker && m_outputWorker->getWaitEvent() != nullptr) {
waitHandles->push_back(m_outputWorker->getWaitEvent());
}
return justConnected
|| readProgress == kProgress
|| writeProgress == kProgress;
}
// manual reset, initially unset
static OwnedHandle createEvent() {
HANDLE ret = CreateEventW(nullptr, TRUE, FALSE, nullptr);
ASSERT(ret != nullptr && "CreateEventW failed");
return OwnedHandle(ret);
}
NamedPipe::IoWorker::IoWorker(NamedPipe &namedPipe) :
m_namedPipe(namedPipe),
m_event(createEvent())
{
}
NamedPipe::ServiceResult NamedPipe::IoWorker::service()
{
ServiceResult progress = ServiceResult::NoProgress;
if (m_pending) {
DWORD actual = 0;
BOOL ret = GetOverlappedResult(m_namedPipe.m_handle, &m_over, &actual, FALSE);
if (!ret) {
if (GetLastError() == ERROR_IO_INCOMPLETE) {
// There is a pending I/O.
return progress;
} else {
// Pipe error.
return ServiceResult::Error;
}
}
ResetEvent(m_event.get());
m_pending = false;
completeIo(actual);
m_currentIoSize = 0;
progress = ServiceResult::Progress;
}
DWORD nextSize = 0;
bool isRead = false;
while (shouldIssueIo(&nextSize, &isRead)) {
m_currentIoSize = nextSize;
DWORD actual = 0;
memset(&m_over, 0, sizeof(m_over));
m_over.hEvent = m_event.get();
BOOL ret = isRead
? ReadFile(m_namedPipe.m_handle, m_buffer, nextSize, &actual, &m_over)
: WriteFile(m_namedPipe.m_handle, m_buffer, nextSize, &actual, &m_over);
if (!ret) {
if (GetLastError() == ERROR_IO_PENDING) {
// There is a pending I/O.
m_pending = true;
return progress;
} else {
// Pipe error.
return ServiceResult::Error;
}
}
ResetEvent(m_event.get());
completeIo(actual);
m_currentIoSize = 0;
progress = ServiceResult::Progress;
}
return progress;
}
// This function is called after CancelIo has returned. We need to block until
// the I/O operations have completed, which should happen very quickly.
// https://blogs.msdn.microsoft.com/oldnewthing/20110202-00/?p=11613
void NamedPipe::IoWorker::waitForCanceledIo()
{
if (m_pending) {
DWORD actual = 0;
GetOverlappedResult(m_namedPipe.m_handle, &m_over, &actual, TRUE);
m_pending = false;
}
}
HANDLE NamedPipe::IoWorker::getWaitEvent()
{
return m_pending ? m_event.get() : NULL;
}
void NamedPipe::InputWorker::completeIo(DWORD size)
{
m_namedPipe.m_inQueue.append(m_buffer, size);
}
bool NamedPipe::InputWorker::shouldIssueIo(DWORD *size, bool *isRead)
{
*isRead = true;
ASSERT(!m_namedPipe.isConnecting());
if (m_namedPipe.isClosed()) {
return false;
} else if (m_namedPipe.m_inQueue.size() < m_namedPipe.readBufferSize()) {
*size = kIoSize;
return true;
} else {
return false;
}
}
void NamedPipe::OutputWorker::completeIo(DWORD size)
{
ASSERT(size == m_currentIoSize);
}
bool NamedPipe::OutputWorker::shouldIssueIo(DWORD *size, bool *isRead)
{
*isRead = false;
if (!m_namedPipe.m_outQueue.empty()) {
auto &out = m_namedPipe.m_outQueue;
const DWORD writeSize = std::min<size_t>(out.size(), kIoSize);
std::copy(&out[0], &out[writeSize], m_buffer);
out.erase(0, writeSize);
*size = writeSize;
return true;
} else {
return false;
}
}
DWORD NamedPipe::OutputWorker::getPendingIoSize()
{
return m_pending ? m_currentIoSize : 0;
}
void NamedPipe::openServerPipe(LPCWSTR pipeName, OpenMode::t openMode,
int outBufferSize, int inBufferSize) {
ASSERT(isClosed());
ASSERT((openMode & OpenMode::Duplex) != 0);
const DWORD winOpenMode =
((openMode & OpenMode::Reading) ? PIPE_ACCESS_INBOUND : 0)
| ((openMode & OpenMode::Writing) ? PIPE_ACCESS_OUTBOUND : 0)
| FILE_FLAG_FIRST_PIPE_INSTANCE
| FILE_FLAG_OVERLAPPED;
const auto sd = createPipeSecurityDescriptorOwnerFullControl();
ASSERT(sd && "error creating data pipe SECURITY_DESCRIPTOR");
SECURITY_ATTRIBUTES sa = {};
sa.nLength = sizeof(sa);
sa.lpSecurityDescriptor = sd.get();
HANDLE handle = CreateNamedPipeW(
pipeName,
/*dwOpenMode=*/winOpenMode,
/*dwPipeMode=*/rejectRemoteClientsPipeFlag(),
/*nMaxInstances=*/1,
/*nOutBufferSize=*/outBufferSize,
/*nInBufferSize=*/inBufferSize,
/*nDefaultTimeOut=*/30000,
&sa);
TRACE("opened server pipe [%s], handle == %p",
utf8FromWide(pipeName).c_str(), handle);
ASSERT(handle != INVALID_HANDLE_VALUE && "Could not open server pipe");
m_name = pipeName;
m_handle = handle;
m_openMode = openMode;
// Start an asynchronous connection attempt.
m_connectEvent = createEvent();
memset(&m_connectOver, 0, sizeof(m_connectOver));
m_connectOver.hEvent = m_connectEvent.get();
BOOL success = ConnectNamedPipe(m_handle, &m_connectOver);
const auto err = GetLastError();
if (!success && err == ERROR_PIPE_CONNECTED) {
success = TRUE;
}
if (success) {
TRACE("Server pipe [%s] connected", utf8FromWide(pipeName).c_str());
m_connectEvent.dispose();
startPipeWorkers();
} else if (err != ERROR_IO_PENDING) {
ASSERT(false && "ConnectNamedPipe call failed");
}
}
void NamedPipe::connectToServer(LPCWSTR pipeName, OpenMode::t openMode)
{
ASSERT(isClosed());
ASSERT((openMode & OpenMode::Duplex) != 0);
HANDLE handle = CreateFileW(
pipeName,
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
OPEN_EXISTING,
SECURITY_SQOS_PRESENT | SECURITY_IDENTIFICATION | FILE_FLAG_OVERLAPPED,
NULL);
TRACE("connected to [%s], handle == %p",
utf8FromWide(pipeName).c_str(), handle);
ASSERT(handle != INVALID_HANDLE_VALUE && "Could not connect to pipe");
m_name = pipeName;
m_handle = handle;
m_openMode = openMode;
startPipeWorkers();
}
void NamedPipe::startPipeWorkers()
{
if (m_openMode & OpenMode::Reading) {
m_inputWorker.reset(new InputWorker(*this));
}
if (m_openMode & OpenMode::Writing) {
m_outputWorker.reset(new OutputWorker(*this));
}
}
size_t NamedPipe::bytesToSend()
{
ASSERT(m_openMode & OpenMode::Writing);
auto ret = m_outQueue.size();
if (m_outputWorker != NULL) {
ret += m_outputWorker->getPendingIoSize();
}
return ret;
}
void NamedPipe::write(const void *data, size_t size)
{
ASSERT(m_openMode & OpenMode::Writing);
m_outQueue.append(reinterpret_cast<const char*>(data), size);
}
void NamedPipe::write(const char *text)
{
write(text, strlen(text));
}
size_t NamedPipe::readBufferSize()
{
ASSERT(m_openMode & OpenMode::Reading);
return m_readBufferSize;
}
void NamedPipe::setReadBufferSize(size_t size)
{
ASSERT(m_openMode & OpenMode::Reading);
m_readBufferSize = size;
}
size_t NamedPipe::bytesAvailable()
{
ASSERT(m_openMode & OpenMode::Reading);
return m_inQueue.size();
}
size_t NamedPipe::peek(void *data, size_t size)
{
ASSERT(m_openMode & OpenMode::Reading);
const auto out = reinterpret_cast<char*>(data);
const size_t ret = std::min(size, m_inQueue.size());
std::copy(&m_inQueue[0], &m_inQueue[ret], out);
return ret;
}
size_t NamedPipe::read(void *data, size_t size)
{
size_t ret = peek(data, size);
m_inQueue.erase(0, ret);
return ret;
}
std::string NamedPipe::readToString(size_t size)
{
ASSERT(m_openMode & OpenMode::Reading);
size_t retSize = std::min(size, m_inQueue.size());
std::string ret = m_inQueue.substr(0, retSize);
m_inQueue.erase(0, retSize);
return ret;
}
std::string NamedPipe::readAllToString()
{
ASSERT(m_openMode & OpenMode::Reading);
std::string ret = m_inQueue;
m_inQueue.clear();
return ret;
}
void NamedPipe::closePipe()
{
if (m_handle == NULL) {
return;
}
CancelIo(m_handle);
if (m_connectEvent.get() != nullptr) {
DWORD actual = 0;
GetOverlappedResult(m_handle, &m_connectOver, &actual, TRUE);
m_connectEvent.dispose();
}
if (m_inputWorker) {
m_inputWorker->waitForCanceledIo();
m_inputWorker.reset();
}
if (m_outputWorker) {
m_outputWorker->waitForCanceledIo();
m_outputWorker.reset();
}
CloseHandle(m_handle);
m_handle = NULL;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* 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.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_desktop.hxx"
#include "dp_update.hxx"
#include "dp_version.hxx"
#include "dp_identifier.hxx"
#include "dp_descriptioninfoset.hxx"
#include "rtl/bootstrap.hxx"
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using ::rtl::OUString;
using ::rtl::OString;
namespace dp_misc {
namespace {
int determineHighestVersion(
::rtl::OUString const & userVersion,
::rtl::OUString const & sharedVersion,
::rtl::OUString const & bundledVersion,
::rtl::OUString const & onlineVersion)
{
int index = 0;
OUString greatest = userVersion;
if (dp_misc::compareVersions(sharedVersion, greatest) == dp_misc::GREATER)
{
index = 1;
greatest = sharedVersion;
}
if (dp_misc::compareVersions(bundledVersion, greatest) == dp_misc::GREATER)
{
index = 2;
greatest = bundledVersion;
}
if (dp_misc::compareVersions(onlineVersion, greatest) == dp_misc::GREATER)
{
index = 3;
}
return index;
}
Sequence< Reference< xml::dom::XElement > >
getUpdateInformation( Reference<deployment::XUpdateInformationProvider > const & updateInformation,
Sequence< OUString > const & urls,
OUString const & identifier,
uno::Any & out_error)
{
try {
return updateInformation->getUpdateInformation(urls, identifier);
} catch (uno::RuntimeException &) {
throw;
} catch (ucb::CommandFailedException & e) {
out_error = e.Reason;
} catch (ucb::CommandAbortedException &) {
} catch (uno::Exception & e) {
out_error = uno::makeAny(e);
}
return
Sequence<Reference< xml::dom::XElement > >();
}
//Put in anonymous namespace
void getOwnUpdateInfos(
Reference<uno::XComponentContext> const & xContext,
Reference<deployment::XUpdateInformationProvider > const & updateInformation,
UpdateInfoMap& inout_map, std::vector<std::pair<Reference<deployment::XPackage>, uno::Any> > & out_errors,
bool & out_allFound)
{
bool allHaveOwnUpdateInformation = true;
for (UpdateInfoMap::iterator i = inout_map.begin(); i != inout_map.end(); i++)
{
OSL_ASSERT(i->second.extension.is());
Sequence<OUString> urls(i->second.extension->getUpdateInformationURLs());
if (urls.getLength())
{
const OUString id = dp_misc::getIdentifier(i->second.extension);
uno::Any anyError;
//It is unclear from the idl if there can be a null reference returned.
//However all valid information should be the same
Sequence<Reference< xml::dom::XElement > >
infos(getUpdateInformation(updateInformation, urls, id, anyError));
if (anyError.hasValue())
out_errors.push_back(std::make_pair(i->second.extension, anyError));
for (sal_Int32 j = 0; j < infos.getLength(); ++j)
{
dp_misc::DescriptionInfoset infoset(
xContext,
Reference< xml::dom::XNode >(infos[j], UNO_QUERY_THROW));
if (!infoset.hasDescription())
continue;
boost::optional< OUString > id2(infoset.getIdentifier());
if (!id2)
continue;
OSL_ASSERT(*id2 == id);
if (*id2 == id)
{
i->second.version = infoset.getVersion();
i->second.info = Reference< xml::dom::XNode >(
infos[j], UNO_QUERY_THROW);
}
break;
}
}
else
{
allHaveOwnUpdateInformation &= false;
}
}
out_allFound = allHaveOwnUpdateInformation;
}
void getDefaultUpdateInfos(
Reference<uno::XComponentContext> const & xContext,
Reference<deployment::XUpdateInformationProvider > const & updateInformation,
UpdateInfoMap& inout_map,
std::vector<std::pair<Reference<deployment::XPackage>, uno::Any> > & out_errors)
{
const rtl::OUString sDefaultURL(dp_misc::getExtensionDefaultUpdateURL());
OSL_ASSERT(sDefaultURL.getLength());
Any anyError;
Sequence< Reference< xml::dom::XElement > >
infos(
getUpdateInformation(
updateInformation,
Sequence< OUString >(&sDefaultURL, 1), OUString(), anyError));
if (anyError.hasValue())
out_errors.push_back(std::make_pair(Reference<deployment::XPackage>(), anyError));
for (sal_Int32 i = 0; i < infos.getLength(); ++i)
{
Reference< xml::dom::XNode > node(infos[i], UNO_QUERY_THROW);
dp_misc::DescriptionInfoset infoset(xContext, node);
boost::optional< OUString > id(infoset.getIdentifier());
if (!id) {
continue;
}
UpdateInfoMap::iterator j = inout_map.find(*id);
if (j != inout_map.end())
{
//skip those extension which provide its own update urls
if (j->second.extension->getUpdateInformationURLs().getLength())
continue;
OUString v(infoset.getVersion());
//look for the highest version in the online repository
if (dp_misc::compareVersions(v, j->second.version) ==
dp_misc::GREATER)
{
j->second.version = v;
j->second.info = node;
}
}
}
}
} // anon namespace
OUString getExtensionDefaultUpdateURL()
{
::rtl::OUString sUrl(
RTL_CONSTASCII_USTRINGPARAM(
"${$BRAND_BASE_DIR/program/" SAL_CONFIGFILE("version")
":Version:ExtensionUpdateURL}"));
::rtl::Bootstrap::expandMacros(sUrl);
return sUrl;
}
/* returns the index of the greatest version, starting with 0
*/
UPDATE_SOURCE isUpdateUserExtension(
bool bReadOnlyShared,
::rtl::OUString const & userVersion,
::rtl::OUString const & sharedVersion,
::rtl::OUString const & bundledVersion,
::rtl::OUString const & onlineVersion)
{
UPDATE_SOURCE retVal = UPDATE_SOURCE_NONE;
if (bReadOnlyShared)
{
if (userVersion.getLength())
{
int index = determineHighestVersion(
userVersion, sharedVersion, bundledVersion, onlineVersion);
if (index == 1)
retVal = UPDATE_SOURCE_SHARED;
else if (index == 2)
retVal = UPDATE_SOURCE_BUNDLED;
else if (index == 3)
retVal = UPDATE_SOURCE_ONLINE;
}
else if (sharedVersion.getLength())
{
int index = determineHighestVersion(
OUString(), sharedVersion, bundledVersion, onlineVersion);
if (index == 2)
retVal = UPDATE_SOURCE_BUNDLED;
else if (index == 3)
retVal = UPDATE_SOURCE_ONLINE;
}
else if (bundledVersion.getLength())
{
int index = determineHighestVersion(
OUString(), OUString(), bundledVersion, onlineVersion);
if (index == 3)
retVal = UPDATE_SOURCE_ONLINE;
}
}
else
{
if (userVersion.getLength())
{
int index = determineHighestVersion(
userVersion, sharedVersion, bundledVersion, onlineVersion);
if (index == 1)
retVal = UPDATE_SOURCE_SHARED;
else if (index == 2)
retVal = UPDATE_SOURCE_BUNDLED;
else if (index == 3)
retVal = UPDATE_SOURCE_ONLINE;
}
}
return retVal;
}
UPDATE_SOURCE isUpdateSharedExtension(
bool bReadOnlyShared,
::rtl::OUString const & sharedVersion,
::rtl::OUString const & bundledVersion,
::rtl::OUString const & onlineVersion)
{
if (bReadOnlyShared)
return UPDATE_SOURCE_NONE;
UPDATE_SOURCE retVal = UPDATE_SOURCE_NONE;
if (sharedVersion.getLength())
{
int index = determineHighestVersion(
OUString(), sharedVersion, bundledVersion, onlineVersion);
if (index == 2)
retVal = UPDATE_SOURCE_BUNDLED;
else if (index == 3)
retVal = UPDATE_SOURCE_ONLINE;
}
else if (bundledVersion.getLength())
{
int index = determineHighestVersion(
OUString(), OUString(), bundledVersion, onlineVersion);
if (index == 3)
retVal = UPDATE_SOURCE_ONLINE;
}
return retVal;
}
Reference<deployment::XPackage>
getExtensionWithHighestVersion(
Sequence<Reference<deployment::XPackage> > const & seqExt)
{
if (seqExt.getLength() == 0)
return Reference<deployment::XPackage>();
Reference<deployment::XPackage> greatest;
sal_Int32 len = seqExt.getLength();
for (sal_Int32 i = 0; i < len; i++)
{
if (!greatest.is())
{
greatest = seqExt[i];
continue;
}
Reference<deployment::XPackage> const & current = seqExt[i];
//greatest has a value
if (! current.is())
continue;
if (dp_misc::compareVersions(current->getVersion(), greatest->getVersion()) == dp_misc::GREATER)
greatest = current;
}
return greatest;
}
UpdateInfo::UpdateInfo( Reference< deployment::XPackage> const & ext):
extension(ext)
{
}
UpdateInfoMap getOnlineUpdateInfos(
Reference<uno::XComponentContext> const &xContext,
Reference<deployment::XExtensionManager> const & xExtMgr,
Reference<deployment::XUpdateInformationProvider > const & updateInformation,
std::vector<Reference<deployment::XPackage > > const * extensionList,
std::vector<std::pair< Reference<deployment::XPackage>, uno::Any> > & out_errors)
{
OSL_ASSERT(xExtMgr.is());
UpdateInfoMap infoMap;
if (!xExtMgr.is())
return infoMap;
if (!extensionList)
{
const uno::Sequence< uno::Sequence< Reference<deployment::XPackage > > > seqAllExt = xExtMgr->getAllExtensions(
Reference<task::XAbortChannel>(), Reference<ucb::XCommandEnvironment>());
//fill the UpdateInfoMap. key = extension identifier, value = UpdateInfo
for (int pos = seqAllExt.getLength(); pos --; )
{
uno::Sequence<Reference<deployment::XPackage> > const & seqExt = seqAllExt[pos];
Reference<deployment::XPackage> extension = getExtensionWithHighestVersion(seqExt);
OSL_ASSERT(extension.is());
std::pair<UpdateInfoMap::iterator, bool> insertRet = infoMap.insert(
UpdateInfoMap::value_type(
dp_misc::getIdentifier(extension), UpdateInfo(extension)));
OSL_ASSERT(insertRet.second == true);
}
}
else
{
typedef std::vector<Reference<deployment::XPackage > >::const_iterator CIT;
for (CIT i = extensionList->begin(); i != extensionList->end(); i++)
{
OSL_ASSERT(i->is());
std::pair<UpdateInfoMap::iterator, bool> insertRet = infoMap.insert(
UpdateInfoMap::value_type(
dp_misc::getIdentifier(*i), UpdateInfo(*i)));
OSL_ASSERT(insertRet.second == true);
}
}
//Now find the update information for the extensions which provide their own
//URLs to update information.
bool allInfosObtained = false;
getOwnUpdateInfos(xContext, updateInformation, infoMap, out_errors, allInfosObtained);
if (!allInfosObtained)
getDefaultUpdateInfos(xContext, updateInformation, infoMap, out_errors);
return infoMap;
}
OUString getHighestVersion(
::rtl::OUString const & userVersion,
::rtl::OUString const & sharedVersion,
::rtl::OUString const & bundledVersion,
::rtl::OUString const & onlineVersion)
{
int index = determineHighestVersion(userVersion, sharedVersion, bundledVersion, onlineVersion);
switch (index)
{
case 0: return userVersion;
case 1: return sharedVersion;
case 2: return bundledVersion;
case 3: return onlineVersion;
default: OSL_ASSERT(0);
}
return OUString();
}
} //namespace dp_misc
<commit_msg>dv21 #i113524# prevent online update for bundled extensions<commit_after>/*************************************************************************
*
* 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.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_desktop.hxx"
#include "dp_update.hxx"
#include "dp_version.hxx"
#include "dp_identifier.hxx"
#include "dp_descriptioninfoset.hxx"
#include "rtl/bootstrap.hxx"
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using ::rtl::OUString;
using ::rtl::OString;
namespace dp_misc {
namespace {
int determineHighestVersion(
::rtl::OUString const & userVersion,
::rtl::OUString const & sharedVersion,
::rtl::OUString const & bundledVersion,
::rtl::OUString const & onlineVersion)
{
int index = 0;
OUString greatest = userVersion;
if (dp_misc::compareVersions(sharedVersion, greatest) == dp_misc::GREATER)
{
index = 1;
greatest = sharedVersion;
}
if (dp_misc::compareVersions(bundledVersion, greatest) == dp_misc::GREATER)
{
index = 2;
greatest = bundledVersion;
}
if (dp_misc::compareVersions(onlineVersion, greatest) == dp_misc::GREATER)
{
index = 3;
}
return index;
}
Sequence< Reference< xml::dom::XElement > >
getUpdateInformation( Reference<deployment::XUpdateInformationProvider > const & updateInformation,
Sequence< OUString > const & urls,
OUString const & identifier,
uno::Any & out_error)
{
try {
return updateInformation->getUpdateInformation(urls, identifier);
} catch (uno::RuntimeException &) {
throw;
} catch (ucb::CommandFailedException & e) {
out_error = e.Reason;
} catch (ucb::CommandAbortedException &) {
} catch (uno::Exception & e) {
out_error = uno::makeAny(e);
}
return
Sequence<Reference< xml::dom::XElement > >();
}
void getOwnUpdateInfos(
Reference<uno::XComponentContext> const & xContext,
Reference<deployment::XUpdateInformationProvider > const & updateInformation,
UpdateInfoMap& inout_map, std::vector<std::pair<Reference<deployment::XPackage>, uno::Any> > & out_errors,
bool & out_allFound)
{
bool allHaveOwnUpdateInformation = true;
for (UpdateInfoMap::iterator i = inout_map.begin(); i != inout_map.end(); i++)
{
OSL_ASSERT(i->second.extension.is());
Sequence<OUString> urls(i->second.extension->getUpdateInformationURLs());
if (urls.getLength())
{
const OUString id = dp_misc::getIdentifier(i->second.extension);
uno::Any anyError;
//It is unclear from the idl if there can be a null reference returned.
//However all valid information should be the same
Sequence<Reference< xml::dom::XElement > >
infos(getUpdateInformation(updateInformation, urls, id, anyError));
if (anyError.hasValue())
out_errors.push_back(std::make_pair(i->second.extension, anyError));
for (sal_Int32 j = 0; j < infos.getLength(); ++j)
{
dp_misc::DescriptionInfoset infoset(
xContext,
Reference< xml::dom::XNode >(infos[j], UNO_QUERY_THROW));
if (!infoset.hasDescription())
continue;
boost::optional< OUString > id2(infoset.getIdentifier());
if (!id2)
continue;
OSL_ASSERT(*id2 == id);
if (*id2 == id)
{
i->second.version = infoset.getVersion();
i->second.info = Reference< xml::dom::XNode >(
infos[j], UNO_QUERY_THROW);
}
break;
}
}
else
{
allHaveOwnUpdateInformation &= false;
}
}
out_allFound = allHaveOwnUpdateInformation;
}
void getDefaultUpdateInfos(
Reference<uno::XComponentContext> const & xContext,
Reference<deployment::XUpdateInformationProvider > const & updateInformation,
UpdateInfoMap& inout_map,
std::vector<std::pair<Reference<deployment::XPackage>, uno::Any> > & out_errors)
{
const rtl::OUString sDefaultURL(dp_misc::getExtensionDefaultUpdateURL());
OSL_ASSERT(sDefaultURL.getLength());
Any anyError;
Sequence< Reference< xml::dom::XElement > >
infos(
getUpdateInformation(
updateInformation,
Sequence< OUString >(&sDefaultURL, 1), OUString(), anyError));
if (anyError.hasValue())
out_errors.push_back(std::make_pair(Reference<deployment::XPackage>(), anyError));
for (sal_Int32 i = 0; i < infos.getLength(); ++i)
{
Reference< xml::dom::XNode > node(infos[i], UNO_QUERY_THROW);
dp_misc::DescriptionInfoset infoset(xContext, node);
boost::optional< OUString > id(infoset.getIdentifier());
if (!id) {
continue;
}
UpdateInfoMap::iterator j = inout_map.find(*id);
if (j != inout_map.end())
{
//skip those extension which provide its own update urls
if (j->second.extension->getUpdateInformationURLs().getLength())
continue;
OUString v(infoset.getVersion());
//look for the highest version in the online repository
if (dp_misc::compareVersions(v, j->second.version) ==
dp_misc::GREATER)
{
j->second.version = v;
j->second.info = node;
}
}
}
}
bool containsBundledOnly(Sequence<Reference<deployment::XPackage> > const & sameIdExtensions)
{
OSL_ASSERT(sameIdExtensions.getLength() == 3);
if (!sameIdExtensions[0].is() && !sameIdExtensions[1].is() && sameIdExtensions[2].is())
return true;
else
return false;
}
/** Returns true if the list of extensions are bundled extensions and there are no
other extensions with the same identifier in the shared or user repository.
If extensionList is NULL, then it is checked if there are only bundled extensions.
*/
bool onlyBundledExtensions(
Reference<deployment::XExtensionManager> const & xExtMgr,
std::vector< Reference<deployment::XPackage > > const * extensionList)
{
OSL_ASSERT(xExtMgr.is());
bool onlyBundled = true;
if (extensionList)
{
typedef std::vector<Reference<deployment::XPackage > >::const_iterator CIT;
for (CIT i = extensionList->begin(); i != extensionList->end(); i++)
{
Sequence<Reference<deployment::XPackage> > seqExt = xExtMgr->getExtensionsWithSameIdentifier(
dp_misc::getIdentifier(*i), (*i)->getName(), Reference<ucb::XCommandEnvironment>());
if (!containsBundledOnly(seqExt))
{
onlyBundled = false;
break;
}
}
}
else
{
const uno::Sequence< uno::Sequence< Reference<deployment::XPackage > > > seqAllExt =
xExtMgr->getAllExtensions(Reference<task::XAbortChannel>(), Reference<ucb::XCommandEnvironment>());
for (int pos = seqAllExt.getLength(); pos --; )
{
if (!containsBundledOnly(seqAllExt[pos]))
{
onlyBundled = false;
break;
}
}
}
return onlyBundled;
}
} // anon namespace
OUString getExtensionDefaultUpdateURL()
{
::rtl::OUString sUrl(
RTL_CONSTASCII_USTRINGPARAM(
"${$BRAND_BASE_DIR/program/" SAL_CONFIGFILE("version")
":Version:ExtensionUpdateURL}"));
::rtl::Bootstrap::expandMacros(sUrl);
return sUrl;
}
/* returns the index of the greatest version, starting with 0
*/
UPDATE_SOURCE isUpdateUserExtension(
bool bReadOnlyShared,
::rtl::OUString const & userVersion,
::rtl::OUString const & sharedVersion,
::rtl::OUString const & bundledVersion,
::rtl::OUString const & onlineVersion)
{
UPDATE_SOURCE retVal = UPDATE_SOURCE_NONE;
if (bReadOnlyShared)
{
if (userVersion.getLength())
{
int index = determineHighestVersion(
userVersion, sharedVersion, bundledVersion, onlineVersion);
if (index == 1)
retVal = UPDATE_SOURCE_SHARED;
else if (index == 2)
retVal = UPDATE_SOURCE_BUNDLED;
else if (index == 3)
retVal = UPDATE_SOURCE_ONLINE;
}
else if (sharedVersion.getLength())
{
int index = determineHighestVersion(
OUString(), sharedVersion, bundledVersion, onlineVersion);
if (index == 2)
retVal = UPDATE_SOURCE_BUNDLED;
else if (index == 3)
retVal = UPDATE_SOURCE_ONLINE;
}
//No update for bundled extensions, they are updated only by the setup
//else if (bundledVersion.getLength())
//{
// int index = determineHighestVersion(
// OUString(), OUString(), bundledVersion, onlineVersion);
// if (index == 3)
// retVal = UPDATE_SOURCE_ONLINE;
//}
}
else
{
if (userVersion.getLength())
{
int index = determineHighestVersion(
userVersion, sharedVersion, bundledVersion, onlineVersion);
if (index == 1)
retVal = UPDATE_SOURCE_SHARED;
else if (index == 2)
retVal = UPDATE_SOURCE_BUNDLED;
else if (index == 3)
retVal = UPDATE_SOURCE_ONLINE;
}
}
return retVal;
}
UPDATE_SOURCE isUpdateSharedExtension(
bool bReadOnlyShared,
::rtl::OUString const & sharedVersion,
::rtl::OUString const & bundledVersion,
::rtl::OUString const & onlineVersion)
{
if (bReadOnlyShared)
return UPDATE_SOURCE_NONE;
UPDATE_SOURCE retVal = UPDATE_SOURCE_NONE;
if (sharedVersion.getLength())
{
int index = determineHighestVersion(
OUString(), sharedVersion, bundledVersion, onlineVersion);
if (index == 2)
retVal = UPDATE_SOURCE_BUNDLED;
else if (index == 3)
retVal = UPDATE_SOURCE_ONLINE;
}
//No update for bundled extensions, they are updated only by the setup
//else if (bundledVersion.getLength())
//{
// int index = determineHighestVersion(
// OUString(), OUString(), bundledVersion, onlineVersion);
// if (index == 3)
// retVal = UPDATE_SOURCE_ONLINE;
//}
return retVal;
}
Reference<deployment::XPackage>
getExtensionWithHighestVersion(
Sequence<Reference<deployment::XPackage> > const & seqExt)
{
if (seqExt.getLength() == 0)
return Reference<deployment::XPackage>();
Reference<deployment::XPackage> greatest;
sal_Int32 len = seqExt.getLength();
for (sal_Int32 i = 0; i < len; i++)
{
if (!greatest.is())
{
greatest = seqExt[i];
continue;
}
Reference<deployment::XPackage> const & current = seqExt[i];
//greatest has a value
if (! current.is())
continue;
if (dp_misc::compareVersions(current->getVersion(), greatest->getVersion()) == dp_misc::GREATER)
greatest = current;
}
return greatest;
}
UpdateInfo::UpdateInfo( Reference< deployment::XPackage> const & ext):
extension(ext)
{
}
UpdateInfoMap getOnlineUpdateInfos(
Reference<uno::XComponentContext> const &xContext,
Reference<deployment::XExtensionManager> const & xExtMgr,
Reference<deployment::XUpdateInformationProvider > const & updateInformation,
std::vector<Reference<deployment::XPackage > > const * extensionList,
std::vector<std::pair< Reference<deployment::XPackage>, uno::Any> > & out_errors)
{
OSL_ASSERT(xExtMgr.is());
UpdateInfoMap infoMap;
if (!xExtMgr.is() || onlyBundledExtensions(xExtMgr, extensionList))
return infoMap;
if (!extensionList)
{
const uno::Sequence< uno::Sequence< Reference<deployment::XPackage > > > seqAllExt = xExtMgr->getAllExtensions(
Reference<task::XAbortChannel>(), Reference<ucb::XCommandEnvironment>());
//fill the UpdateInfoMap. key = extension identifier, value = UpdateInfo
for (int pos = seqAllExt.getLength(); pos --; )
{
uno::Sequence<Reference<deployment::XPackage> > const & seqExt = seqAllExt[pos];
Reference<deployment::XPackage> extension = getExtensionWithHighestVersion(seqExt);
OSL_ASSERT(extension.is());
std::pair<UpdateInfoMap::iterator, bool> insertRet = infoMap.insert(
UpdateInfoMap::value_type(
dp_misc::getIdentifier(extension), UpdateInfo(extension)));
OSL_ASSERT(insertRet.second == true);
}
}
else
{
typedef std::vector<Reference<deployment::XPackage > >::const_iterator CIT;
for (CIT i = extensionList->begin(); i != extensionList->end(); i++)
{
OSL_ASSERT(i->is());
std::pair<UpdateInfoMap::iterator, bool> insertRet = infoMap.insert(
UpdateInfoMap::value_type(
dp_misc::getIdentifier(*i), UpdateInfo(*i)));
OSL_ASSERT(insertRet.second == true);
}
}
//Now find the update information for the extensions which provide their own
//URLs to update information.
bool allInfosObtained = false;
getOwnUpdateInfos(xContext, updateInformation, infoMap, out_errors, allInfosObtained);
if (!allInfosObtained)
getDefaultUpdateInfos(xContext, updateInformation, infoMap, out_errors);
return infoMap;
}
OUString getHighestVersion(
::rtl::OUString const & userVersion,
::rtl::OUString const & sharedVersion,
::rtl::OUString const & bundledVersion,
::rtl::OUString const & onlineVersion)
{
int index = determineHighestVersion(userVersion, sharedVersion, bundledVersion, onlineVersion);
switch (index)
{
case 0: return userVersion;
case 1: return sharedVersion;
case 2: return bundledVersion;
case 3: return onlineVersion;
default: OSL_ASSERT(0);
}
return OUString();
}
} //namespace dp_misc
<|endoftext|>
|
<commit_before>#include "resources/TextureData.h"
#include "math/Misc.h"
#include "renderers/Renderer.h"
#include "resources/ResourceManager.h"
#include "ImageIO.h"
#include "Log.h"
#include <nanosvg/nanosvg.h>
#include <nanosvg/nanosvgrast.h>
#include <assert.h>
#include <string.h>
#define DPI 96
TextureData::TextureData(bool tile) : mTile(tile), mTextureID(0), mDataRGBA(nullptr), mScalable(false),
mWidth(0), mHeight(0), mSourceWidth(0.0f), mSourceHeight(0.0f)
{
}
TextureData::~TextureData()
{
releaseVRAM();
releaseRAM();
}
void TextureData::initFromPath(const std::string& path)
{
// Just set the path. It will be loaded later
mPath = path;
// Only textures with paths are reloadable
mReloadable = true;
}
bool TextureData::initSVGFromMemory(const unsigned char* fileData, size_t length)
{
// If already initialised then don't read again
std::unique_lock<std::mutex> lock(mMutex);
if (mDataRGBA)
return true;
// nsvgParse excepts a modifiable, null-terminated string
char* copy = (char*)malloc(length + 1);
assert(copy != NULL);
memcpy(copy, fileData, length);
copy[length] = '\0';
NSVGimage* svgImage = nsvgParse(copy, "px", DPI);
free(copy);
if (!svgImage)
{
LOG(LogError) << "Error parsing SVG image.";
return false;
}
// We want to rasterise this texture at a specific resolution. If the source size
// variables are set then use them otherwise set them from the parsed file
if ((mSourceWidth == 0.0f) && (mSourceHeight == 0.0f))
{
mSourceWidth = svgImage->width;
mSourceHeight = svgImage->height;
}
mWidth = (size_t)Math::round(mSourceWidth);
mHeight = (size_t)Math::round(mSourceHeight);
if (mWidth == 0)
{
// auto scale width to keep aspect
mWidth = (size_t)Math::round(((float)mHeight / svgImage->height) * svgImage->width);
}
else if (mHeight == 0)
{
// auto scale height to keep aspect
mHeight = (size_t)Math::round(((float)mWidth / svgImage->width) * svgImage->height);
}
unsigned char* dataRGBA = new unsigned char[mWidth * mHeight * 4];
NSVGrasterizer* rast = nsvgCreateRasterizer();
float scale = Math::min(mHeight / svgImage->height, mWidth / svgImage->width);
nsvgRasterize(rast, svgImage, 0, 0, scale, dataRGBA, (int)mWidth, (int)mHeight, (int)mWidth * 4);
nsvgDeleteRasterizer(rast);
ImageIO::flipPixelsVert(dataRGBA, mWidth, mHeight);
mDataRGBA = dataRGBA;
return true;
}
bool TextureData::initImageFromMemory(const unsigned char* fileData, size_t length)
{
size_t width, height;
// If already initialised then don't read again
{
std::unique_lock<std::mutex> lock(mMutex);
if (mDataRGBA)
return true;
}
std::vector<unsigned char> imageRGBA = ImageIO::loadFromMemoryRGBA32((const unsigned char*)(fileData), length, width, height);
if (imageRGBA.size() == 0)
{
LOG(LogError) << "Could not initialize texture from memory, invalid data! (file path: " << mPath << ", data ptr: " << (size_t)fileData << ", reported size: " << length << ")";
return false;
}
mSourceWidth = (float) width;
mSourceHeight = (float) height;
mScalable = false;
return initFromRGBA(imageRGBA.data(), width, height);
}
bool TextureData::initFromRGBA(const unsigned char* dataRGBA, size_t width, size_t height)
{
// If already initialised then don't read again
std::unique_lock<std::mutex> lock(mMutex);
if (mDataRGBA)
return true;
// Take a copy
mDataRGBA = new unsigned char[width * height * 4];
memcpy(mDataRGBA, dataRGBA, width * height * 4);
mWidth = width;
mHeight = height;
return true;
}
bool TextureData::load()
{
bool retval = false;
// Need to load. See if there is a file
if (!mPath.empty())
{
std::shared_ptr<ResourceManager>& rm = ResourceManager::getInstance();
const ResourceData& data = rm->getFileData(mPath);
// is it an SVG?
if (mPath.substr(mPath.size() - 4, std::string::npos) == ".svg")
{
mScalable = true;
retval = initSVGFromMemory((const unsigned char*)data.ptr.get(), data.length);
}
else
retval = initImageFromMemory((const unsigned char*)data.ptr.get(), data.length);
}
return retval;
}
bool TextureData::isLoaded()
{
std::unique_lock<std::mutex> lock(mMutex);
if (mDataRGBA || (mTextureID != 0))
return true;
return false;
}
bool TextureData::uploadAndBind()
{
// See if it's already been uploaded
std::unique_lock<std::mutex> lock(mMutex);
if (mTextureID != 0)
{
Renderer::bindTexture(mTextureID);
}
else
{
// Load it if necessary
if (!mDataRGBA)
{
return false;
}
// Make sure we're ready to upload
if ((mWidth == 0) || (mHeight == 0) || (mDataRGBA == nullptr))
return false;
// Upload texture
mTextureID = Renderer::createTexture(Renderer::Texture::RGBA, true, mTile, (int)mWidth, (int)mHeight, mDataRGBA);
}
return true;
}
void TextureData::releaseVRAM()
{
std::unique_lock<std::mutex> lock(mMutex);
if (mTextureID != 0)
{
Renderer::destroyTexture(mTextureID);
mTextureID = 0;
}
}
void TextureData::releaseRAM()
{
std::unique_lock<std::mutex> lock(mMutex);
delete[] mDataRGBA;
mDataRGBA = 0;
}
size_t TextureData::width()
{
if (mWidth == 0)
load();
return mWidth;
}
size_t TextureData::height()
{
if (mHeight == 0)
load();
return mHeight;
}
float TextureData::sourceWidth()
{
if (mSourceWidth == 0)
load();
return mSourceWidth;
}
float TextureData::sourceHeight()
{
if (mSourceHeight == 0)
load();
return mSourceHeight;
}
void TextureData::setSourceSize(float width, float height)
{
if (mScalable)
{
if ((mSourceWidth != width) || (mSourceHeight != height))
{
mSourceWidth = width;
mSourceHeight = height;
releaseVRAM();
releaseRAM();
}
}
}
size_t TextureData::getVRAMUsage()
{
if ((mTextureID != 0) || (mDataRGBA != nullptr))
return mWidth * mHeight * 4;
else
return 0;
}
<commit_msg>Base SVG size on height<commit_after>#include "resources/TextureData.h"
#include "math/Misc.h"
#include "renderers/Renderer.h"
#include "resources/ResourceManager.h"
#include "ImageIO.h"
#include "Log.h"
#include <nanosvg/nanosvg.h>
#include <nanosvg/nanosvgrast.h>
#include <assert.h>
#include <string.h>
#define DPI 96
TextureData::TextureData(bool tile) : mTile(tile), mTextureID(0), mDataRGBA(nullptr), mScalable(false),
mWidth(0), mHeight(0), mSourceWidth(0.0f), mSourceHeight(0.0f)
{
}
TextureData::~TextureData()
{
releaseVRAM();
releaseRAM();
}
void TextureData::initFromPath(const std::string& path)
{
// Just set the path. It will be loaded later
mPath = path;
// Only textures with paths are reloadable
mReloadable = true;
}
bool TextureData::initSVGFromMemory(const unsigned char* fileData, size_t length)
{
// If already initialised then don't read again
std::unique_lock<std::mutex> lock(mMutex);
if (mDataRGBA)
return true;
// nsvgParse excepts a modifiable, null-terminated string
char* copy = (char*)malloc(length + 1);
assert(copy != NULL);
memcpy(copy, fileData, length);
copy[length] = '\0';
NSVGimage* svgImage = nsvgParse(copy, "px", DPI);
free(copy);
if (!svgImage || (svgImage->width == 0) || (svgImage->height == 0))
{
LOG(LogError) << "Error parsing SVG image.";
return false;
}
// We want to rasterise this texture at a specific resolution. If the source size
// variables are set then use them otherwise set them from the parsed file
if (mSourceHeight == 0.0f)
mSourceHeight = svgImage->height;
mSourceWidth = (mSourceHeight * svgImage->width) / svgImage->height;
mWidth = (size_t)Math::round(mSourceWidth);
mHeight = (size_t)Math::round(mSourceHeight);
unsigned char* dataRGBA = new unsigned char[mWidth * mHeight * 4];
NSVGrasterizer* rast = nsvgCreateRasterizer();
float scale = Math::min(mHeight / svgImage->height, mWidth / svgImage->width);
nsvgRasterize(rast, svgImage, 0, 0, scale, dataRGBA, (int)mWidth, (int)mHeight, (int)mWidth * 4);
nsvgDeleteRasterizer(rast);
ImageIO::flipPixelsVert(dataRGBA, mWidth, mHeight);
mDataRGBA = dataRGBA;
return true;
}
bool TextureData::initImageFromMemory(const unsigned char* fileData, size_t length)
{
size_t width, height;
// If already initialised then don't read again
{
std::unique_lock<std::mutex> lock(mMutex);
if (mDataRGBA)
return true;
}
std::vector<unsigned char> imageRGBA = ImageIO::loadFromMemoryRGBA32((const unsigned char*)(fileData), length, width, height);
if (imageRGBA.size() == 0)
{
LOG(LogError) << "Could not initialize texture from memory, invalid data! (file path: " << mPath << ", data ptr: " << (size_t)fileData << ", reported size: " << length << ")";
return false;
}
mSourceWidth = (float) width;
mSourceHeight = (float) height;
mScalable = false;
return initFromRGBA(imageRGBA.data(), width, height);
}
bool TextureData::initFromRGBA(const unsigned char* dataRGBA, size_t width, size_t height)
{
// If already initialised then don't read again
std::unique_lock<std::mutex> lock(mMutex);
if (mDataRGBA)
return true;
// Take a copy
mDataRGBA = new unsigned char[width * height * 4];
memcpy(mDataRGBA, dataRGBA, width * height * 4);
mWidth = width;
mHeight = height;
return true;
}
bool TextureData::load()
{
bool retval = false;
// Need to load. See if there is a file
if (!mPath.empty())
{
std::shared_ptr<ResourceManager>& rm = ResourceManager::getInstance();
const ResourceData& data = rm->getFileData(mPath);
// is it an SVG?
if (mPath.substr(mPath.size() - 4, std::string::npos) == ".svg")
{
mScalable = true;
retval = initSVGFromMemory((const unsigned char*)data.ptr.get(), data.length);
}
else
retval = initImageFromMemory((const unsigned char*)data.ptr.get(), data.length);
}
return retval;
}
bool TextureData::isLoaded()
{
std::unique_lock<std::mutex> lock(mMutex);
if (mDataRGBA || (mTextureID != 0))
return true;
return false;
}
bool TextureData::uploadAndBind()
{
// See if it's already been uploaded
std::unique_lock<std::mutex> lock(mMutex);
if (mTextureID != 0)
{
Renderer::bindTexture(mTextureID);
}
else
{
// Load it if necessary
if (!mDataRGBA)
{
return false;
}
// Make sure we're ready to upload
if ((mWidth == 0) || (mHeight == 0) || (mDataRGBA == nullptr))
return false;
// Upload texture
mTextureID = Renderer::createTexture(Renderer::Texture::RGBA, true, mTile, (int)mWidth, (int)mHeight, mDataRGBA);
}
return true;
}
void TextureData::releaseVRAM()
{
std::unique_lock<std::mutex> lock(mMutex);
if (mTextureID != 0)
{
Renderer::destroyTexture(mTextureID);
mTextureID = 0;
}
}
void TextureData::releaseRAM()
{
std::unique_lock<std::mutex> lock(mMutex);
delete[] mDataRGBA;
mDataRGBA = 0;
}
size_t TextureData::width()
{
if (mWidth == 0)
load();
return mWidth;
}
size_t TextureData::height()
{
if (mHeight == 0)
load();
return mHeight;
}
float TextureData::sourceWidth()
{
if (mSourceWidth == 0)
load();
return mSourceWidth;
}
float TextureData::sourceHeight()
{
if (mSourceHeight == 0)
load();
return mSourceHeight;
}
void TextureData::setSourceSize(float width, float height)
{
if (mScalable)
{
if ((mSourceWidth != width) || (mSourceHeight != height))
{
mSourceWidth = width;
mSourceHeight = height;
releaseVRAM();
releaseRAM();
}
}
}
size_t TextureData::getVRAMUsage()
{
if ((mTextureID != 0) || (mDataRGBA != nullptr))
return mWidth * mHeight * 4;
else
return 0;
}
<|endoftext|>
|
<commit_before>// Copyright 2012-2013 Samplecount S.L.
//
// 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.
#ifndef METHCLA_ENGINE_HPP_INCLUDED
#define METHCLA_ENGINE_HPP_INCLUDED
#include <methcla/engine.h>
#include <future>
#include <iostream>
#include <memory>
#include <stdexcept>
#include <string>
#include <thread>
#include <unordered_map>
#include <vector>
#include <boost/optional.hpp>
#include <boost/serialization/strong_typedef.hpp>
#include <boost/utility.hpp>
#include <oscpp/client.hpp>
#include <oscpp/server.hpp>
#include <oscpp/print.hpp>
namespace Methcla
{
inline static void dumpRequest(std::ostream& out, const OSC::Server::Packet& packet)
{
out << "Request (send): " << packet << std::endl;
}
inline static std::exception_ptr responseToException(const OSC::Server::Packet& packet)
{
if (packet.isMessage()) {
OSC::Server::Message msg(packet);
if (msg == "/error") {
auto args(msg.args());
args.drop(); // request id
const char* error = args.string();
return std::make_exception_ptr(std::runtime_error(error));
} else {
return std::exception_ptr();
}
} else {
return std::make_exception_ptr(std::invalid_argument("Response is not a message"));
}
}
BOOST_STRONG_TYPEDEF(int32_t, SynthId);
BOOST_STRONG_TYPEDEF(int32_t, AudioBusId);
namespace impl
{
struct Result : boost::noncopyable
{
Result()
: m_cond(false)
{ }
inline void notify()
{
m_cond = true;
m_cond_var.notify_one();
}
inline void wait()
{
std::unique_lock<std::mutex> lock(m_mutex);
while (!m_cond) {
m_cond_var.wait(lock);
}
if (m_exc) {
std::rethrow_exception(m_exc);
}
}
void set_exception(std::exception_ptr exc)
{
BOOST_ASSERT(m_cond);
std::lock_guard<std::mutex> lock(m_mutex);
m_exc = exc;
notify();
}
std::mutex m_mutex;
std::condition_variable m_cond_var;
bool m_cond;
std::exception_ptr m_exc;
};
};
template <class T> class Result : impl::Result
{
public:
void set(std::exception_ptr exc)
{
set_exception(exc);
}
void set(const T& value)
{
BOOST_ASSERT(!m_cond);
std::lock_guard<std::mutex> lock(m_mutex);
m_value = value;
notify();
}
const T& get()
{
wait();
return m_value;
}
private:
T m_value;
};
template <> class Result<void> : impl::Result
{
public:
void set(std::exception_ptr exc)
{
set_exception(exc);
}
void set()
{
BOOST_ASSERT(!m_cond);
std::lock_guard<std::mutex> lock(m_mutex);
notify();
}
void get()
{
wait();
}
};
template <typename T> bool checkResponse(const OSC::Server::Packet& response, Result<T>& result)
{
auto error = responseToException(response);
if (error) {
result.set(error);
return false;
}
return true;
}
class Value
{
public:
enum Type
{
kInt,
kFloat,
kString
};
explicit Value(int x)
: m_type(kInt)
, m_int(x)
{ }
explicit Value(float x)
: m_type(kFloat)
, m_float(x)
{ }
Value(const std::string& x)
: m_type(kString)
, m_string(x)
{ }
void put(OSC::Client::Packet& packet) const
{
switch (m_type) {
case kInt:
packet.int32(m_int);
break;
case kFloat:
packet.float32(m_float);
break;
case kString:
packet.string(m_string.c_str());
break;
}
}
private:
Type m_type;
int m_int;
float m_float;
std::string m_string;
};
class Engine
{
public:
Engine(const Methcla_Option* options)
: m_requestId(kMethcla_Notification+1)
{
check(nullptr, methcla_engine_new(handlePacket, this, options, &m_engine));
}
~Engine()
{
methcla_engine_free(m_engine);
}
operator const Methcla_Engine* () const
{
return m_engine;
}
operator Methcla_Engine* ()
{
return m_engine;
}
void start()
{
check(m_engine, methcla_engine_start(m_engine));
}
void stop()
{
check(m_engine, methcla_engine_stop(m_engine));
}
SynthId synth(const char* synthDef, const std::vector<float>& controls, const std::list<Value>& options=std::list<Value>())
{
const char address[] = "/s_new";
const size_t numArgs = 4 + OSC::Size::array(controls.size()) + OSC::Size::array(options.size());
const size_t packetSize = OSC::Size::message(address, numArgs)
+ OSC::Size::int32()
+ OSC::Size::string(256)
+ 2 * OSC::Size::int32()
+ controls.size() * OSC::Size::float32()
+ 256; // margin for options. better: pool allocator with fixed size packets.
const Methcla_RequestId requestId = getRequestId();
OSC::Client::DynamicPacket request(packetSize);
request
.openMessage(address, numArgs)
.int32(requestId)
.string(synthDef)
.int32(0)
.int32(0)
.putArray(controls.begin(), controls.end());
request.openArray();
for (const auto& x : options) {
x.put(request);
}
request.closeArray();
request.closeMessage();
dumpRequest(std::cerr, OSC::Server::Packet(request.data(), request.size()));
Result<SynthId> result;
withRequest(requestId, request, [&result](Methcla_RequestId requestId, const void* buffer, size_t size){
OSC::Server::Packet response(buffer, size);
if (checkResponse(response, result)) {
auto args = ((OSC::Server::Message)response).args();
int32_t requestId_ = args.int32();
BOOST_ASSERT_MSG( requestId_ == requestId, "Request id mismatch");
int32_t nodeId = args.int32();
std::cerr << "synth: " << requestId << " " << nodeId << std::endl;
result.set(SynthId(nodeId));
}
});
return result.get();
}
void mapOutput(const SynthId& synth, size_t index, AudioBusId bus)
{
const char address[] = "/synth/map/output";
const size_t numArgs = 4;
const size_t packetSize = OSC::Size::message(address, numArgs)
+ numArgs * OSC::Size::int32();
Methcla_RequestId requestId = getRequestId();
OSC::Client::StaticPacket<packetSize> request;
request
.openMessage(address, numArgs)
.int32(requestId)
.int32(synth)
.int32(index)
.int32(bus)
.closeMessage();
dumpRequest(std::cerr, OSC::Server::Packet(request.data(), request.size()));
Result<void> result;
withRequest(requestId, request, [&result](Methcla_RequestId requestId, const void* buffer, size_t size){
if (checkResponse(OSC::Server::Packet(buffer, size), result)) {
result.set();
}
});
result.get();
}
void freeNode(const SynthId& synth)
{
const char address[] = "/n_free";
const size_t numArgs = 2;
const size_t packetSize = OSC::Size::message(address, numArgs) + numArgs * OSC::Size::int32();
const Methcla_RequestId requestId = getRequestId();
OSC::Client::StaticPacket<packetSize> request;
request
.openMessage(address, numArgs)
.int32(requestId)
.int32(synth)
.closeMessage();
Result<void> result;
withRequest(requestId, request, [&result](Methcla_RequestId, const void* buffer, size_t size){
if (checkResponse(OSC::Server::Packet(buffer, size), result)) {
result.set();
}
});
result.get();
// send(request);
}
private:
static void check(const Methcla_Engine* engine, Methcla_Error err)
{
if (err != kMethcla_NoError) {
const char* msg = methcla_engine_error_message(engine, err);
if (err == kMethcla_InvalidArgument)
throw std::invalid_argument(msg);
else if (err == kMethcla_BadAlloc)
throw std::bad_alloc();
else
throw std::runtime_error(msg);
}
}
static void handlePacket(void* data, Methcla_RequestId requestId, const void* packet, size_t size)
{
static_cast<Engine*>(data)->handlePacket(requestId, packet, size);
}
void handlePacket(Methcla_RequestId requestId, const void* packet, size_t size)
{
std::lock_guard<std::mutex> lock(m_callbacksMutex);
// look up request id and invoke callback
auto it = m_callbacks.find(requestId);
if (it != m_callbacks.end()) {
try {
it->second(requestId, packet, size);
m_callbacks.erase(it);
} catch (...) {
m_callbacks.erase(it);
throw;
}
}
}
void send(const void* packet, size_t size)
{
methcla_engine_send(m_engine, packet, size);
}
void send(const OSC::Client::Packet& packet)
{
send(packet.data(), packet.size());
}
Methcla_RequestId getRequestId()
{
std::lock_guard<std::mutex> lock(m_requestIdMutex);
Methcla_RequestId result = m_requestId;
if (result == kMethcla_Notification) {
result++;
}
m_requestId = result + 1;
return result;
}
void registerResponse(Methcla_RequestId requestId, std::function<void (Methcla_RequestId, const void*, size_t)> callback)
{
std::lock_guard<std::mutex> lock(m_callbacksMutex);
BOOST_ASSERT_MSG( m_callbacks.find(requestId) == m_callbacks.end(), "Duplicate request id" );
m_callbacks[requestId] = callback;
}
void withRequest(Methcla_RequestId requestId, const OSC::Client::Packet& request, std::function<void (Methcla_RequestId, const void*, size_t)> callback)
{
registerResponse(requestId, callback);
send(request);
}
private:
Methcla_Engine* m_engine;
Methcla_RequestId m_requestId;
std::mutex m_requestIdMutex;
std::unordered_map<Methcla_RequestId,std::function<void (Methcla_RequestId, const void*, size_t)>> m_callbacks;
std::mutex m_callbacksMutex;
};
};
#endif // METHCLA_ENGINE_HPP_INCLUDED
<commit_msg>Add bool constructor<commit_after>// Copyright 2012-2013 Samplecount S.L.
//
// 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.
#ifndef METHCLA_ENGINE_HPP_INCLUDED
#define METHCLA_ENGINE_HPP_INCLUDED
#include <methcla/engine.h>
#include <future>
#include <iostream>
#include <memory>
#include <stdexcept>
#include <string>
#include <thread>
#include <unordered_map>
#include <vector>
#include <boost/optional.hpp>
#include <boost/serialization/strong_typedef.hpp>
#include <boost/utility.hpp>
#include <oscpp/client.hpp>
#include <oscpp/server.hpp>
#include <oscpp/print.hpp>
namespace Methcla
{
inline static void dumpRequest(std::ostream& out, const OSC::Server::Packet& packet)
{
out << "Request (send): " << packet << std::endl;
}
inline static std::exception_ptr responseToException(const OSC::Server::Packet& packet)
{
if (packet.isMessage()) {
OSC::Server::Message msg(packet);
if (msg == "/error") {
auto args(msg.args());
args.drop(); // request id
const char* error = args.string();
return std::make_exception_ptr(std::runtime_error(error));
} else {
return std::exception_ptr();
}
} else {
return std::make_exception_ptr(std::invalid_argument("Response is not a message"));
}
}
BOOST_STRONG_TYPEDEF(int32_t, SynthId);
BOOST_STRONG_TYPEDEF(int32_t, AudioBusId);
namespace impl
{
struct Result : boost::noncopyable
{
Result()
: m_cond(false)
{ }
inline void notify()
{
m_cond = true;
m_cond_var.notify_one();
}
inline void wait()
{
std::unique_lock<std::mutex> lock(m_mutex);
while (!m_cond) {
m_cond_var.wait(lock);
}
if (m_exc) {
std::rethrow_exception(m_exc);
}
}
void set_exception(std::exception_ptr exc)
{
BOOST_ASSERT(m_cond);
std::lock_guard<std::mutex> lock(m_mutex);
m_exc = exc;
notify();
}
std::mutex m_mutex;
std::condition_variable m_cond_var;
bool m_cond;
std::exception_ptr m_exc;
};
};
template <class T> class Result : impl::Result
{
public:
void set(std::exception_ptr exc)
{
set_exception(exc);
}
void set(const T& value)
{
BOOST_ASSERT(!m_cond);
std::lock_guard<std::mutex> lock(m_mutex);
m_value = value;
notify();
}
const T& get()
{
wait();
return m_value;
}
private:
T m_value;
};
template <> class Result<void> : impl::Result
{
public:
void set(std::exception_ptr exc)
{
set_exception(exc);
}
void set()
{
BOOST_ASSERT(!m_cond);
std::lock_guard<std::mutex> lock(m_mutex);
notify();
}
void get()
{
wait();
}
};
template <typename T> bool checkResponse(const OSC::Server::Packet& response, Result<T>& result)
{
auto error = responseToException(response);
if (error) {
result.set(error);
return false;
}
return true;
}
class Value
{
public:
enum Type
{
kInt,
kFloat,
kString
};
explicit Value(int x)
: m_type(kInt)
, m_int(x)
{ }
explicit Value(float x)
: m_type(kFloat)
, m_float(x)
{ }
Value(const std::string& x)
: m_type(kString)
, m_string(x)
{ }
explicit Value(bool x)
: m_type(kInt)
, m_int(x)
{ }
void put(OSC::Client::Packet& packet) const
{
switch (m_type) {
case kInt:
packet.int32(m_int);
break;
case kFloat:
packet.float32(m_float);
break;
case kString:
packet.string(m_string.c_str());
break;
}
}
private:
Type m_type;
int m_int;
float m_float;
std::string m_string;
};
class Engine
{
public:
Engine(const Methcla_Option* options)
: m_requestId(kMethcla_Notification+1)
{
check(nullptr, methcla_engine_new(handlePacket, this, options, &m_engine));
}
~Engine()
{
methcla_engine_free(m_engine);
}
operator const Methcla_Engine* () const
{
return m_engine;
}
operator Methcla_Engine* ()
{
return m_engine;
}
void start()
{
check(m_engine, methcla_engine_start(m_engine));
}
void stop()
{
check(m_engine, methcla_engine_stop(m_engine));
}
SynthId synth(const char* synthDef, const std::vector<float>& controls, const std::list<Value>& options=std::list<Value>())
{
const char address[] = "/s_new";
const size_t numArgs = 4 + OSC::Size::array(controls.size()) + OSC::Size::array(options.size());
const size_t packetSize = OSC::Size::message(address, numArgs)
+ OSC::Size::int32()
+ OSC::Size::string(256)
+ 2 * OSC::Size::int32()
+ controls.size() * OSC::Size::float32()
+ 256; // margin for options. better: pool allocator with fixed size packets.
const Methcla_RequestId requestId = getRequestId();
OSC::Client::DynamicPacket request(packetSize);
request
.openMessage(address, numArgs)
.int32(requestId)
.string(synthDef)
.int32(0)
.int32(0)
.putArray(controls.begin(), controls.end());
request.openArray();
for (const auto& x : options) {
x.put(request);
}
request.closeArray();
request.closeMessage();
dumpRequest(std::cerr, OSC::Server::Packet(request.data(), request.size()));
Result<SynthId> result;
withRequest(requestId, request, [&result](Methcla_RequestId requestId, const void* buffer, size_t size){
OSC::Server::Packet response(buffer, size);
if (checkResponse(response, result)) {
auto args = ((OSC::Server::Message)response).args();
int32_t requestId_ = args.int32();
BOOST_ASSERT_MSG( requestId_ == requestId, "Request id mismatch");
int32_t nodeId = args.int32();
std::cerr << "synth: " << requestId << " " << nodeId << std::endl;
result.set(SynthId(nodeId));
}
});
return result.get();
}
void mapOutput(const SynthId& synth, size_t index, AudioBusId bus)
{
const char address[] = "/synth/map/output";
const size_t numArgs = 4;
const size_t packetSize = OSC::Size::message(address, numArgs)
+ numArgs * OSC::Size::int32();
Methcla_RequestId requestId = getRequestId();
OSC::Client::StaticPacket<packetSize> request;
request
.openMessage(address, numArgs)
.int32(requestId)
.int32(synth)
.int32(index)
.int32(bus)
.closeMessage();
dumpRequest(std::cerr, OSC::Server::Packet(request.data(), request.size()));
Result<void> result;
withRequest(requestId, request, [&result](Methcla_RequestId requestId, const void* buffer, size_t size){
if (checkResponse(OSC::Server::Packet(buffer, size), result)) {
result.set();
}
});
result.get();
}
void freeNode(const SynthId& synth)
{
const char address[] = "/n_free";
const size_t numArgs = 2;
const size_t packetSize = OSC::Size::message(address, numArgs) + numArgs * OSC::Size::int32();
const Methcla_RequestId requestId = getRequestId();
OSC::Client::StaticPacket<packetSize> request;
request
.openMessage(address, numArgs)
.int32(requestId)
.int32(synth)
.closeMessage();
Result<void> result;
withRequest(requestId, request, [&result](Methcla_RequestId, const void* buffer, size_t size){
if (checkResponse(OSC::Server::Packet(buffer, size), result)) {
result.set();
}
});
result.get();
// send(request);
}
private:
static void check(const Methcla_Engine* engine, Methcla_Error err)
{
if (err != kMethcla_NoError) {
const char* msg = methcla_engine_error_message(engine, err);
if (err == kMethcla_InvalidArgument)
throw std::invalid_argument(msg);
else if (err == kMethcla_BadAlloc)
throw std::bad_alloc();
else
throw std::runtime_error(msg);
}
}
static void handlePacket(void* data, Methcla_RequestId requestId, const void* packet, size_t size)
{
static_cast<Engine*>(data)->handlePacket(requestId, packet, size);
}
void handlePacket(Methcla_RequestId requestId, const void* packet, size_t size)
{
std::lock_guard<std::mutex> lock(m_callbacksMutex);
// look up request id and invoke callback
auto it = m_callbacks.find(requestId);
if (it != m_callbacks.end()) {
try {
it->second(requestId, packet, size);
m_callbacks.erase(it);
} catch (...) {
m_callbacks.erase(it);
throw;
}
}
}
void send(const void* packet, size_t size)
{
methcla_engine_send(m_engine, packet, size);
}
void send(const OSC::Client::Packet& packet)
{
send(packet.data(), packet.size());
}
Methcla_RequestId getRequestId()
{
std::lock_guard<std::mutex> lock(m_requestIdMutex);
Methcla_RequestId result = m_requestId;
if (result == kMethcla_Notification) {
result++;
}
m_requestId = result + 1;
return result;
}
void registerResponse(Methcla_RequestId requestId, std::function<void (Methcla_RequestId, const void*, size_t)> callback)
{
std::lock_guard<std::mutex> lock(m_callbacksMutex);
BOOST_ASSERT_MSG( m_callbacks.find(requestId) == m_callbacks.end(), "Duplicate request id" );
m_callbacks[requestId] = callback;
}
void withRequest(Methcla_RequestId requestId, const OSC::Client::Packet& request, std::function<void (Methcla_RequestId, const void*, size_t)> callback)
{
registerResponse(requestId, callback);
send(request);
}
private:
Methcla_Engine* m_engine;
Methcla_RequestId m_requestId;
std::mutex m_requestIdMutex;
std::unordered_map<Methcla_RequestId,std::function<void (Methcla_RequestId, const void*, size_t)>> m_callbacks;
std::mutex m_callbacksMutex;
};
};
#endif // METHCLA_ENGINE_HPP_INCLUDED
<|endoftext|>
|
<commit_before>#include "LinearModule.h"
#include <cstdio>
LinearModule::LinearModule(ModularSynth& synth)
:SynthModule(synth, moduleId, 3, 1, 0)
{
}
void LinearModule::cycle()
{
float input = getInput(0);
float x = std::min(1.0f, std::max(0.0f, getInput(1)));
float y = std::min(1.0f, std::max(0.0f, getInput(1)));
float amp;
if (input >= x)
{
amp = (input - y) * (input - x) + y;
}
else
{
amp = input * y / x;
}
setOutput(0, input * amp);
}
const char * LinearModule::getInputName(int input) const
{
static const char *names[] = {"Input", "X", "Y"};
return names[input];
}
const char * LinearModule::getOutputName(int output) const
{
static const char *names[] = {"Output"};
return names[output];
}
const char * LinearModule::getName() const
{
return "Linear";
}
SynthModule * LinearModule::createModule(ModularSynth& synth)
{
return new LinearModule(synth);
}
<commit_msg>LinearModule<commit_after>#include "LinearModule.h"
#include <cstdio>
#include <algorithm>
LinearModule::LinearModule(ModularSynth& synth)
:SynthModule(synth, moduleId, 3, 1, 0)
{
}
void LinearModule::cycle()
{
float input = getInput(0);
float x = std::min(1.0f, std::max(0.0f, getInput(1)));
float y = std::min(1.0f, std::max(0.0f, getInput(2)));
float amp;
if (input >= x)
{
amp = (1.0f - y) * (input - x) / (1.0f - x) + y;
}
else
{
amp = y * input / x;
}
setOutput(0, amp);
}
const char * LinearModule::getInputName(int input) const
{
static const char *names[] = {"Input", "X", "Y"};
return names[input];
}
const char * LinearModule::getOutputName(int output) const
{
static const char *names[] = {"Output"};
return names[output];
}
const char * LinearModule::getName() const
{
return "Linear";
}
SynthModule * LinearModule::createModule(ModularSynth& synth)
{
return new LinearModule(synth);
}
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "qt5nodeinstanceclientproxy.h"
#include <QCoreApplication>
#include "qt5informationnodeinstanceserver.h"
#include "qt5previewnodeinstanceserver.h"
#include "qt5rendernodeinstanceserver.h"
namespace QmlDesigner {
Qt5NodeInstanceClientProxy::Qt5NodeInstanceClientProxy(QObject *parent) :
NodeInstanceClientProxy(parent)
{
if (QCoreApplication::arguments().at(2) == QLatin1String("previewmode")) {
setNodeInstanceServer(new Qt5PreviewNodeInstanceServer(this));
} else if (QCoreApplication::arguments().at(2) == QLatin1String("editormode")) {
setNodeInstanceServer(new Qt5InformationNodeInstanceServer(this));
} else if (QCoreApplication::arguments().at(2) == QLatin1String("rendermode")) {
setNodeInstanceServer(new Qt5RenderNodeInstanceServer(this));
}
initializeSocket();
}
} // namespace QmlDesigner
<commit_msg>QmlDesigner.NodeInstances: Quick Window Manager Support<commit_after>/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "qt5nodeinstanceclientproxy.h"
#include <QCoreApplication>
#include "qt5informationnodeinstanceserver.h"
#include "qt5previewnodeinstanceserver.h"
#include "qt5rendernodeinstanceserver.h"
#include <designersupport.h>
namespace QmlDesigner {
Qt5NodeInstanceClientProxy::Qt5NodeInstanceClientProxy(QObject *parent) :
NodeInstanceClientProxy(parent)
{
DesignerSupport::activateDesignerWindowManager();
if (QCoreApplication::arguments().at(2) == QLatin1String("previewmode")) {
setNodeInstanceServer(new Qt5PreviewNodeInstanceServer(this));
} else if (QCoreApplication::arguments().at(2) == QLatin1String("editormode")) {
setNodeInstanceServer(new Qt5InformationNodeInstanceServer(this));
} else if (QCoreApplication::arguments().at(2) == QLatin1String("rendermode")) {
setNodeInstanceServer(new Qt5RenderNodeInstanceServer(this));
}
initializeSocket();
}
} // namespace QmlDesigner
<|endoftext|>
|
<commit_before>#include <sys/errno.h>
#include <sys/uio.h>
#include <errno.h>
#include <limits.h>
#include <unistd.h>
#include <common/buffer.h>
#include <event/action.h>
#include <event/callback.h>
#include <event/event_system.h>
#include <io/io_system.h>
IOSystem::Handle::Handle(int fd, Channel *owner)
: log_("/io/system/handle"),
fd_(fd),
owner_(owner),
close_callback_(NULL),
close_action_(NULL),
read_amount_(0),
read_buffer_(),
read_callback_(NULL),
read_action_(NULL),
write_buffer_(),
write_callback_(NULL),
write_action_(NULL)
{ }
IOSystem::Handle::~Handle()
{
ASSERT(fd_ == -1);
ASSERT(close_action_ == NULL);
ASSERT(close_callback_ == NULL);
ASSERT(read_action_ == NULL);
ASSERT(read_callback_ == NULL);
ASSERT(write_action_ == NULL);
ASSERT(write_callback_ == NULL);
}
void
IOSystem::Handle::close_callback(void)
{
close_action_->cancel();
close_action_ = NULL;
ASSERT(fd_ != -1);
int rv = ::close(fd_);
if (rv == -1) {
switch (errno) {
case EAGAIN:
close_action_ = close_schedule();
break;
default:
close_callback_->event(Event(Event::Error, errno));
Action *a = EventSystem::instance()->schedule(close_callback_);
close_action_ = a;
close_callback_ = NULL;
break;
}
return;
}
fd_ = -1;
close_callback_->event(Event(Event::Done, 0));
Action *a = EventSystem::instance()->schedule(close_callback_);
close_action_ = a;
close_callback_ = NULL;
}
void
IOSystem::Handle::close_cancel(void)
{
ASSERT(close_action_ != NULL);
close_action_->cancel();
close_action_ = NULL;
if (close_callback_ != NULL) {
delete close_callback_;
close_callback_ = NULL;
}
}
Action *
IOSystem::Handle::close_schedule(void)
{
ASSERT(close_action_ == NULL);
Callback *cb = callback(this, &IOSystem::Handle::close_callback);
Action *a = EventSystem::instance()->schedule(cb);
return (a);
}
void
IOSystem::Handle::read_callback(Event e)
{
read_action_->cancel();
read_action_ = NULL;
switch (e.type_) {
case Event::EOS:
case Event::Done:
break;
default:
HALT(log_) << "Unexpected event: " << e;
}
size_t rlen;
if (read_amount_ == 0)
rlen = 65536;
else
rlen = read_amount_ - read_buffer_.length();
ASSERT(rlen != 0);
uint8_t data[rlen];
ssize_t len = ::read(fd_, data, sizeof data);
if (len == -1) {
switch (errno) {
case EAGAIN:
read_action_ = read_schedule();
break;
default:
read_callback_->event(Event(Event::Error, errno, read_buffer_));
Action *a = EventSystem::instance()->schedule(read_callback_);
read_action_ = a;
read_callback_ = NULL;
read_buffer_.clear();
read_amount_ = 0;
break;
}
return;
}
/*
* XXX
* If we get an EOS from EventPoll, should we just terminate after that
* one read? How can we tell how much data is still available to be
* read? Will we get it all in one read? Eventually, one would expect
* to get a read with a length of 0, or an error, but will kevent even
* continue to fire off read events?
*/
if (len == 0) {
read_callback_->event(Event(Event::EOS, 0, read_buffer_));
Action *a = EventSystem::instance()->schedule(read_callback_);
read_action_ = a;
read_callback_ = NULL;
read_buffer_.clear();
read_amount_ = 0;
return;
}
read_buffer_.append(data, len);
read_action_ = read_schedule();
}
void
IOSystem::Handle::read_cancel(void)
{
ASSERT(read_action_ != NULL);
read_action_->cancel();
read_action_ = NULL;
if (read_callback_ != NULL) {
delete read_callback_;
read_callback_ = NULL;
}
}
Action *
IOSystem::Handle::read_schedule(void)
{
ASSERT(read_action_ == NULL);
if (!read_buffer_.empty() && read_buffer_.length() >= read_amount_) {
if (read_amount_ == 0)
read_amount_ = read_buffer_.length();
read_callback_->event(Event(Event::Done, 0, Buffer(read_buffer_, read_amount_)));
Action *a = EventSystem::instance()->schedule(read_callback_);
read_callback_ = NULL;
read_buffer_.skip(read_amount_);
read_amount_ = 0;
return (a);
}
EventCallback *cb = callback(this, &IOSystem::Handle::read_callback);
Action *a = EventSystem::instance()->poll(EventPoll::Readable, fd_, cb);
return (a);
}
void
IOSystem::Handle::write_callback(Event e)
{
write_action_->cancel();
write_action_ = NULL;
switch (e.type_) {
case Event::EOS:
case Event::Done:
break;
default:
HALT(log_) << "Unexpected event: " << e;
}
/* XXX This doesn't handle UDP nicely. Right? */
struct iovec iov[IOV_MAX];
size_t iovcnt = write_buffer_.fill_iovec(iov, IOV_MAX);
ssize_t len = ::writev(fd_, iov, iovcnt);
if (len == -1) {
switch (errno) {
case EAGAIN:
write_action_ = write_schedule();
break;
default:
write_callback_->event(Event(Event::Error, errno));
Action *a = EventSystem::instance()->schedule(write_callback_);
write_action_ = a;
write_callback_ = NULL;
break;
}
return;
}
write_buffer_.skip(len);
if (write_buffer_.empty()) {
write_callback_->event(Event(Event::Done, 0));
Action *a = EventSystem::instance()->schedule(write_callback_);
write_action_ = a;
write_callback_ = NULL;
return;
}
write_action_ = write_schedule();
}
void
IOSystem::Handle::write_cancel(void)
{
ASSERT(write_action_ != NULL);
write_action_->cancel();
write_action_ = NULL;
if (write_callback_ != NULL) {
delete write_callback_;
write_callback_ = NULL;
}
}
Action *
IOSystem::Handle::write_schedule(void)
{
ASSERT(write_action_ == NULL);
EventCallback *cb = callback(this, &IOSystem::Handle::write_callback);
Action *a = EventSystem::instance()->poll(EventPoll::Writable, fd_, cb);
return (a);
}
IOSystem::IOSystem(void)
: log_("/io/system"),
handle_map_()
{ }
IOSystem::~IOSystem()
{
ASSERT(handle_map_.empty());
}
void
IOSystem::attach(int fd, Channel *owner)
{
ASSERT(handle_map_.find(handle_key_t(fd, owner)) == handle_map_.end());
handle_map_[handle_key_t(fd, owner)] = new IOSystem::Handle(fd, owner);
}
void
IOSystem::detach(int fd, Channel *owner)
{
handle_map_t::iterator it;
IOSystem::Handle *h;
it = handle_map_.find(handle_key_t(fd, owner));
ASSERT(it != handle_map_.end());
h = it->second;
ASSERT(h != NULL);
ASSERT(h->owner_ == owner);
handle_map_.erase(it);
delete h;
}
Action *
IOSystem::close(int fd, Channel *owner, EventCallback *cb)
{
IOSystem::Handle *h;
h = handle_map_[handle_key_t(fd, owner)];
ASSERT(h != NULL);
ASSERT(h->close_callback_ == NULL);
ASSERT(h->close_action_ == NULL);
ASSERT(h->read_callback_ == NULL);
ASSERT(h->read_action_ == NULL);
ASSERT(h->write_callback_ == NULL);
ASSERT(h->write_action_ == NULL);
ASSERT(h->fd_ != -1);
h->close_callback_ = cb;
h->close_action_ = h->close_schedule();
return (cancellation(h, &IOSystem::Handle::close_cancel));
}
Action *
IOSystem::read(int fd, Channel *owner, size_t amount, EventCallback *cb)
{
IOSystem::Handle *h;
h = handle_map_[handle_key_t(fd, owner)];
ASSERT(h != NULL);
ASSERT(h->read_callback_ == NULL);
ASSERT(h->read_action_ == NULL);
h->read_amount_ = amount;
h->read_callback_ = cb;
h->read_action_ = h->read_schedule();
return (cancellation(h, &IOSystem::Handle::read_cancel));
}
Action *
IOSystem::write(int fd, Channel *owner, Buffer *buffer, EventCallback *cb)
{
IOSystem::Handle *h;
h = handle_map_[handle_key_t(fd, owner)];
ASSERT(h != NULL);
ASSERT(h->write_callback_ == NULL);
ASSERT(h->write_action_ == NULL);
ASSERT(h->write_buffer_.empty());
h->write_buffer_.append(buffer);
buffer->clear();
h->write_callback_ = cb;
h->write_action_ = h->write_schedule();
return (cancellation(h, &IOSystem::Handle::write_cancel));
}
<commit_msg>Only ever try to read 64K onto the stack at a time.<commit_after>#include <sys/errno.h>
#include <sys/uio.h>
#include <errno.h>
#include <limits.h>
#include <unistd.h>
#include <common/buffer.h>
#include <event/action.h>
#include <event/callback.h>
#include <event/event_system.h>
#include <io/io_system.h>
#define IO_READ_BUFFER_SIZE 65536
IOSystem::Handle::Handle(int fd, Channel *owner)
: log_("/io/system/handle"),
fd_(fd),
owner_(owner),
close_callback_(NULL),
close_action_(NULL),
read_amount_(0),
read_buffer_(),
read_callback_(NULL),
read_action_(NULL),
write_buffer_(),
write_callback_(NULL),
write_action_(NULL)
{ }
IOSystem::Handle::~Handle()
{
ASSERT(fd_ == -1);
ASSERT(close_action_ == NULL);
ASSERT(close_callback_ == NULL);
ASSERT(read_action_ == NULL);
ASSERT(read_callback_ == NULL);
ASSERT(write_action_ == NULL);
ASSERT(write_callback_ == NULL);
}
void
IOSystem::Handle::close_callback(void)
{
close_action_->cancel();
close_action_ = NULL;
ASSERT(fd_ != -1);
int rv = ::close(fd_);
if (rv == -1) {
switch (errno) {
case EAGAIN:
close_action_ = close_schedule();
break;
default:
close_callback_->event(Event(Event::Error, errno));
Action *a = EventSystem::instance()->schedule(close_callback_);
close_action_ = a;
close_callback_ = NULL;
break;
}
return;
}
fd_ = -1;
close_callback_->event(Event(Event::Done, 0));
Action *a = EventSystem::instance()->schedule(close_callback_);
close_action_ = a;
close_callback_ = NULL;
}
void
IOSystem::Handle::close_cancel(void)
{
ASSERT(close_action_ != NULL);
close_action_->cancel();
close_action_ = NULL;
if (close_callback_ != NULL) {
delete close_callback_;
close_callback_ = NULL;
}
}
Action *
IOSystem::Handle::close_schedule(void)
{
ASSERT(close_action_ == NULL);
Callback *cb = callback(this, &IOSystem::Handle::close_callback);
Action *a = EventSystem::instance()->schedule(cb);
return (a);
}
void
IOSystem::Handle::read_callback(Event e)
{
read_action_->cancel();
read_action_ = NULL;
switch (e.type_) {
case Event::EOS:
case Event::Done:
break;
default:
HALT(log_) << "Unexpected event: " << e;
}
size_t rlen;
if (read_amount_ == 0)
rlen = IO_READ_BUFFER_SIZE;
else {
rlen = read_amount_ - read_buffer_.length();
ASSERT(rlen != 0);
if (rlen > IO_READ_BUFFER_SIZE)
rlen = IO_READ_BUFFER_SIZE;
}
uint8_t data[IO_READ_BUFFER_SIZE];
ssize_t len = ::read(fd_, data, sizeof data);
if (len == -1) {
switch (errno) {
case EAGAIN:
read_action_ = read_schedule();
break;
default:
read_callback_->event(Event(Event::Error, errno, read_buffer_));
Action *a = EventSystem::instance()->schedule(read_callback_);
read_action_ = a;
read_callback_ = NULL;
read_buffer_.clear();
read_amount_ = 0;
break;
}
return;
}
/*
* XXX
* If we get an EOS from EventPoll, should we just terminate after that
* one read? How can we tell how much data is still available to be
* read? Will we get it all in one read? Eventually, one would expect
* to get a read with a length of 0, or an error, but will kevent even
* continue to fire off read events?
*/
if (len == 0) {
read_callback_->event(Event(Event::EOS, 0, read_buffer_));
Action *a = EventSystem::instance()->schedule(read_callback_);
read_action_ = a;
read_callback_ = NULL;
read_buffer_.clear();
read_amount_ = 0;
return;
}
read_buffer_.append(data, len);
read_action_ = read_schedule();
}
void
IOSystem::Handle::read_cancel(void)
{
ASSERT(read_action_ != NULL);
read_action_->cancel();
read_action_ = NULL;
if (read_callback_ != NULL) {
delete read_callback_;
read_callback_ = NULL;
}
}
Action *
IOSystem::Handle::read_schedule(void)
{
ASSERT(read_action_ == NULL);
if (!read_buffer_.empty() && read_buffer_.length() >= read_amount_) {
if (read_amount_ == 0)
read_amount_ = read_buffer_.length();
read_callback_->event(Event(Event::Done, 0, Buffer(read_buffer_, read_amount_)));
Action *a = EventSystem::instance()->schedule(read_callback_);
read_callback_ = NULL;
read_buffer_.skip(read_amount_);
read_amount_ = 0;
return (a);
}
EventCallback *cb = callback(this, &IOSystem::Handle::read_callback);
Action *a = EventSystem::instance()->poll(EventPoll::Readable, fd_, cb);
return (a);
}
void
IOSystem::Handle::write_callback(Event e)
{
write_action_->cancel();
write_action_ = NULL;
switch (e.type_) {
case Event::EOS:
case Event::Done:
break;
default:
HALT(log_) << "Unexpected event: " << e;
}
/* XXX This doesn't handle UDP nicely. Right? */
struct iovec iov[IOV_MAX];
size_t iovcnt = write_buffer_.fill_iovec(iov, IOV_MAX);
ssize_t len = ::writev(fd_, iov, iovcnt);
if (len == -1) {
switch (errno) {
case EAGAIN:
write_action_ = write_schedule();
break;
default:
write_callback_->event(Event(Event::Error, errno));
Action *a = EventSystem::instance()->schedule(write_callback_);
write_action_ = a;
write_callback_ = NULL;
break;
}
return;
}
write_buffer_.skip(len);
if (write_buffer_.empty()) {
write_callback_->event(Event(Event::Done, 0));
Action *a = EventSystem::instance()->schedule(write_callback_);
write_action_ = a;
write_callback_ = NULL;
return;
}
write_action_ = write_schedule();
}
void
IOSystem::Handle::write_cancel(void)
{
ASSERT(write_action_ != NULL);
write_action_->cancel();
write_action_ = NULL;
if (write_callback_ != NULL) {
delete write_callback_;
write_callback_ = NULL;
}
}
Action *
IOSystem::Handle::write_schedule(void)
{
ASSERT(write_action_ == NULL);
EventCallback *cb = callback(this, &IOSystem::Handle::write_callback);
Action *a = EventSystem::instance()->poll(EventPoll::Writable, fd_, cb);
return (a);
}
IOSystem::IOSystem(void)
: log_("/io/system"),
handle_map_()
{ }
IOSystem::~IOSystem()
{
ASSERT(handle_map_.empty());
}
void
IOSystem::attach(int fd, Channel *owner)
{
ASSERT(handle_map_.find(handle_key_t(fd, owner)) == handle_map_.end());
handle_map_[handle_key_t(fd, owner)] = new IOSystem::Handle(fd, owner);
}
void
IOSystem::detach(int fd, Channel *owner)
{
handle_map_t::iterator it;
IOSystem::Handle *h;
it = handle_map_.find(handle_key_t(fd, owner));
ASSERT(it != handle_map_.end());
h = it->second;
ASSERT(h != NULL);
ASSERT(h->owner_ == owner);
handle_map_.erase(it);
delete h;
}
Action *
IOSystem::close(int fd, Channel *owner, EventCallback *cb)
{
IOSystem::Handle *h;
h = handle_map_[handle_key_t(fd, owner)];
ASSERT(h != NULL);
ASSERT(h->close_callback_ == NULL);
ASSERT(h->close_action_ == NULL);
ASSERT(h->read_callback_ == NULL);
ASSERT(h->read_action_ == NULL);
ASSERT(h->write_callback_ == NULL);
ASSERT(h->write_action_ == NULL);
ASSERT(h->fd_ != -1);
h->close_callback_ = cb;
h->close_action_ = h->close_schedule();
return (cancellation(h, &IOSystem::Handle::close_cancel));
}
Action *
IOSystem::read(int fd, Channel *owner, size_t amount, EventCallback *cb)
{
IOSystem::Handle *h;
h = handle_map_[handle_key_t(fd, owner)];
ASSERT(h != NULL);
ASSERT(h->read_callback_ == NULL);
ASSERT(h->read_action_ == NULL);
h->read_amount_ = amount;
h->read_callback_ = cb;
h->read_action_ = h->read_schedule();
return (cancellation(h, &IOSystem::Handle::read_cancel));
}
Action *
IOSystem::write(int fd, Channel *owner, Buffer *buffer, EventCallback *cb)
{
IOSystem::Handle *h;
h = handle_map_[handle_key_t(fd, owner)];
ASSERT(h != NULL);
ASSERT(h->write_callback_ == NULL);
ASSERT(h->write_action_ == NULL);
ASSERT(h->write_buffer_.empty());
h->write_buffer_.append(buffer);
buffer->clear();
h->write_callback_ = cb;
h->write_action_ = h->write_schedule();
return (cancellation(h, &IOSystem::Handle::write_cancel));
}
<|endoftext|>
|
<commit_before>/*
* ESP8266 LLMNR responder
* Copyright (C) 2017 Stephen Warren <swarren@wwwdotorg.org>
*
* Based on:
* ESP8266 Multicast DNS (port of CC3000 Multicast DNS library)
* Version 1.1
* Copyright (c) 2013 Tony DiCola (tony@tonydicola.com)
* ESP8266 port (c) 2015 Ivan Grokhotkov (ivan@esp8266.com)
* MDNS-SD Suport 2015 Hristo Gochkov
* Extended MDNS-SD support 2016 Lars Englund (lars.englund@gmail.com)
*
* License (MIT license):
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* Reference:
* https://tools.ietf.org/html/rfc4795 (LLMNR)
* https://tools.ietf.org/html/rfc1035 (DNS)
*/
#include <debug.h>
#include <functional>
#include <ESP8266LLMNR.h>
#include <WiFiUdp.h>
extern "C" {
#include <user_interface.h>
}
#include <lwip/udp.h>
#include <lwip/igmp.h>
#include <include/UdpContext.h>
//#define LLMNR_DEBUG
#define BIT(x) (1 << (x))
#define FLAGS_QR BIT(15)
#define FLAGS_OP_SHIFT 11
#define FLAGS_OP_MASK 0xf
#define FLAGS_C BIT(10)
#define FLAGS_TC BIT(9)
#define FLAGS_T BIT(8)
#define FLAGS_RCODE_SHIFT 0
#define FLAGS_RCODE_MASK 0xf
#define _conn_read16() (((uint16_t)_conn->read() << 8) | _conn->read())
#define _conn_read8() _conn->read()
#define _conn_readS(b, l) _conn->read((b), (l));
static const IPAddress LLMNR_MULTICAST_ADDR(224, 0, 0, 252);
static const int LLMNR_MULTICAST_TTL = 1;
static const int LLMNR_PORT = 5355;
LLMNRResponder::LLMNRResponder() :
_conn(0) {
}
LLMNRResponder::~LLMNRResponder() {
if (_conn)
_conn->unref();
}
bool LLMNRResponder::begin(const char* hostname) {
// Max length for a single label in DNS
if (strlen(hostname) > 63)
return false;
_hostname = hostname;
_hostname.toLowerCase();
_sta_got_ip_handler = WiFi.onStationModeGotIP([this](const WiFiEventStationModeGotIP& event){
_restart();
});
_sta_disconnected_handler = WiFi.onStationModeDisconnected([this](const WiFiEventStationModeDisconnected& event) {
_restart();
});
return _restart();
}
void LLMNRResponder::notify_ap_change() {
_restart();
}
bool LLMNRResponder::_restart() {
if (_conn) {
_conn->unref();
_conn = 0;
}
ip_addr_t multicast_addr;
multicast_addr.addr = (uint32_t)LLMNR_MULTICAST_ADDR;
if (igmp_joingroup(IP_ADDR_ANY, &multicast_addr) != ERR_OK)
return false;
_conn = new UdpContext;
_conn->ref();
if (!_conn->listen(*IP_ADDR_ANY, LLMNR_PORT))
return false;
_conn->setMulticastTTL(LLMNR_MULTICAST_TTL);
_conn->onRx(std::bind(&LLMNRResponder::_process_packet, this));
_conn->connect(multicast_addr, LLMNR_PORT);
}
void LLMNRResponder::_process_packet() {
if (!_conn || !_conn->next())
return;
#ifdef LLMNR_DEBUG
Serial.println("LLMNR: RX'd packet");
#endif
uint16_t id = _conn_read16();
uint16_t flags = _conn_read16();
uint16_t qdcount = _conn_read16();
uint16_t ancount = _conn_read16();
uint16_t nscount = _conn_read16();
uint16_t arcount = _conn_read16();
#ifdef LLMNR_DEBUG
Serial.print("LLMNR: ID=");
Serial.println(id, HEX);
Serial.print("LLMNR: FLAGS=");
Serial.println(flags, HEX);
Serial.print("LLMNR: QDCOUNT=");
Serial.println(qdcount);
Serial.print("LLMNR: ANCOUNT=");
Serial.println(ancount);
Serial.print("LLMNR: NSCOUNT=");
Serial.println(nscount);
Serial.print("LLMNR: ARCOUNT=");
Serial.println(arcount);
#endif
#define BAD_FLAGS (FLAGS_QR | (FLAGS_OP_MASK << FLAGS_OP_SHIFT) | FLAGS_C)
if (flags & BAD_FLAGS) {
#ifdef LLMNR_DEBUG
Serial.println("Bad flags");
#endif
return;
}
if (qdcount != 1) {
#ifdef LLMNR_DEBUG
Serial.println("QDCOUNT != 1");
#endif
return;
}
if (ancount || nscount || arcount) {
#ifdef LLMNR_DEBUG
Serial.println("AN/NS/AR-COUNT != 0");
#endif
return;
}
uint8_t namelen = _conn_read8();
#ifdef LLMNR_DEBUG
Serial.print("QNAME len ");
Serial.println(namelen);
#endif
if (namelen != _hostname.length()) {
#ifdef LLMNR_DEBUG
Serial.println("QNAME len mismatch");
#endif
return;
}
char qname[64];
_conn_readS(qname, namelen);
_conn_read8();
qname[namelen] = '\0';
#ifdef LLMNR_DEBUG
Serial.print("QNAME ");
Serial.println(qname);
#endif
if (strcmp(_hostname.c_str(), qname)) {
#ifdef LLMNR_DEBUG
Serial.println("QNAME mismatch");
#endif
return;
}
uint16_t qtype = _conn_read16();
uint16_t qclass = _conn_read16();
#ifdef LLMNR_DEBUG
Serial.print("QTYPE ");
Serial.print(qtype);
Serial.print(" QCLASS ");
Serial.println(qclass);
#endif
bool have_rr =
(qtype == 1) && /* A */
(qclass == 1); /* IN */
_conn->flush();
#ifdef LLMNR_DEBUG
Serial.println("Match; responding");
if (!have_rr)
Serial.println("(no matching RRs)");
#endif
struct ip_info remote_ip_info;
remote_ip_info.ip.addr = _conn->getRemoteAddress();
struct ip_info ip_info;
bool match_ap = false;
if (wifi_get_opmode() & SOFTAP_MODE) {
wifi_get_ip_info(SOFTAP_IF, &ip_info);
if (ip_info.ip.addr && ip_addr_netcmp(&remote_ip_info.ip, &ip_info.ip, &ip_info.netmask))
match_ap = true;
}
if (!match_ap)
wifi_get_ip_info(STATION_IF, &ip_info);
uint32_t ip = ip_info.ip.addr;
// Header
uint8_t header[] = {
id >> 8, id & 0xff, // ID
FLAGS_QR >> 8, 0, // FLAGS
0, 1, // QDCOUNT
0, !!have_rr, // ANCOUNT
0, 0, // NSCOUNT
0, 0, // ARCOUNT
};
_conn->append(reinterpret_cast<const char*>(header), sizeof(header));
// Question
_conn->append(reinterpret_cast<const char*>(&namelen), 1);
_conn->append(qname, namelen);
uint8_t q[] = {
0, // Name terminator
0, 1, // TYPE (A)
0, 1, // CLASS (IN)
};
_conn->append(reinterpret_cast<const char*>(q), sizeof(q));
// Answer, if we have one
if (have_rr) {
_conn->append(reinterpret_cast<const char*>(&namelen), 1);
_conn->append(qname, namelen);
uint8_t rr[] = {
0, // Name terminator
0, 1, // TYPE (A)
0, 1, // CLASS (IN)
0, 0, 0, 30, // TTL (30 seconds)
0, 4, // RDLENGTH
ip & 0xff, (ip >> 8) & 0xff, (ip >> 16) & 0xff, (ip >> 24) & 0xff, // RDATA
};
_conn->append(reinterpret_cast<const char*>(rr), sizeof(rr));
}
_conn->setMulticastInterface(remote_ip_info.ip);
_conn->send(&remote_ip_info.ip, _conn->getRemotePort());
}
#if !defined(NO_GLOBAL_INSTANCES) && !defined(NO_GLOBAL_LLMNR)
LLMNRResponder LLMNR;
#endif
<commit_msg>Fix ESP8266LLMNR for build with lwip2 (#3821)<commit_after>/*
* ESP8266 LLMNR responder
* Copyright (C) 2017 Stephen Warren <swarren@wwwdotorg.org>
*
* Based on:
* ESP8266 Multicast DNS (port of CC3000 Multicast DNS library)
* Version 1.1
* Copyright (c) 2013 Tony DiCola (tony@tonydicola.com)
* ESP8266 port (c) 2015 Ivan Grokhotkov (ivan@esp8266.com)
* MDNS-SD Suport 2015 Hristo Gochkov
* Extended MDNS-SD support 2016 Lars Englund (lars.englund@gmail.com)
*
* License (MIT license):
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* Reference:
* https://tools.ietf.org/html/rfc4795 (LLMNR)
* https://tools.ietf.org/html/rfc1035 (DNS)
*/
#include <debug.h>
#include <functional>
#include <ESP8266LLMNR.h>
#include <WiFiUdp.h>
extern "C" {
#include <user_interface.h>
}
#include <lwip/udp.h>
#include <lwip/igmp.h>
#include <include/UdpContext.h>
//#define LLMNR_DEBUG
//BIT(x) is defined in tools/sdk/c_types.h
#define FLAGS_QR BIT(15)
#define FLAGS_OP_SHIFT 11
#define FLAGS_OP_MASK 0xf
#define FLAGS_C BIT(10)
#define FLAGS_TC BIT(9)
#define FLAGS_T BIT(8)
#define FLAGS_RCODE_SHIFT 0
#define FLAGS_RCODE_MASK 0xf
#define _conn_read16() (((uint16_t)_conn->read() << 8) | _conn->read())
#define _conn_read8() _conn->read()
#define _conn_readS(b, l) _conn->read((b), (l));
static const IPAddress LLMNR_MULTICAST_ADDR(224, 0, 0, 252);
static const int LLMNR_MULTICAST_TTL = 1;
static const int LLMNR_PORT = 5355;
LLMNRResponder::LLMNRResponder() :
_conn(0) {
}
LLMNRResponder::~LLMNRResponder() {
if (_conn)
_conn->unref();
}
bool LLMNRResponder::begin(const char* hostname) {
// Max length for a single label in DNS
if (strlen(hostname) > 63)
return false;
_hostname = hostname;
_hostname.toLowerCase();
_sta_got_ip_handler = WiFi.onStationModeGotIP([this](const WiFiEventStationModeGotIP& event){
_restart();
});
_sta_disconnected_handler = WiFi.onStationModeDisconnected([this](const WiFiEventStationModeDisconnected& event) {
_restart();
});
return _restart();
}
void LLMNRResponder::notify_ap_change() {
_restart();
}
bool LLMNRResponder::_restart() {
if (_conn) {
_conn->unref();
_conn = 0;
}
ip_addr_t multicast_addr;
multicast_addr.addr = (uint32_t)LLMNR_MULTICAST_ADDR;
if (igmp_joingroup(IP_ADDR_ANY, &multicast_addr) != ERR_OK)
return false;
_conn = new UdpContext;
_conn->ref();
if (!_conn->listen(*IP_ADDR_ANY, LLMNR_PORT))
return false;
_conn->setMulticastTTL(LLMNR_MULTICAST_TTL);
_conn->onRx(std::bind(&LLMNRResponder::_process_packet, this));
_conn->connect(multicast_addr, LLMNR_PORT);
}
void LLMNRResponder::_process_packet() {
if (!_conn || !_conn->next())
return;
#ifdef LLMNR_DEBUG
Serial.println("LLMNR: RX'd packet");
#endif
uint16_t id = _conn_read16();
uint16_t flags = _conn_read16();
uint16_t qdcount = _conn_read16();
uint16_t ancount = _conn_read16();
uint16_t nscount = _conn_read16();
uint16_t arcount = _conn_read16();
#ifdef LLMNR_DEBUG
Serial.print("LLMNR: ID=");
Serial.println(id, HEX);
Serial.print("LLMNR: FLAGS=");
Serial.println(flags, HEX);
Serial.print("LLMNR: QDCOUNT=");
Serial.println(qdcount);
Serial.print("LLMNR: ANCOUNT=");
Serial.println(ancount);
Serial.print("LLMNR: NSCOUNT=");
Serial.println(nscount);
Serial.print("LLMNR: ARCOUNT=");
Serial.println(arcount);
#endif
#define BAD_FLAGS (FLAGS_QR | (FLAGS_OP_MASK << FLAGS_OP_SHIFT) | FLAGS_C)
if (flags & BAD_FLAGS) {
#ifdef LLMNR_DEBUG
Serial.println("Bad flags");
#endif
return;
}
if (qdcount != 1) {
#ifdef LLMNR_DEBUG
Serial.println("QDCOUNT != 1");
#endif
return;
}
if (ancount || nscount || arcount) {
#ifdef LLMNR_DEBUG
Serial.println("AN/NS/AR-COUNT != 0");
#endif
return;
}
uint8_t namelen = _conn_read8();
#ifdef LLMNR_DEBUG
Serial.print("QNAME len ");
Serial.println(namelen);
#endif
if (namelen != _hostname.length()) {
#ifdef LLMNR_DEBUG
Serial.println("QNAME len mismatch");
#endif
return;
}
char qname[64];
_conn_readS(qname, namelen);
_conn_read8();
qname[namelen] = '\0';
#ifdef LLMNR_DEBUG
Serial.print("QNAME ");
Serial.println(qname);
#endif
if (strcmp(_hostname.c_str(), qname)) {
#ifdef LLMNR_DEBUG
Serial.println("QNAME mismatch");
#endif
return;
}
uint16_t qtype = _conn_read16();
uint16_t qclass = _conn_read16();
#ifdef LLMNR_DEBUG
Serial.print("QTYPE ");
Serial.print(qtype);
Serial.print(" QCLASS ");
Serial.println(qclass);
#endif
bool have_rr =
(qtype == 1) && /* A */
(qclass == 1); /* IN */
_conn->flush();
#ifdef LLMNR_DEBUG
Serial.println("Match; responding");
if (!have_rr)
Serial.println("(no matching RRs)");
#endif
ip_addr_t remote_ip;
remote_ip.addr = _conn->getRemoteAddress();
struct ip_info ip_info;
bool match_ap = false;
if (wifi_get_opmode() & SOFTAP_MODE) {
wifi_get_ip_info(SOFTAP_IF, &ip_info);
if (ip_info.ip.addr && ip_addr_netcmp(&remote_ip, &ip_info.ip, &ip_info.netmask))
match_ap = true;
}
if (!match_ap)
wifi_get_ip_info(STATION_IF, &ip_info);
uint32_t ip = ip_info.ip.addr;
// Header
uint8_t header[] = {
id >> 8, id & 0xff, // ID
FLAGS_QR >> 8, 0, // FLAGS
0, 1, // QDCOUNT
0, !!have_rr, // ANCOUNT
0, 0, // NSCOUNT
0, 0, // ARCOUNT
};
_conn->append(reinterpret_cast<const char*>(header), sizeof(header));
// Question
_conn->append(reinterpret_cast<const char*>(&namelen), 1);
_conn->append(qname, namelen);
uint8_t q[] = {
0, // Name terminator
0, 1, // TYPE (A)
0, 1, // CLASS (IN)
};
_conn->append(reinterpret_cast<const char*>(q), sizeof(q));
// Answer, if we have one
if (have_rr) {
_conn->append(reinterpret_cast<const char*>(&namelen), 1);
_conn->append(qname, namelen);
uint8_t rr[] = {
0, // Name terminator
0, 1, // TYPE (A)
0, 1, // CLASS (IN)
0, 0, 0, 30, // TTL (30 seconds)
0, 4, // RDLENGTH
ip & 0xff, (ip >> 8) & 0xff, (ip >> 16) & 0xff, (ip >> 24) & 0xff, // RDATA
};
_conn->append(reinterpret_cast<const char*>(rr), sizeof(rr));
}
_conn->setMulticastInterface(remote_ip);
_conn->send(&remote_ip, _conn->getRemotePort());
}
#if !defined(NO_GLOBAL_INSTANCES) && !defined(NO_GLOBAL_LLMNR)
LLMNRResponder LLMNR;
#endif
<|endoftext|>
|
<commit_before>//===--- Stubs.cpp - Swift Language ABI Runtime Stubs ---------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Misc stubs for functions which should be defined in the core standard
// library, but are difficult or impossible to write in Swift at the
// moment.
//
//===----------------------------------------------------------------------===//
#if defined(__FreeBSD__)
#define _WITH_GETLINE
#endif
#include <sys/resource.h>
#include <sys/errno.h>
#include <unistd.h>
#include <climits>
#include <cstdarg>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#if defined(__CYGWIN__)
// Cygwin does not support uselocal() and locale_t.
// Instead, we will use the locale feature in stringstream.
typedef void *locale_t;
#include <sstream>
#include <cmath>
#define fmodl(lhs, rhs) std::fmod(lhs, rhs)
#else
#include <xlocale.h>
#endif
#include <limits>
#include "llvm/ADT/StringExtras.h"
#include "swift/Runtime/Debug.h"
#include "swift/Basic/Lazy.h"
static uint64_t uint64ToStringImpl(char *Buffer, uint64_t Value,
int64_t Radix, bool Uppercase,
bool Negative) {
char *P = Buffer;
uint64_t Y = Value;
if (Y == 0) {
*P++ = '0';
} else if (Radix == 10) {
while (Y) {
*P++ = '0' + char(Y % 10);
Y /= 10;
}
} else {
unsigned Radix32 = Radix;
while (Y) {
*P++ = llvm::hexdigit(Y % Radix32, !Uppercase);
Y /= Radix32;
}
}
if (Negative)
*P++ = '-';
std::reverse(Buffer, P);
return size_t(P - Buffer);
}
extern "C" uint64_t swift_int64ToString(char *Buffer, size_t BufferLength,
int64_t Value, int64_t Radix,
bool Uppercase) {
if ((Radix >= 10 && BufferLength < 32) || (Radix < 10 && BufferLength < 65))
swift::crash("swift_int64ToString: insufficient buffer size");
if (Radix == 0 || Radix > 36)
swift::crash("swift_int64ToString: invalid radix for string conversion");
bool Negative = Value < 0;
// Compute an absolute value safely, without using unary negation on INT_MIN,
// which is undefined behavior.
uint64_t UnsignedValue = Value;
if (Negative) {
// Assumes two's complement representation.
UnsignedValue = ~UnsignedValue + 1;
}
return uint64ToStringImpl(Buffer, UnsignedValue, Radix, Uppercase,
Negative);
}
extern "C" uint64_t swift_uint64ToString(char *Buffer, intptr_t BufferLength,
uint64_t Value, int64_t Radix,
bool Uppercase) {
if ((Radix >= 10 && BufferLength < 32) || (Radix < 10 && BufferLength < 64))
swift::crash("swift_int64ToString: insufficient buffer size");
if (Radix == 0 || Radix > 36)
swift::crash("swift_int64ToString: invalid radix for string conversion");
return uint64ToStringImpl(Buffer, Value, Radix, Uppercase,
/*Negative=*/false);
}
#if defined(__APPLE__) || defined(__FreeBSD__) || defined(__CYGWIN__)
static inline locale_t getCLocale() {
// On these platforms convenience functions from xlocale.h interpret nullptr
// as C locale.
return nullptr;
}
#else
static locale_t makeCLocale() {
locale_t CLocale = newlocale(LC_ALL_MASK, "C", nullptr);
if (!CLocale) {
swift::crash("makeCLocale: newlocale() returned a null pointer");
}
return CLocale;
}
static locale_t getCLocale() {
return SWIFT_LAZY_CONSTANT(makeCLocale());
}
#endif
#if defined(__APPLE__)
#define swift_snprintf_l snprintf_l
#elif defined(__CYGWIN__)
// In Cygwin, swift_snprintf_l() is not used.
#else
static int swift_snprintf_l(char *Str, size_t StrSize, locale_t Locale,
const char *Format, ...) {
if (Locale == nullptr) {
Locale = getCLocale();
}
locale_t OldLocale = uselocale(Locale);
va_list Args;
va_start(Args, Format);
int Result = std::vsnprintf(Str, StrSize, Format, Args);
va_end(Args);
uselocale(OldLocale);
return Result;
}
#endif
template <typename T>
static uint64_t swift_floatingPointToString(char *Buffer, size_t BufferLength,
T Value, const char *Format,
bool Debug) {
if (BufferLength < 32)
swift::crash("swift_floatingPointToString: insufficient buffer size");
int Precision = std::numeric_limits<T>::digits10;
if (Debug) {
Precision = std::numeric_limits<T>::max_digits10;
}
#if defined(__CYGWIN__)
// Cygwin does not support uselocale(), but we can use the locale feature
// in stringstrem object.
std::ostringstream ValueStream;
ValueStream.width(0);
ValueStream.precision(Precision);
ValueStream.imbue(std::locale::classic());
ValueStream << Value;
std::string ValueString(ValueStream.str());
int i = ValueString.length();
if (size_t(i) < BufferLength) {
std::copy(ValueString.begin(), ValueString.end(), Buffer);
Buffer[i] = '\0';
}
#else
// Pass a null locale to use the C locale.
int i = swift_snprintf_l(Buffer, BufferLength, /*locale=*/nullptr, Format,
Precision, Value);
#endif
if (i < 0)
swift::crash(
"swift_floatingPointToString: unexpected return value from sprintf");
if (size_t(i) >= BufferLength)
swift::crash("swift_floatingPointToString: insufficient buffer size");
// Add ".0" to a float that (a) is not in scientific notation, (b) does not
// already have a fractional part, (c) is not infinite, and (d) is not a NaN
// value.
if (strchr(Buffer, 'e') == nullptr && strchr(Buffer, '.') == nullptr &&
strchr(Buffer, 'n') == nullptr) {
Buffer[i++] = '.';
Buffer[i++] = '0';
}
return i;
}
extern "C" uint64_t swift_float32ToString(char *Buffer, size_t BufferLength,
float Value, bool Debug) {
return swift_floatingPointToString<float>(Buffer, BufferLength, Value,
"%0.*g", Debug);
}
extern "C" uint64_t swift_float64ToString(char *Buffer, size_t BufferLength,
double Value, bool Debug) {
return swift_floatingPointToString<double>(Buffer, BufferLength, Value,
"%0.*g", Debug);
}
extern "C" uint64_t swift_float80ToString(char *Buffer, size_t BufferLength,
long double Value, bool Debug) {
return swift_floatingPointToString<long double>(Buffer, BufferLength, Value,
"%0.*Lg", Debug);
}
/// \param[out] LinePtr Replaced with the pointer to the malloc()-allocated
/// line. Can be NULL if no characters were read.
///
/// \returns Size of character data returned in \c LinePtr, or -1
/// if an error occurred, or EOF was reached.
extern "C" ssize_t swift_stdlib_readLine_stdin(char **LinePtr) {
size_t Capacity = 0;
return getline(LinePtr, &Capacity, stdin);
}
extern "C" float _swift_fmodf(float lhs, float rhs) {
return fmodf(lhs, rhs);
}
extern "C" double _swift_fmod(double lhs, double rhs) {
return fmod(lhs, rhs);
}
extern "C" long double _swift_fmodl(long double lhs, long double rhs) {
return fmodl(lhs, rhs);
}
// Although this builtin is provided by clang rt builtins,
// it isn't provided by libgcc, which is the default
// runtime library on Linux, even when compiling with clang.
// This implementation is copied here to avoid a new dependency
// on compiler-rt on Linux.
// FIXME: rdar://14883575 Libcompiler_rt omits muloti4
#if (defined(__APPLE__) && defined(__arm64__)) || \
(defined(__linux__) && defined(__x86_64__)) || \
(defined(__linux__) && defined(__aarch64__)) || \
(defined(__linux__) && defined(__powerpc64__))
typedef int ti_int __attribute__ ((mode (TI)));
extern "C"
ti_int
__muloti4(ti_int a, ti_int b, int* overflow)
{
const int N = (int)(sizeof(ti_int) * CHAR_BIT);
const ti_int MIN = (ti_int)1 << (N-1);
const ti_int MAX = ~MIN;
*overflow = 0;
ti_int result = a * b;
if (a == MIN)
{
if (b != 0 && b != 1)
*overflow = 1;
return result;
}
if (b == MIN)
{
if (a != 0 && a != 1)
*overflow = 1;
return result;
}
ti_int sa = a >> (N - 1);
ti_int abs_a = (a ^ sa) - sa;
ti_int sb = b >> (N - 1);
ti_int abs_b = (b ^ sb) - sb;
if (abs_a < 2 || abs_b < 2)
return result;
if (sa == sb)
{
if (abs_a > MAX / abs_b)
*overflow = 1;
}
else
{
if (abs_a > MIN / -abs_b)
*overflow = 1;
}
return result;
}
#endif
#if defined(__linux__) && defined(__arm__)
// Similar to above, but with mulodi4. Perhaps this is
// something that shouldn't be done, and is a bandaid over
// some other lower-level architecture issue that I'm
// missing. Perhaps relevant bug report:
// FIXME: https://llvm.org/bugs/show_bug.cgi?id=14469
typedef int di_int __attribute__ ((mode (DI)));
extern "C"
di_int
__mulodi4(di_int a, di_int b, int* overflow)
{
const int N = (int)(sizeof(di_int) * CHAR_BIT);
const di_int MIN = (di_int)1 << (N-1);
const di_int MAX = ~MIN;
*overflow = 0;
di_int result = a * b;
if (a == MIN)
{
if (b != 0 && b != 1)
*overflow = 1;
return result;
}
if (b == MIN)
{
if (a != 0 && a != 1)
*overflow = 1;
return result;
}
di_int sa = a >> (N - 1);
di_int abs_a = (a ^ sa) - sa;
di_int sb = b >> (N - 1);
di_int abs_b = (b ^ sb) - sb;
if (abs_a < 2 || abs_b < 2)
return result;
if (sa == sb)
{
if (abs_a > MAX / abs_b)
*overflow = 1;
}
else
{
if (abs_a > MIN / -abs_b)
*overflow = 1;
}
return result;
}
#endif
#if defined(__CYGWIN__)
// Cygwin does not have strtoXX_l() functions.
// These are wrapper functions only for C locale.
static long double strtold_l(const char *nptr, char **EndPtr, locale_t) {
std::string lastLocale = setlocale(LC_ALL, "");
setlocale(LC_ALL, "C");
long double result = strtold(nptr, EndPtr);
setlocale(LC_ALL, lastLocale.c_str());
return result;
}
static double strtod_l(const char *nptr, char **EndPtr, locale_t) {
std::string lastLocale = setlocale(LC_ALL, "");
setlocale(LC_ALL, "C");
double result = strtod(nptr, EndPtr);
setlocale(LC_ALL, lastLocale.c_str());
return result;
}
static float strtof_l(const char *nptr, char **EndPtr, locale_t) {
std::string lastLocale = setlocale(LC_ALL, "");
setlocale(LC_ALL, "C");
float result = strtof(nptr, EndPtr);
setlocale(LC_ALL, lastLocale.c_str());
return result;
}
#endif
// We can't return Float80, but we can receive a pointer to one, so
// switch the return type and the out parameter on strtold.
template <typename T>
static const char *_swift_stdlib_strtoX_clocale_impl(
const char * nptr, T* outResult, T huge,
T (*posixImpl)(const char *, char **, locale_t)
) {
char *EndPtr;
errno = 0;
const auto result = posixImpl(nptr, &EndPtr, getCLocale());
*outResult = result;
if (result == huge || result == -huge || result == 0.0 || result == -0.0) {
if (errno == ERANGE)
EndPtr = nullptr;
}
return EndPtr;
}
extern "C" const char *_swift_stdlib_strtold_clocale(
const char * nptr, void *outResult) {
return _swift_stdlib_strtoX_clocale_impl(
nptr, static_cast<long double*>(outResult), HUGE_VALL, strtold_l);
}
extern "C" const char *_swift_stdlib_strtod_clocale(
const char * nptr, double *outResult) {
return _swift_stdlib_strtoX_clocale_impl(
nptr, outResult, HUGE_VAL, strtod_l);
}
extern "C" const char *_swift_stdlib_strtof_clocale(
const char * nptr, float *outResult) {
return _swift_stdlib_strtoX_clocale_impl(
nptr, outResult, HUGE_VALF, strtof_l);
}
extern "C" void _swift_stdlib_flockfile_stdout() {
flockfile(stdout);
}
extern "C" void _swift_stdlib_funlockfile_stdout() {
funlockfile(stdout);
}
extern "C" int _swift_stdlib_putc_stderr(int C) {
return putc(C, stderr);
}
extern "C" size_t _swift_stdlib_getHardwareConcurrency() {
return sysconf(_SC_NPROCESSORS_ONLN);
}
<commit_msg>Rewrite strtoX_clocale_impl with stringstream<commit_after>//===--- Stubs.cpp - Swift Language ABI Runtime Stubs ---------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Misc stubs for functions which should be defined in the core standard
// library, but are difficult or impossible to write in Swift at the
// moment.
//
//===----------------------------------------------------------------------===//
#if defined(__FreeBSD__)
#define _WITH_GETLINE
#endif
#include <sys/resource.h>
#include <sys/errno.h>
#include <unistd.h>
#include <climits>
#include <cstdarg>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#if defined(__CYGWIN__)
#include <sstream>
#include <cmath>
#define fmodl(lhs, rhs) std::fmod(lhs, rhs)
#else
#include <xlocale.h>
#endif
#include <limits>
#include "llvm/ADT/StringExtras.h"
#include "swift/Runtime/Debug.h"
#include "swift/Basic/Lazy.h"
static uint64_t uint64ToStringImpl(char *Buffer, uint64_t Value,
int64_t Radix, bool Uppercase,
bool Negative) {
char *P = Buffer;
uint64_t Y = Value;
if (Y == 0) {
*P++ = '0';
} else if (Radix == 10) {
while (Y) {
*P++ = '0' + char(Y % 10);
Y /= 10;
}
} else {
unsigned Radix32 = Radix;
while (Y) {
*P++ = llvm::hexdigit(Y % Radix32, !Uppercase);
Y /= Radix32;
}
}
if (Negative)
*P++ = '-';
std::reverse(Buffer, P);
return size_t(P - Buffer);
}
extern "C" uint64_t swift_int64ToString(char *Buffer, size_t BufferLength,
int64_t Value, int64_t Radix,
bool Uppercase) {
if ((Radix >= 10 && BufferLength < 32) || (Radix < 10 && BufferLength < 65))
swift::crash("swift_int64ToString: insufficient buffer size");
if (Radix == 0 || Radix > 36)
swift::crash("swift_int64ToString: invalid radix for string conversion");
bool Negative = Value < 0;
// Compute an absolute value safely, without using unary negation on INT_MIN,
// which is undefined behavior.
uint64_t UnsignedValue = Value;
if (Negative) {
// Assumes two's complement representation.
UnsignedValue = ~UnsignedValue + 1;
}
return uint64ToStringImpl(Buffer, UnsignedValue, Radix, Uppercase,
Negative);
}
extern "C" uint64_t swift_uint64ToString(char *Buffer, intptr_t BufferLength,
uint64_t Value, int64_t Radix,
bool Uppercase) {
if ((Radix >= 10 && BufferLength < 32) || (Radix < 10 && BufferLength < 64))
swift::crash("swift_int64ToString: insufficient buffer size");
if (Radix == 0 || Radix > 36)
swift::crash("swift_int64ToString: invalid radix for string conversion");
return uint64ToStringImpl(Buffer, Value, Radix, Uppercase,
/*Negative=*/false);
}
#if defined(__APPLE__) || defined(__FreeBSD__)
static inline locale_t getCLocale() {
// On these platforms convenience functions from xlocale.h interpret nullptr
// as C locale.
return nullptr;
}
#elif defined(__CYGWIN__)
// In Cygwin, getCLocale() is not used.
#else
static locale_t makeCLocale() {
locale_t CLocale = newlocale(LC_ALL_MASK, "C", nullptr);
if (!CLocale) {
swift::crash("makeCLocale: newlocale() returned a null pointer");
}
return CLocale;
}
static locale_t getCLocale() {
return SWIFT_LAZY_CONSTANT(makeCLocale());
}
#endif
#if defined(__APPLE__)
#define swift_snprintf_l snprintf_l
#elif defined(__CYGWIN__)
// In Cygwin, swift_snprintf_l() is not used.
#else
static int swift_snprintf_l(char *Str, size_t StrSize, locale_t Locale,
const char *Format, ...) {
if (Locale == nullptr) {
Locale = getCLocale();
}
locale_t OldLocale = uselocale(Locale);
va_list Args;
va_start(Args, Format);
int Result = std::vsnprintf(Str, StrSize, Format, Args);
va_end(Args);
uselocale(OldLocale);
return Result;
}
#endif
template <typename T>
static uint64_t swift_floatingPointToString(char *Buffer, size_t BufferLength,
T Value, const char *Format,
bool Debug) {
if (BufferLength < 32)
swift::crash("swift_floatingPointToString: insufficient buffer size");
int Precision = std::numeric_limits<T>::digits10;
if (Debug) {
Precision = std::numeric_limits<T>::max_digits10;
}
#if defined(__CYGWIN__)
// Cygwin does not support uselocale(), but we can use the locale feature
// in stringstream object.
std::ostringstream ValueStream;
ValueStream.width(0);
ValueStream.precision(Precision);
ValueStream.imbue(std::locale::classic());
ValueStream << Value;
std::string ValueString(ValueStream.str());
size_t i = ValueString.length();
if (i < BufferLength) {
std::copy(ValueString.begin(), ValueString.end(), Buffer);
Buffer[i] = '\0';
} else {
swift::crash("swift_floatingPointToString: insufficient buffer size");
}
#else
// Pass a null locale to use the C locale.
int i = swift_snprintf_l(Buffer, BufferLength, /*locale=*/nullptr, Format,
Precision, Value);
if (i < 0)
swift::crash(
"swift_floatingPointToString: unexpected return value from sprintf");
if (size_t(i) >= BufferLength)
swift::crash("swift_floatingPointToString: insufficient buffer size");
#endif
// Add ".0" to a float that (a) is not in scientific notation, (b) does not
// already have a fractional part, (c) is not infinite, and (d) is not a NaN
// value.
if (strchr(Buffer, 'e') == nullptr && strchr(Buffer, '.') == nullptr &&
strchr(Buffer, 'n') == nullptr) {
Buffer[i++] = '.';
Buffer[i++] = '0';
}
return i;
}
extern "C" uint64_t swift_float32ToString(char *Buffer, size_t BufferLength,
float Value, bool Debug) {
return swift_floatingPointToString<float>(Buffer, BufferLength, Value,
"%0.*g", Debug);
}
extern "C" uint64_t swift_float64ToString(char *Buffer, size_t BufferLength,
double Value, bool Debug) {
return swift_floatingPointToString<double>(Buffer, BufferLength, Value,
"%0.*g", Debug);
}
extern "C" uint64_t swift_float80ToString(char *Buffer, size_t BufferLength,
long double Value, bool Debug) {
return swift_floatingPointToString<long double>(Buffer, BufferLength, Value,
"%0.*Lg", Debug);
}
/// \param[out] LinePtr Replaced with the pointer to the malloc()-allocated
/// line. Can be NULL if no characters were read.
///
/// \returns Size of character data returned in \c LinePtr, or -1
/// if an error occurred, or EOF was reached.
extern "C" ssize_t swift_stdlib_readLine_stdin(char **LinePtr) {
size_t Capacity = 0;
return getline(LinePtr, &Capacity, stdin);
}
extern "C" float _swift_fmodf(float lhs, float rhs) {
return fmodf(lhs, rhs);
}
extern "C" double _swift_fmod(double lhs, double rhs) {
return fmod(lhs, rhs);
}
extern "C" long double _swift_fmodl(long double lhs, long double rhs) {
return fmodl(lhs, rhs);
}
// Although this builtin is provided by clang rt builtins,
// it isn't provided by libgcc, which is the default
// runtime library on Linux, even when compiling with clang.
// This implementation is copied here to avoid a new dependency
// on compiler-rt on Linux.
// FIXME: rdar://14883575 Libcompiler_rt omits muloti4
#if (defined(__APPLE__) && defined(__arm64__)) || \
(defined(__linux__) && defined(__x86_64__)) || \
(defined(__linux__) && defined(__aarch64__)) || \
(defined(__linux__) && defined(__powerpc64__))
typedef int ti_int __attribute__ ((mode (TI)));
extern "C"
ti_int
__muloti4(ti_int a, ti_int b, int* overflow)
{
const int N = (int)(sizeof(ti_int) * CHAR_BIT);
const ti_int MIN = (ti_int)1 << (N-1);
const ti_int MAX = ~MIN;
*overflow = 0;
ti_int result = a * b;
if (a == MIN)
{
if (b != 0 && b != 1)
*overflow = 1;
return result;
}
if (b == MIN)
{
if (a != 0 && a != 1)
*overflow = 1;
return result;
}
ti_int sa = a >> (N - 1);
ti_int abs_a = (a ^ sa) - sa;
ti_int sb = b >> (N - 1);
ti_int abs_b = (b ^ sb) - sb;
if (abs_a < 2 || abs_b < 2)
return result;
if (sa == sb)
{
if (abs_a > MAX / abs_b)
*overflow = 1;
}
else
{
if (abs_a > MIN / -abs_b)
*overflow = 1;
}
return result;
}
#endif
#if defined(__linux__) && defined(__arm__)
// Similar to above, but with mulodi4. Perhaps this is
// something that shouldn't be done, and is a bandaid over
// some other lower-level architecture issue that I'm
// missing. Perhaps relevant bug report:
// FIXME: https://llvm.org/bugs/show_bug.cgi?id=14469
typedef int di_int __attribute__ ((mode (DI)));
extern "C"
di_int
__mulodi4(di_int a, di_int b, int* overflow)
{
const int N = (int)(sizeof(di_int) * CHAR_BIT);
const di_int MIN = (di_int)1 << (N-1);
const di_int MAX = ~MIN;
*overflow = 0;
di_int result = a * b;
if (a == MIN)
{
if (b != 0 && b != 1)
*overflow = 1;
return result;
}
if (b == MIN)
{
if (a != 0 && a != 1)
*overflow = 1;
return result;
}
di_int sa = a >> (N - 1);
di_int abs_a = (a ^ sa) - sa;
di_int sb = b >> (N - 1);
di_int abs_b = (b ^ sb) - sb;
if (abs_a < 2 || abs_b < 2)
return result;
if (sa == sb)
{
if (abs_a > MAX / abs_b)
*overflow = 1;
}
else
{
if (abs_a > MIN / -abs_b)
*overflow = 1;
}
return result;
}
#endif
#if defined(__CYGWIN__)
// Cygwin does not support uselocale(), but we can use the locale feature
// in stringstream object.
template <typename T>
static const char *_swift_stdlib_strtoX_clocale_impl(
const char *nptr, T *outResult) {
std::istringstream ValueStream(nptr);
ValueStream.imbue(std::locale::classic());
T ParsedValue;
ValueStream >> ParsedValue;
*outResult = ParsedValue;
int pos = ValueStream.tellg();
if (pos <= 0)
return nullptr;
return nptr + pos;
}
extern "C" const char *_swift_stdlib_strtold_clocale(
const char *nptr, void *outResult) {
return _swift_stdlib_strtoX_clocale_impl(
nptr, static_cast<long double*>(outResult));
}
extern "C" const char *_swift_stdlib_strtod_clocale(
const char * nptr, double *outResult) {
return _swift_stdlib_strtoX_clocale_impl(nptr, outResult);
}
extern "C" const char *_swift_stdlib_strtof_clocale(
const char * nptr, float *outResult) {
return _swift_stdlib_strtoX_clocale_impl(nptr, outResult);
}
#else
// We can't return Float80, but we can receive a pointer to one, so
// switch the return type and the out parameter on strtold.
template <typename T>
static const char *_swift_stdlib_strtoX_clocale_impl(
const char * nptr, T* outResult, T huge,
T (*posixImpl)(const char *, char **, locale_t)
) {
char *EndPtr;
errno = 0;
const auto result = posixImpl(nptr, &EndPtr, getCLocale());
*outResult = result;
if (result == huge || result == -huge || result == 0.0 || result == -0.0) {
if (errno == ERANGE)
EndPtr = nullptr;
}
return EndPtr;
}
extern "C" const char *_swift_stdlib_strtold_clocale(
const char * nptr, void *outResult) {
return _swift_stdlib_strtoX_clocale_impl(
nptr, static_cast<long double*>(outResult), HUGE_VALL, strtold_l);
}
extern "C" const char *_swift_stdlib_strtod_clocale(
const char * nptr, double *outResult) {
return _swift_stdlib_strtoX_clocale_impl(
nptr, outResult, HUGE_VAL, strtod_l);
}
extern "C" const char *_swift_stdlib_strtof_clocale(
const char * nptr, float *outResult) {
return _swift_stdlib_strtoX_clocale_impl(
nptr, outResult, HUGE_VALF, strtof_l);
}
#endif
extern "C" void _swift_stdlib_flockfile_stdout() {
flockfile(stdout);
}
extern "C" void _swift_stdlib_funlockfile_stdout() {
funlockfile(stdout);
}
extern "C" int _swift_stdlib_putc_stderr(int C) {
return putc(C, stderr);
}
extern "C" size_t _swift_stdlib_getHardwareConcurrency() {
return sysconf(_SC_NPROCESSORS_ONLN);
}
<|endoftext|>
|
<commit_before>/////////////////////////////////////////////////////////////////////////
// $Id: ioapic.cc,v 1.8 2002/08/27 19:54:46 bdenney Exp $
/////////////////////////////////////////////////////////////////////////
//
#include <stdio.h>
#include "bochs.h"
class bx_ioapic_c bx_ioapic;
#define LOG_THIS bx_ioapic.
void
bx_io_redirect_entry_t::parse_value ()
{
dest = (value >> 56) & 0xff;
masked = (value >> 16) & 1;
trig_mode = (value >> 15) & 1;
remote_irr = (value >> 14) & 1;
polarity = (value >> 13) & 1;
//delivery_status = (value >> 12) & 1;
delivery_status = 0; // always say the message has gone through
dest_mode = (value >> 11) & 1;
delivery_mode = (value >> 8) & 7;
vector = (value >> 0) & 0xff;
}
void
bx_io_redirect_entry_t::sprintf_self (char *buf)
{
sprintf (buf, "dest=%02x, masked=%d, trig_mode=%d, remote_irr=%d, polarity=%d, delivery_status=%d, dest_mode=%d, delivery_mode=%d, vector=%02x", dest, masked, trig_mode, remote_irr, polarity, delivery_status, dest_mode, delivery_mode, vector);
}
bx_ioapic_c::bx_ioapic_c ()
: bx_generic_apic_c ()
{
put("IOAP");
settype(IOAPICLOG);
}
bx_ioapic_c::~bx_ioapic_c () {
}
void
bx_ioapic_c::init ()
{
bx_generic_apic_c::init ();
BX_DEBUG(("initializing I/O APIC"));
base_addr = 0xfec00000;
ioregsel = 0;
// all interrupts masked
for (int i=0; i<BX_IOAPIC_NUM_PINS; i++) {
ioredtbl[i].set_even_word (0x00010000);
ioredtbl[i].set_odd_word (0x00000000);
}
irr = 0;
}
void
bx_ioapic_c::reset ()
{
}
void
bx_ioapic_c::read_aligned(Bit32u address, Bit32u *data, unsigned len)
{
BX_DEBUG( ("I/O APIC read_aligned addr=%08x, len=%d", address, len));
BX_ASSERT (len == 4);
address &= 0xff;
if (address == 0x00) {
// select register
*data = ioregsel;
return;
} else if (address != 0x10) {
BX_PANIC(("IOAPIC: read from unsupported address"));
}
// only reached when reading data register
switch (ioregsel) {
case 0x00: // APIC ID
*data = ((id & 0xf) << 24);
return;
case 0x01: // version
*data = (((BX_IOAPIC_NUM_PINS-1) & 0xff) << 16)
| (BX_IOAPIC_VERSION_ID & 0x0f);
return;
case 0x02:
BX_INFO(("IOAPIC: arbitration ID unsupported, returned 0"));
*data = 0;
return;
default:
int index = (ioregsel - 0x10) >> 1;
if (index >= 0 && index < BX_IOAPIC_NUM_PINS) {
bx_io_redirect_entry_t *entry = ioredtbl + index;
*data = (ioregsel&1) ? entry->get_odd_word() : entry->get_even_word ();
return;
}
BX_PANIC(("IOAPIC: IOREGSEL points to undefined register %02x", ioregsel));
}
}
void
bx_ioapic_c::write(Bit32u address, Bit32u *value, unsigned len)
{
BX_DEBUG(("IOAPIC: write addr=%08x, data=%08x, len=%d", address, *value, len));
address &= 0xff;
if (address == 0x00) {
ioregsel = *value;
return;
} else if (address != 0x10) {
BX_PANIC(("IOAPIC: write to unsupported address"));
}
// only reached when writing data register
switch (ioregsel) {
case 0x00: // set APIC ID
{
Bit8u newid = (*value >> 24) & 0xf;
BX_INFO(("IOAPIC: setting id to 0x%x", newid));
set_id (newid);
return;
}
case 0x01: // version
case 0x02: // arbitration id
BX_INFO(("IOAPIC: could not write, IOREGSEL=0x%02x", ioregsel));
return;
default:
int index = (ioregsel - 0x10) >> 1;
if (index >= 0 && index < BX_IOAPIC_NUM_PINS) {
bx_io_redirect_entry_t *entry = ioredtbl + index;
if (ioregsel&1)
entry->set_odd_word (*value);
else
entry->set_even_word (*value);
char buf[1024];
entry->sprintf_self (buf);
BX_DEBUG(("IOAPIC: now entry[%d] is %s", index, buf));
service_ioapic ();
return;
}
BX_PANIC(("IOAPIC: IOREGSEL points to undefined register %02x", ioregsel));
}
}
void bx_ioapic_c::trigger_irq (unsigned vector, unsigned from)
{
BX_DEBUG(("IOAPIC: received interrupt %d", vector));
if (vector >= 0 && vector < BX_IOAPIC_NUM_PINS) {
Bit32u bit = 1<<vector;
if ((irr & bit) == 0) {
irr |= bit;
service_ioapic ();
}
} else BX_PANIC(("IOAPIC: vector %d out of range", vector));
}
void bx_ioapic_c::untrigger_irq (unsigned num, unsigned from)
{
BX_DEBUG(("IOAPIC: interrupt %d went away", num));
}
void bx_ioapic_c::service_ioapic ()
{
// look in IRR and deliver any interrupts that are not masked.
BX_DEBUG(("IOAPIC: servicing"));
for (unsigned bit=0; bit < BX_IOAPIC_NUM_PINS; bit++) {
if (irr & (1<<bit)) {
bx_io_redirect_entry_t *entry = ioredtbl + bit;
if (!entry->masked) {
// clear irr bit and deliver
Boolean done = deliver (entry->dest, entry->dest_mode, entry->delivery_mode, entry->vector, entry->polarity, entry->trig_mode);
if (done) irr &= ~(1<<bit);
}
}
}
}
<commit_msg>- reset should have one arg, unsigned int type<commit_after>/////////////////////////////////////////////////////////////////////////
// $Id: ioapic.cc,v 1.9 2002/08/29 16:52:47 bdenney Exp $
/////////////////////////////////////////////////////////////////////////
//
#include <stdio.h>
#include "bochs.h"
class bx_ioapic_c bx_ioapic;
#define LOG_THIS bx_ioapic.
void
bx_io_redirect_entry_t::parse_value ()
{
dest = (value >> 56) & 0xff;
masked = (value >> 16) & 1;
trig_mode = (value >> 15) & 1;
remote_irr = (value >> 14) & 1;
polarity = (value >> 13) & 1;
//delivery_status = (value >> 12) & 1;
delivery_status = 0; // always say the message has gone through
dest_mode = (value >> 11) & 1;
delivery_mode = (value >> 8) & 7;
vector = (value >> 0) & 0xff;
}
void
bx_io_redirect_entry_t::sprintf_self (char *buf)
{
sprintf (buf, "dest=%02x, masked=%d, trig_mode=%d, remote_irr=%d, polarity=%d, delivery_status=%d, dest_mode=%d, delivery_mode=%d, vector=%02x", dest, masked, trig_mode, remote_irr, polarity, delivery_status, dest_mode, delivery_mode, vector);
}
bx_ioapic_c::bx_ioapic_c ()
: bx_generic_apic_c ()
{
put("IOAP");
settype(IOAPICLOG);
}
bx_ioapic_c::~bx_ioapic_c () {
}
void
bx_ioapic_c::init ()
{
bx_generic_apic_c::init ();
BX_DEBUG(("initializing I/O APIC"));
base_addr = 0xfec00000;
ioregsel = 0;
// all interrupts masked
for (int i=0; i<BX_IOAPIC_NUM_PINS; i++) {
ioredtbl[i].set_even_word (0x00010000);
ioredtbl[i].set_odd_word (0x00000000);
}
irr = 0;
}
void
bx_ioapic_c::reset (unsigned type)
{
}
void
bx_ioapic_c::read_aligned(Bit32u address, Bit32u *data, unsigned len)
{
BX_DEBUG( ("I/O APIC read_aligned addr=%08x, len=%d", address, len));
BX_ASSERT (len == 4);
address &= 0xff;
if (address == 0x00) {
// select register
*data = ioregsel;
return;
} else if (address != 0x10) {
BX_PANIC(("IOAPIC: read from unsupported address"));
}
// only reached when reading data register
switch (ioregsel) {
case 0x00: // APIC ID
*data = ((id & 0xf) << 24);
return;
case 0x01: // version
*data = (((BX_IOAPIC_NUM_PINS-1) & 0xff) << 16)
| (BX_IOAPIC_VERSION_ID & 0x0f);
return;
case 0x02:
BX_INFO(("IOAPIC: arbitration ID unsupported, returned 0"));
*data = 0;
return;
default:
int index = (ioregsel - 0x10) >> 1;
if (index >= 0 && index < BX_IOAPIC_NUM_PINS) {
bx_io_redirect_entry_t *entry = ioredtbl + index;
*data = (ioregsel&1) ? entry->get_odd_word() : entry->get_even_word ();
return;
}
BX_PANIC(("IOAPIC: IOREGSEL points to undefined register %02x", ioregsel));
}
}
void
bx_ioapic_c::write(Bit32u address, Bit32u *value, unsigned len)
{
BX_DEBUG(("IOAPIC: write addr=%08x, data=%08x, len=%d", address, *value, len));
address &= 0xff;
if (address == 0x00) {
ioregsel = *value;
return;
} else if (address != 0x10) {
BX_PANIC(("IOAPIC: write to unsupported address"));
}
// only reached when writing data register
switch (ioregsel) {
case 0x00: // set APIC ID
{
Bit8u newid = (*value >> 24) & 0xf;
BX_INFO(("IOAPIC: setting id to 0x%x", newid));
set_id (newid);
return;
}
case 0x01: // version
case 0x02: // arbitration id
BX_INFO(("IOAPIC: could not write, IOREGSEL=0x%02x", ioregsel));
return;
default:
int index = (ioregsel - 0x10) >> 1;
if (index >= 0 && index < BX_IOAPIC_NUM_PINS) {
bx_io_redirect_entry_t *entry = ioredtbl + index;
if (ioregsel&1)
entry->set_odd_word (*value);
else
entry->set_even_word (*value);
char buf[1024];
entry->sprintf_self (buf);
BX_DEBUG(("IOAPIC: now entry[%d] is %s", index, buf));
service_ioapic ();
return;
}
BX_PANIC(("IOAPIC: IOREGSEL points to undefined register %02x", ioregsel));
}
}
void bx_ioapic_c::trigger_irq (unsigned vector, unsigned from)
{
BX_DEBUG(("IOAPIC: received interrupt %d", vector));
if (vector >= 0 && vector < BX_IOAPIC_NUM_PINS) {
Bit32u bit = 1<<vector;
if ((irr & bit) == 0) {
irr |= bit;
service_ioapic ();
}
} else BX_PANIC(("IOAPIC: vector %d out of range", vector));
}
void bx_ioapic_c::untrigger_irq (unsigned num, unsigned from)
{
BX_DEBUG(("IOAPIC: interrupt %d went away", num));
}
void bx_ioapic_c::service_ioapic ()
{
// look in IRR and deliver any interrupts that are not masked.
BX_DEBUG(("IOAPIC: servicing"));
for (unsigned bit=0; bit < BX_IOAPIC_NUM_PINS; bit++) {
if (irr & (1<<bit)) {
bx_io_redirect_entry_t *entry = ioredtbl + bit;
if (!entry->masked) {
// clear irr bit and deliver
Boolean done = deliver (entry->dest, entry->dest_mode, entry->delivery_mode, entry->vector, entry->polarity, entry->trig_mode);
if (done) irr &= ~(1<<bit);
}
}
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2019-2020 Fastly, Inc., Toru Maesaka, Goro Fuji
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include <vector>
#include "h2olog.h"
using namespace std;
#define VERSION "0.1.0"
#define POLL_TIMEOUT (-1)
static void usage(void)
{
printf("h2olog (%s)\n", VERSION);
printf("-p PID of the H2O server\n");
printf("-h Print this help and exit\n");
return;
}
static void show_event_per_sec(h2o_tracer_t *tracer, time_t t0)
{
time_t t1 = time(NULL);
int64_t d = t1 - t0;
if (d > 10) {
uint64_t c = tracer->count / d;
if (c > 0) {
struct tm t;
localtime_r(&t1, &t);
char s[100];
strftime(s, sizeof(s), "%Y-%m-%d %H:%M:%S%z", &t);
fprintf(stderr, "%s %20lu events/s\n", s, c);
t0 = t1;
tracer->count = 0;
}
}
}
int main(int argc, char **argv)
{
h2o_tracer_t *tracer;
if (argc > 1 && strcmp(argv[1], "quic") == 0) {
tracer = create_quic_tracer();
--argc;
++argv;
} else {
tracer = create_http_tracer();
}
bool debug = false;
const char *out_file = nullptr;
int c;
pid_t h2o_pid = -1;
while ((c = getopt(argc, argv, "hvp:t:s:dP:o:")) != -1) {
switch (c) {
case 'p':
h2o_pid = atoi(optarg);
break;
case 'o':
out_file = optarg;
break;
case 'd':
debug = true;
break;
case 'h':
usage();
exit(EXIT_SUCCESS);
}
}
if (h2o_pid == -1) {
fprintf(stderr, "Error: -p option is missing\n");
exit(EXIT_FAILURE);
}
if (geteuid() != 0) {
fprintf(stderr, "Error: root privilege is required\n");
exit(EXIT_FAILURE);
}
if (out_file != nullptr) {
FILE *out = fopen(out_file, "w");
if (out == nullptr) {
fprintf(stderr, "Error: failed to open %s: %s", out_file, strerror(errno));
exit(EXIT_FAILURE);
}
tracer->out = out;
} else {
tracer->out = stdout;
}
ebpf::BPF *bpf = new ebpf::BPF();
std::vector<ebpf::USDT> probes = tracer->init_usdt_probes(h2o_pid);
ebpf::StatusTuple ret = bpf->init(tracer->bpf_text(), {}, probes);
if (ret.code() != 0) {
fprintf(stderr, "init: %s\n", ret.msg().c_str());
return EXIT_FAILURE;
}
for (auto &probe : probes) {
ret = bpf->attach_usdt(probe);
if (ret.code() != 0) {
fprintf(stderr, "attach_usdt: %s\n", ret.msg().c_str());
return EXIT_FAILURE;
}
}
ret = bpf->open_perf_buffer("events", tracer->handle_event, nullptr, &tracer, 64);
if (ret.code() != 0) {
fprintf(stderr, "open_perf_buffer: %s\n", ret.msg().c_str());
return EXIT_FAILURE;
}
if (debug) {
fprintf(stderr, "attaching pid=%d\n", h2o_pid);
}
ebpf::BPFPerfBuffer *perf_buffer = bpf->get_perf_buffer("events");
if (perf_buffer) {
time_t t0 = time(NULL);
while (true) {
perf_buffer->poll(POLL_TIMEOUT);
fflush(tracer->out);
if (debug) {
show_event_per_sec(tracer, t0);
t0 = time(NULL);
}
}
}
fprintf(stderr, "Error: failed to get_perf_buffer()\n");
return EXIT_FAILURE;
}
<commit_msg>fix use of context ptr<commit_after>/*
* Copyright (c) 2019-2020 Fastly, Inc., Toru Maesaka, Goro Fuji
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include <vector>
#include "h2olog.h"
using namespace std;
#define VERSION "0.1.0"
#define POLL_TIMEOUT (-1)
static void usage(void)
{
printf("h2olog (%s)\n", VERSION);
printf("-p PID of the H2O server\n");
printf("-h Print this help and exit\n");
return;
}
static void show_event_per_sec(h2o_tracer_t *tracer, time_t t0)
{
time_t t1 = time(NULL);
int64_t d = t1 - t0;
if (d > 10) {
uint64_t c = tracer->count / d;
if (c > 0) {
struct tm t;
localtime_r(&t1, &t);
char s[100];
strftime(s, sizeof(s), "%Y-%m-%d %H:%M:%S%z", &t);
fprintf(stderr, "%s %20lu events/s\n", s, c);
t0 = t1;
tracer->count = 0;
}
}
}
int main(int argc, char **argv)
{
h2o_tracer_t *tracer;
if (argc > 1 && strcmp(argv[1], "quic") == 0) {
tracer = create_quic_tracer();
--argc;
++argv;
} else {
tracer = create_http_tracer();
}
bool debug = false;
const char *out_file = nullptr;
int c;
pid_t h2o_pid = -1;
while ((c = getopt(argc, argv, "hvp:t:s:dP:o:")) != -1) {
switch (c) {
case 'p':
h2o_pid = atoi(optarg);
break;
case 'o':
out_file = optarg;
break;
case 'd':
debug = true;
break;
case 'h':
usage();
exit(EXIT_SUCCESS);
}
}
if (h2o_pid == -1) {
fprintf(stderr, "Error: -p option is missing\n");
exit(EXIT_FAILURE);
}
if (geteuid() != 0) {
fprintf(stderr, "Error: root privilege is required\n");
exit(EXIT_FAILURE);
}
if (out_file != nullptr) {
FILE *out = fopen(out_file, "w");
if (out == nullptr) {
fprintf(stderr, "Error: failed to open %s: %s", out_file, strerror(errno));
exit(EXIT_FAILURE);
}
tracer->out = out;
} else {
tracer->out = stdout;
}
ebpf::BPF *bpf = new ebpf::BPF();
std::vector<ebpf::USDT> probes = tracer->init_usdt_probes(h2o_pid);
ebpf::StatusTuple ret = bpf->init(tracer->bpf_text(), {}, probes);
if (ret.code() != 0) {
fprintf(stderr, "init: %s\n", ret.msg().c_str());
return EXIT_FAILURE;
}
for (auto &probe : probes) {
ret = bpf->attach_usdt(probe);
if (ret.code() != 0) {
fprintf(stderr, "attach_usdt: %s\n", ret.msg().c_str());
return EXIT_FAILURE;
}
}
ret = bpf->open_perf_buffer("events", tracer->handle_event, nullptr, tracer, 64);
if (ret.code() != 0) {
fprintf(stderr, "open_perf_buffer: %s\n", ret.msg().c_str());
return EXIT_FAILURE;
}
if (debug) {
fprintf(stderr, "attaching pid=%d\n", h2o_pid);
}
ebpf::BPFPerfBuffer *perf_buffer = bpf->get_perf_buffer("events");
if (perf_buffer) {
time_t t0 = time(NULL);
while (true) {
perf_buffer->poll(POLL_TIMEOUT);
fflush(tracer->out);
if (debug) {
show_event_per_sec(tracer, t0);
t0 = time(NULL);
}
}
}
fprintf(stderr, "Error: failed to get_perf_buffer()\n");
return EXIT_FAILURE;
}
<|endoftext|>
|
<commit_before><commit_msg>Hooks<commit_after><|endoftext|>
|
<commit_before>#include "walk.hpp"
namespace vg {
namespace algorithms {
void for_each_walk(const HandleGraph& graph, size_t k, size_t edge_max,
const std::function<void(const walk_t&)>& lambda) {
graph.for_each_handle([&](const handle_t& h) {
// for the forward and reverse of this handle
// walk k bases from the end, so that any walk starting on the node will be represented in the tree we build
for (auto handle_is_rev : { false, true }) {
handle_t handle = handle_is_rev ? graph.flip(h) : h;
std::list<walk_t> walks;
// for each position in the node, set up a walk with that start position and the node end or walk length as the end position
// determine next positions
nid_t handle_id = graph.get_id(handle);
size_t handle_length = graph.get_length(handle);
std::string handle_seq = graph.get_sequence(handle);
for (size_t i = 0; i < handle_length; ++i) {
pos_t begin = make_pos_t(handle_id, handle_is_rev, i);
pos_t end = make_pos_t(handle_id, handle_is_rev, std::min(handle_length, i+k));
walk_t walk = walk_t(handle_seq.substr(offset(begin), offset(end)-offset(begin)), begin, end, handle);
if (walk.seq.size() < k) {
size_t next_count = 0;
if (edge_max) graph.follow_edges(walk.curr, false, [&](const handle_t& next) { ++next_count; return next_count <= 1; });
//walk.seq.reserve(k); // may reduce allocation costs
// follow edges if we haven't completed the walk here
if (next_count > 1 && (edge_max && edge_max == walk.forks)) {
} else {
graph.follow_edges(walk.curr, false, [&](const handle_t& next) {
walks.push_back(walk);
auto& todo = walks.back();
todo.curr = next;
if (next_count > 1) {
++todo.forks;
}
});
}
} else {
walks.push_back(walk);
}
}
// now expand the walks until they reach k
while (!walks.empty()) {
// first we check which ones have reached length k in the current handle; for each of these we run lambda and remove them from our list
auto walks_end = walks.end();
for (std::list<walk_t>::iterator q = walks.begin(); q != walks_end; ++q) {
auto& walk = *q;
// did we reach our target length?
if (walk.seq.size() == k) {
// TODO here check if we are at the beginning of the reverse head or the beginning of the forward tail and would need special handling
// establish the context
handle_t end_handle = graph.get_handle(id(walk.end), is_rev(walk.end));
size_t end_length = graph.get_length(end_handle);
// now pass the walk to our callback
lambda(walk);
q = walks.erase(q);
} else {
// do we finish in the current node?
nid_t curr_id = graph.get_id(walk.curr);
size_t curr_length = graph.get_length(walk.curr);
bool curr_is_rev = graph.get_is_reverse(walk.curr);
std::string curr_seq = graph.get_sequence(walk.curr);
size_t take = std::min(curr_length, k-walk.seq.size());
walk.end = make_pos_t(curr_id, curr_is_rev, take);
walk.seq.append(curr_seq.substr(0,take));
walk.path.push_back(walk.curr);
if (walk.seq.size() < k) {
size_t next_count = 0;
if (edge_max) graph.follow_edges(walk.curr, false, [&](const handle_t& next) { ++next_count; return next_count <= 1; });
//walk.seq.reserve(k); // may reduce allocation costs
// follow edges if we haven't completed the walk here
if (next_count > 1 && (edge_max && edge_max == walk.forks)) {
} else {
graph.follow_edges(walk.curr, false, [&](const handle_t& next) {
walks.push_back(walk);
auto& todo = walks.back();
todo.curr = next;
if (next_count > 1) {
++todo.forks;
}
});
}
// if not, we need to expand through the node then follow on
/*
graph.follow_edges(walk.curr, false, [&](const handle_t& next) {
walks.push_back(walk);
auto& todo = walks.back();
todo.curr = next;
});
*/
q = walks.erase(q);
} else {
if (walk.seq.size() > k) {
assert(walk.seq.size() <= k);
}
}
}
}
}
}
}, true);
}
std::ostream& operator<<(std::ostream& out, const walk_t& walk) {
out << walk.seq << "\t"
<< id(walk.begin) << ":" << (is_rev(walk.begin) ? "-":"") << offset(walk.begin) << "\t";
return out;
}
uint64_t walk_haplotype_frequency(const HandleGraph& graph,
const gbwt::GBWT& haplotypes,
const walk_t& walk) {
if (walk.path.empty()) {
return 0;
}
auto& first_step = walk.path.front();
gbwt::node_type start_node = gbwt::Node::encode(graph.get_id(first_step), graph.get_is_reverse(first_step));
gbwt::SearchState search_state = haplotypes.find(start_node);
for (uint64_t i = 1; i < walk.path.size(); ++i) {
auto& next = walk.path[i];
gbwt::node_type next_node = gbwt::Node::encode(graph.get_id(next), graph.get_is_reverse(next));
search_state = haplotypes.extend(search_state, next_node);
if (search_state.empty()) {
break;
}
}
return search_state.size();
}
std::vector<std::string> walk_haplotype_names(const HandleGraph& graph,
const gbwt::GBWT& haplotypes,
const walk_t& walk) {
std::vector<std::string> names;
if (walk.path.empty()) {
return names;
}
auto& first_step = walk.path.front();
gbwt::node_type start_node = gbwt::Node::encode(graph.get_id(first_step), graph.get_is_reverse(first_step));
gbwt::SearchState search_state = haplotypes.find(start_node);
for (uint64_t i = 1; i < walk.path.size(); ++i) {
auto& next = walk.path[i];
gbwt::node_type next_node = gbwt::Node::encode(graph.get_id(next), graph.get_is_reverse(next));
search_state = haplotypes.extend(search_state, next_node);
if (search_state.empty()) {
break;
}
}
assert(haplotypes.hasMetadata() && haplotypes.metadata.hasSampleNames());
for (auto& thread : haplotypes.locate(search_state)) {
// not clear why we have to do this, but it's necessary
// perhaps due to fwd/reverse threads
auto id = (thread-1)/2; // convert thread id returned by locat to gbwt metadata compatible one
std::stringstream ss;
ss << thread_sample(haplotypes, id) << "#" << thread_phase(haplotypes, id);
names.push_back(ss.str());
}
return names;
}
}
}
<commit_msg>correct conversion of thread to path id<commit_after>#include "walk.hpp"
namespace vg {
namespace algorithms {
void for_each_walk(const HandleGraph& graph, size_t k, size_t edge_max,
const std::function<void(const walk_t&)>& lambda) {
graph.for_each_handle([&](const handle_t& h) {
// for the forward and reverse of this handle
// walk k bases from the end, so that any walk starting on the node will be represented in the tree we build
for (auto handle_is_rev : { false, true }) {
handle_t handle = handle_is_rev ? graph.flip(h) : h;
std::list<walk_t> walks;
// for each position in the node, set up a walk with that start position and the node end or walk length as the end position
// determine next positions
nid_t handle_id = graph.get_id(handle);
size_t handle_length = graph.get_length(handle);
std::string handle_seq = graph.get_sequence(handle);
for (size_t i = 0; i < handle_length; ++i) {
pos_t begin = make_pos_t(handle_id, handle_is_rev, i);
pos_t end = make_pos_t(handle_id, handle_is_rev, std::min(handle_length, i+k));
walk_t walk = walk_t(handle_seq.substr(offset(begin), offset(end)-offset(begin)), begin, end, handle);
if (walk.seq.size() < k) {
size_t next_count = 0;
if (edge_max) graph.follow_edges(walk.curr, false, [&](const handle_t& next) { ++next_count; return next_count <= 1; });
//walk.seq.reserve(k); // may reduce allocation costs
// follow edges if we haven't completed the walk here
if (next_count > 1 && (edge_max && edge_max == walk.forks)) {
} else {
graph.follow_edges(walk.curr, false, [&](const handle_t& next) {
walks.push_back(walk);
auto& todo = walks.back();
todo.curr = next;
if (next_count > 1) {
++todo.forks;
}
});
}
} else {
walks.push_back(walk);
}
}
// now expand the walks until they reach k
while (!walks.empty()) {
// first we check which ones have reached length k in the current handle; for each of these we run lambda and remove them from our list
auto walks_end = walks.end();
for (std::list<walk_t>::iterator q = walks.begin(); q != walks_end; ++q) {
auto& walk = *q;
// did we reach our target length?
if (walk.seq.size() == k) {
// TODO here check if we are at the beginning of the reverse head or the beginning of the forward tail and would need special handling
// establish the context
handle_t end_handle = graph.get_handle(id(walk.end), is_rev(walk.end));
size_t end_length = graph.get_length(end_handle);
// now pass the walk to our callback
lambda(walk);
q = walks.erase(q);
} else {
// do we finish in the current node?
nid_t curr_id = graph.get_id(walk.curr);
size_t curr_length = graph.get_length(walk.curr);
bool curr_is_rev = graph.get_is_reverse(walk.curr);
std::string curr_seq = graph.get_sequence(walk.curr);
size_t take = std::min(curr_length, k-walk.seq.size());
walk.end = make_pos_t(curr_id, curr_is_rev, take);
walk.seq.append(curr_seq.substr(0,take));
walk.path.push_back(walk.curr);
if (walk.seq.size() < k) {
size_t next_count = 0;
if (edge_max) graph.follow_edges(walk.curr, false, [&](const handle_t& next) { ++next_count; return next_count <= 1; });
//walk.seq.reserve(k); // may reduce allocation costs
// follow edges if we haven't completed the walk here
if (next_count > 1 && (edge_max && edge_max == walk.forks)) {
} else {
graph.follow_edges(walk.curr, false, [&](const handle_t& next) {
walks.push_back(walk);
auto& todo = walks.back();
todo.curr = next;
if (next_count > 1) {
++todo.forks;
}
});
}
// if not, we need to expand through the node then follow on
/*
graph.follow_edges(walk.curr, false, [&](const handle_t& next) {
walks.push_back(walk);
auto& todo = walks.back();
todo.curr = next;
});
*/
q = walks.erase(q);
} else {
if (walk.seq.size() > k) {
assert(walk.seq.size() <= k);
}
}
}
}
}
}
}, true);
}
std::ostream& operator<<(std::ostream& out, const walk_t& walk) {
out << walk.seq << "\t"
<< id(walk.begin) << ":" << (is_rev(walk.begin) ? "-":"") << offset(walk.begin) << "\t";
return out;
}
uint64_t walk_haplotype_frequency(const HandleGraph& graph,
const gbwt::GBWT& haplotypes,
const walk_t& walk) {
if (walk.path.empty()) {
return 0;
}
auto& first_step = walk.path.front();
gbwt::node_type start_node = gbwt::Node::encode(graph.get_id(first_step), graph.get_is_reverse(first_step));
gbwt::SearchState search_state = haplotypes.find(start_node);
for (uint64_t i = 1; i < walk.path.size(); ++i) {
auto& next = walk.path[i];
gbwt::node_type next_node = gbwt::Node::encode(graph.get_id(next), graph.get_is_reverse(next));
search_state = haplotypes.extend(search_state, next_node);
if (search_state.empty()) {
break;
}
}
return search_state.size();
}
std::vector<std::string> walk_haplotype_names(const HandleGraph& graph,
const gbwt::GBWT& haplotypes,
const walk_t& walk) {
std::vector<std::string> names;
if (walk.path.empty()) {
return names;
}
auto& first_step = walk.path.front();
gbwt::node_type start_node = gbwt::Node::encode(graph.get_id(first_step), graph.get_is_reverse(first_step));
gbwt::SearchState search_state = haplotypes.find(start_node);
for (uint64_t i = 1; i < walk.path.size(); ++i) {
auto& next = walk.path[i];
gbwt::node_type next_node = gbwt::Node::encode(graph.get_id(next), graph.get_is_reverse(next));
search_state = haplotypes.extend(search_state, next_node);
if (search_state.empty()) {
break;
}
}
assert(haplotypes.hasMetadata() && haplotypes.metadata.hasSampleNames());
for (auto& thread : haplotypes.locate(search_state)) {
auto id = gbwt::Path::id(thread);
std::stringstream ss;
ss << thread_sample(haplotypes, id) << "#" << thread_phase(haplotypes, id);
names.push_back(ss.str());
}
return names;
}
}
}
<|endoftext|>
|
<commit_before><commit_msg>Reading of the theme config file<commit_after><|endoftext|>
|
<commit_before>// Copyright (c) 2020 The Orbit Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "CaptureOptionsDialog.h"
#include <absl/flags/declare.h>
#include <absl/flags/flag.h>
#include <QAbstractButton>
#include <QDialog>
#include <QDialogButtonBox>
#include <QWidget>
#include <QtGui/QValidator>
#include "ClientFlags/ClientFlags.h"
#include "ui_CaptureOptionsDialog.h"
namespace orbit_qt {
using orbit_client_data::WineSyscallHandlingMethod;
using orbit_grpc_protos::CaptureOptions;
using DynamicInstrumentationMethod =
orbit_grpc_protos::CaptureOptions::DynamicInstrumentationMethod;
using UnwindingMethod = orbit_grpc_protos::CaptureOptions::UnwindingMethod;
CaptureOptionsDialog::CaptureOptionsDialog(QWidget* parent)
: QDialog{parent}, ui_(std::make_unique<Ui::CaptureOptionsDialog>()) {
ui_->setupUi(this);
QObject::connect(ui_->buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept);
QObject::connect(ui_->buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject);
QObject::connect(ui_->framePointerUnwindingRadioButton, qOverload<bool>(&QRadioButton::toggled),
ui_->maxCopyRawStackSizeWidget,
[this](bool checked) { ui_->maxCopyRawStackSizeWidget->setEnabled(checked); });
QObject::connect(ui_->dwarfUnwindingRadioButton, qOverload<bool>(&QRadioButton::toggled),
ui_->wineGroupBox,
[this](bool checked) { ui_->wineGroupBox->setEnabled(checked); });
QObject::connect(ui_->collectMemoryInfoCheckBox, qOverload<bool>(&QCheckBox::toggled), this,
[this](bool checked) {
ui_->memorySamplingPeriodMsLabel->setEnabled(checked);
ui_->memorySamplingPeriodMsLineEdit->setEnabled(checked);
ui_->memoryWarningThresholdKbLabel->setEnabled(checked);
ui_->memoryWarningThresholdKbLineEdit->setEnabled(checked);
});
QObject::connect(ui_->samplingCheckBox, qOverload<bool>(&QCheckBox::toggled), this,
[this](bool checked) {
ui_->samplingPeriodMsLabel->setEnabled(checked);
ui_->samplingPeriodMsDoubleSpinBox->setEnabled(checked);
ui_->unwindingMethodGroupBox->setEnabled(checked);
});
ui_->samplingPeriodMsLabel->setEnabled(ui_->samplingCheckBox->isChecked());
ui_->samplingPeriodMsDoubleSpinBox->setEnabled(ui_->samplingCheckBox->isChecked());
ui_->unwindingMethodGroupBox->setEnabled(ui_->samplingCheckBox->isChecked());
ui_->maxCopyRawStackSizeSpinBox->setValue(kMaxCopyRawStackSizeDefaultValue);
ui_->maxCopyRawStackSizeWidget->setEnabled(ui_->framePointerUnwindingRadioButton->isChecked());
ui_->localMarkerDepthLineEdit->setValidator(&uint64_validator_);
ui_->memorySamplingPeriodMsLabel->setEnabled(ui_->collectMemoryInfoCheckBox->isChecked());
ui_->memorySamplingPeriodMsLineEdit->setEnabled(ui_->collectMemoryInfoCheckBox->isChecked());
ui_->memoryWarningThresholdKbLabel->setEnabled(ui_->collectMemoryInfoCheckBox->isChecked());
ui_->memoryWarningThresholdKbLineEdit->setEnabled(ui_->collectMemoryInfoCheckBox->isChecked());
ui_->memorySamplingPeriodMsLineEdit->setValidator(new UInt64Validator(
1, std::numeric_limits<uint64_t>::max(), ui_->memorySamplingPeriodMsLineEdit));
ui_->memoryWarningThresholdKbLineEdit->setValidator(&uint64_validator_);
if (!absl::GetFlag(FLAGS_enable_warning_threshold)) {
ui_->memoryWarningThresholdKbLabel->hide();
ui_->memoryWarningThresholdKbLineEdit->hide();
}
if (!absl::GetFlag(FLAGS_devmode)) {
// TODO(b/198748597): Don't hide samplingCheckBox once disabling sampling completely is exposed.
ui_->samplingCheckBox->hide();
ui_->schedulerCheckBox->hide();
ui_->devModeGroupBox->hide();
ui_->wineNoneRadioButton->hide();
}
}
void CaptureOptionsDialog::SetEnableSampling(bool enable_sampling) {
ui_->samplingCheckBox->setChecked(enable_sampling);
}
bool CaptureOptionsDialog::GetEnableSampling() const { return ui_->samplingCheckBox->isChecked(); }
void CaptureOptionsDialog::SetSamplingPeriodMs(double sampling_period_ms) {
ui_->samplingPeriodMsDoubleSpinBox->setValue(sampling_period_ms);
}
double CaptureOptionsDialog::GetSamplingPeriodMs() const {
return ui_->samplingPeriodMsDoubleSpinBox->value();
}
void CaptureOptionsDialog::SetUnwindingMethod(UnwindingMethod unwinding_method) {
switch (unwinding_method) {
case CaptureOptions::kDwarf:
ui_->dwarfUnwindingRadioButton->setChecked(true);
break;
case CaptureOptions::kFramePointers:
ui_->framePointerUnwindingRadioButton->setChecked(true);
break;
default:
ORBIT_UNREACHABLE();
}
}
UnwindingMethod CaptureOptionsDialog::GetUnwindingMethod() const {
if (ui_->dwarfUnwindingRadioButton->isChecked()) {
ORBIT_CHECK(!ui_->framePointerUnwindingRadioButton->isChecked());
return CaptureOptions::kDwarf;
}
if (ui_->framePointerUnwindingRadioButton->isChecked()) {
ORBIT_CHECK(!ui_->dwarfUnwindingRadioButton->isChecked());
return CaptureOptions::kFramePointers;
}
ORBIT_UNREACHABLE();
}
void CaptureOptionsDialog::SetMaxCopyRawStackSize(uint16_t stack_dump_size) {
ORBIT_CHECK(stack_dump_size % 8 == 0);
ui_->maxCopyRawStackSizeSpinBox->setValue(stack_dump_size);
}
uint16_t CaptureOptionsDialog::GetMaxCopyRawStackSize() const {
uint16_t result = ui_->maxCopyRawStackSizeSpinBox->value();
ORBIT_CHECK(result % 8 == 0);
return result;
}
void CaptureOptionsDialog::SetCollectSchedulerInfo(bool collect_scheduler_info) {
ui_->schedulerCheckBox->setChecked(collect_scheduler_info);
}
bool CaptureOptionsDialog::GetCollectSchedulerInfo() const {
return ui_->schedulerCheckBox->isChecked();
}
void CaptureOptionsDialog::SetCollectThreadStates(bool collect_thread_state) {
ui_->threadStateCheckBox->setChecked(collect_thread_state);
}
bool CaptureOptionsDialog::GetCollectThreadStates() const {
return ui_->threadStateCheckBox->isChecked();
}
void CaptureOptionsDialog::SetTraceGpuSubmissions(bool trace_gpu_submissions) {
ui_->gpuSubmissionsCheckBox->setChecked(trace_gpu_submissions);
}
bool CaptureOptionsDialog::GetTraceGpuSubmissions() const {
return ui_->gpuSubmissionsCheckBox->isChecked();
}
void CaptureOptionsDialog::SetEnableApi(bool enable_api) {
ui_->apiCheckBox->setChecked(enable_api);
}
bool CaptureOptionsDialog::GetEnableApi() const { return ui_->apiCheckBox->isChecked(); }
void CaptureOptionsDialog::SetDynamicInstrumentationMethod(DynamicInstrumentationMethod method) {
switch (method) {
case CaptureOptions::kKernelUprobes:
ui_->uprobesRadioButton->setChecked(true);
break;
case CaptureOptions::kUserSpaceInstrumentation:
ui_->userSpaceRadioButton->setChecked(true);
break;
default:
ORBIT_UNREACHABLE();
}
}
DynamicInstrumentationMethod CaptureOptionsDialog::GetDynamicInstrumentationMethod() const {
if (ui_->uprobesRadioButton->isChecked()) {
ORBIT_CHECK(!ui_->userSpaceRadioButton->isChecked());
return CaptureOptions::kKernelUprobes;
}
if (ui_->userSpaceRadioButton->isChecked()) {
ORBIT_CHECK(!ui_->uprobesRadioButton->isChecked());
return CaptureOptions::kUserSpaceInstrumentation;
}
ORBIT_UNREACHABLE();
}
void CaptureOptionsDialog::SetWineSyscallHandlingMethod(
orbit_client_data::WineSyscallHandlingMethod method) {
switch (method) {
case WineSyscallHandlingMethod::kNoSpecialHandling:
ui_->wineNoneRadioButton->setChecked(true);
break;
case WineSyscallHandlingMethod::kStopUnwinding:
ui_->wineStopRadioButton->setChecked(true);
break;
case WineSyscallHandlingMethod::kRecordUserStack:
ui_->wineRecordRadioButton->setChecked(true);
break;
}
}
WineSyscallHandlingMethod CaptureOptionsDialog::GetWineSyscallHandlingMethod() const {
if (ui_->wineNoneRadioButton->isChecked()) {
ORBIT_CHECK(!ui_->wineStopRadioButton->isChecked() && !ui_->wineRecordRadioButton->isChecked());
return WineSyscallHandlingMethod::kNoSpecialHandling;
}
if (ui_->wineStopRadioButton->isChecked()) {
ORBIT_CHECK(!ui_->wineNoneRadioButton->isChecked() && !ui_->wineRecordRadioButton->isChecked());
return WineSyscallHandlingMethod::kStopUnwinding;
}
if (ui_->wineRecordRadioButton->isChecked()) {
ORBIT_CHECK(!ui_->wineNoneRadioButton->isChecked() && !ui_->wineStopRadioButton->isChecked());
return WineSyscallHandlingMethod::kRecordUserStack;
}
ORBIT_UNREACHABLE();
}
void CaptureOptionsDialog::SetEnableIntrospection(bool enable_introspection) {
ui_->introspectionCheckBox->setChecked(enable_introspection);
}
bool CaptureOptionsDialog::GetEnableIntrospection() const {
return ui_->introspectionCheckBox->isChecked();
}
void CaptureOptionsDialog::SetLimitLocalMarkerDepthPerCommandBuffer(
bool limit_local_marker_depth_per_command_buffer) {
ui_->localMarkerDepthCheckBox->setChecked(limit_local_marker_depth_per_command_buffer);
}
bool CaptureOptionsDialog::GetLimitLocalMarkerDepthPerCommandBuffer() const {
return ui_->localMarkerDepthCheckBox->isChecked();
}
void CaptureOptionsDialog::SetMaxLocalMarkerDepthPerCommandBuffer(
uint64_t local_marker_depth_per_command_buffer) {
ui_->localMarkerDepthLineEdit->setText(QString::number(local_marker_depth_per_command_buffer));
}
uint64_t CaptureOptionsDialog::GetMaxLocalMarkerDepthPerCommandBuffer() const {
ORBIT_CHECK(!ui_->localMarkerDepthLineEdit->text().isEmpty());
bool valid = false;
uint64_t result = ui_->localMarkerDepthLineEdit->text().toULongLong(&valid);
ORBIT_CHECK(valid);
return result;
}
void CaptureOptionsDialog::ResetLocalMarkerDepthLineEdit() {
if (ui_->localMarkerDepthLineEdit->text().isEmpty()) {
ui_->localMarkerDepthLineEdit->setText(QString::number(kLocalMarkerDepthDefaultValue));
}
}
void CaptureOptionsDialog::SetCollectMemoryInfo(bool collect_memory_info) {
ui_->collectMemoryInfoCheckBox->setChecked(collect_memory_info);
}
bool CaptureOptionsDialog::GetCollectMemoryInfo() const {
return ui_->collectMemoryInfoCheckBox->isChecked();
}
void CaptureOptionsDialog::SetMemorySamplingPeriodMs(uint64_t memory_sampling_period_ms) {
ui_->memorySamplingPeriodMsLineEdit->setText(QString::number(memory_sampling_period_ms));
}
void CaptureOptionsDialog::ResetMemorySamplingPeriodMsLineEditWhenEmpty() {
if (!ui_->memorySamplingPeriodMsLineEdit->text().isEmpty()) return;
ui_->memorySamplingPeriodMsLineEdit->setText(
QString::number(kMemorySamplingPeriodMsDefaultValue));
}
uint64_t CaptureOptionsDialog::GetMemorySamplingPeriodMs() const {
ORBIT_CHECK(!ui_->memorySamplingPeriodMsLineEdit->text().isEmpty());
bool valid = false;
uint64_t memory_sampling_period_ms =
ui_->memorySamplingPeriodMsLineEdit->text().toULongLong(&valid);
ORBIT_CHECK(valid);
return memory_sampling_period_ms;
}
void CaptureOptionsDialog::SetMemoryWarningThresholdKb(uint64_t memory_warning_threshold_kb) {
ui_->memoryWarningThresholdKbLineEdit->setText(QString::number(memory_warning_threshold_kb));
}
void CaptureOptionsDialog::ResetMemoryWarningThresholdKbLineEditWhenEmpty() {
if (!ui_->memoryWarningThresholdKbLineEdit->text().isEmpty()) return;
ui_->memoryWarningThresholdKbLineEdit->setText(
QString::number(kMemoryWarningThresholdKbDefaultValue));
}
uint64_t CaptureOptionsDialog::GetMemoryWarningThresholdKb() const {
ORBIT_CHECK(!ui_->memoryWarningThresholdKbLineEdit->text().isEmpty());
bool valid = false;
uint64_t result = ui_->memoryWarningThresholdKbLineEdit->text().toULongLong(&valid);
ORBIT_CHECK(valid);
return result;
}
} // namespace orbit_qt
<commit_msg>Disable the "Wine" group box on frame- pointer unwinding (#4015)<commit_after>// Copyright (c) 2020 The Orbit Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "CaptureOptionsDialog.h"
#include <absl/flags/declare.h>
#include <absl/flags/flag.h>
#include <QAbstractButton>
#include <QDialog>
#include <QDialogButtonBox>
#include <QWidget>
#include <QtGui/QValidator>
#include "ClientFlags/ClientFlags.h"
#include "ui_CaptureOptionsDialog.h"
namespace orbit_qt {
using orbit_client_data::WineSyscallHandlingMethod;
using orbit_grpc_protos::CaptureOptions;
using DynamicInstrumentationMethod =
orbit_grpc_protos::CaptureOptions::DynamicInstrumentationMethod;
using UnwindingMethod = orbit_grpc_protos::CaptureOptions::UnwindingMethod;
CaptureOptionsDialog::CaptureOptionsDialog(QWidget* parent)
: QDialog{parent}, ui_(std::make_unique<Ui::CaptureOptionsDialog>()) {
ui_->setupUi(this);
QObject::connect(ui_->buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept);
QObject::connect(ui_->buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject);
QObject::connect(ui_->framePointerUnwindingRadioButton, qOverload<bool>(&QRadioButton::toggled),
ui_->maxCopyRawStackSizeWidget,
[this](bool checked) { ui_->maxCopyRawStackSizeWidget->setEnabled(checked); });
QObject::connect(ui_->dwarfUnwindingRadioButton, qOverload<bool>(&QRadioButton::toggled),
ui_->wineGroupBox,
[this](bool checked) { ui_->wineGroupBox->setEnabled(checked); });
QObject::connect(ui_->collectMemoryInfoCheckBox, qOverload<bool>(&QCheckBox::toggled), this,
[this](bool checked) {
ui_->memorySamplingPeriodMsLabel->setEnabled(checked);
ui_->memorySamplingPeriodMsLineEdit->setEnabled(checked);
ui_->memoryWarningThresholdKbLabel->setEnabled(checked);
ui_->memoryWarningThresholdKbLineEdit->setEnabled(checked);
});
QObject::connect(ui_->samplingCheckBox, qOverload<bool>(&QCheckBox::toggled), this,
[this](bool checked) {
ui_->samplingPeriodMsLabel->setEnabled(checked);
ui_->samplingPeriodMsDoubleSpinBox->setEnabled(checked);
ui_->unwindingMethodGroupBox->setEnabled(checked);
});
ui_->samplingPeriodMsLabel->setEnabled(ui_->samplingCheckBox->isChecked());
ui_->samplingPeriodMsDoubleSpinBox->setEnabled(ui_->samplingCheckBox->isChecked());
ui_->unwindingMethodGroupBox->setEnabled(ui_->samplingCheckBox->isChecked());
ui_->maxCopyRawStackSizeSpinBox->setValue(kMaxCopyRawStackSizeDefaultValue);
ui_->maxCopyRawStackSizeWidget->setEnabled(ui_->framePointerUnwindingRadioButton->isChecked());
ui_->wineGroupBox->setEnabled(ui_->dwarfUnwindingRadioButton->isChecked());
ui_->localMarkerDepthLineEdit->setValidator(&uint64_validator_);
ui_->memorySamplingPeriodMsLabel->setEnabled(ui_->collectMemoryInfoCheckBox->isChecked());
ui_->memorySamplingPeriodMsLineEdit->setEnabled(ui_->collectMemoryInfoCheckBox->isChecked());
ui_->memoryWarningThresholdKbLabel->setEnabled(ui_->collectMemoryInfoCheckBox->isChecked());
ui_->memoryWarningThresholdKbLineEdit->setEnabled(ui_->collectMemoryInfoCheckBox->isChecked());
ui_->memorySamplingPeriodMsLineEdit->setValidator(new UInt64Validator(
1, std::numeric_limits<uint64_t>::max(), ui_->memorySamplingPeriodMsLineEdit));
ui_->memoryWarningThresholdKbLineEdit->setValidator(&uint64_validator_);
if (!absl::GetFlag(FLAGS_enable_warning_threshold)) {
ui_->memoryWarningThresholdKbLabel->hide();
ui_->memoryWarningThresholdKbLineEdit->hide();
}
if (!absl::GetFlag(FLAGS_devmode)) {
// TODO(b/198748597): Don't hide samplingCheckBox once disabling sampling completely is exposed.
ui_->samplingCheckBox->hide();
ui_->schedulerCheckBox->hide();
ui_->devModeGroupBox->hide();
ui_->wineNoneRadioButton->hide();
}
}
void CaptureOptionsDialog::SetEnableSampling(bool enable_sampling) {
ui_->samplingCheckBox->setChecked(enable_sampling);
}
bool CaptureOptionsDialog::GetEnableSampling() const { return ui_->samplingCheckBox->isChecked(); }
void CaptureOptionsDialog::SetSamplingPeriodMs(double sampling_period_ms) {
ui_->samplingPeriodMsDoubleSpinBox->setValue(sampling_period_ms);
}
double CaptureOptionsDialog::GetSamplingPeriodMs() const {
return ui_->samplingPeriodMsDoubleSpinBox->value();
}
void CaptureOptionsDialog::SetUnwindingMethod(UnwindingMethod unwinding_method) {
switch (unwinding_method) {
case CaptureOptions::kDwarf:
ui_->dwarfUnwindingRadioButton->setChecked(true);
break;
case CaptureOptions::kFramePointers:
ui_->framePointerUnwindingRadioButton->setChecked(true);
break;
default:
ORBIT_UNREACHABLE();
}
}
UnwindingMethod CaptureOptionsDialog::GetUnwindingMethod() const {
if (ui_->dwarfUnwindingRadioButton->isChecked()) {
ORBIT_CHECK(!ui_->framePointerUnwindingRadioButton->isChecked());
return CaptureOptions::kDwarf;
}
if (ui_->framePointerUnwindingRadioButton->isChecked()) {
ORBIT_CHECK(!ui_->dwarfUnwindingRadioButton->isChecked());
return CaptureOptions::kFramePointers;
}
ORBIT_UNREACHABLE();
}
void CaptureOptionsDialog::SetMaxCopyRawStackSize(uint16_t stack_dump_size) {
ORBIT_CHECK(stack_dump_size % 8 == 0);
ui_->maxCopyRawStackSizeSpinBox->setValue(stack_dump_size);
}
uint16_t CaptureOptionsDialog::GetMaxCopyRawStackSize() const {
uint16_t result = ui_->maxCopyRawStackSizeSpinBox->value();
ORBIT_CHECK(result % 8 == 0);
return result;
}
void CaptureOptionsDialog::SetCollectSchedulerInfo(bool collect_scheduler_info) {
ui_->schedulerCheckBox->setChecked(collect_scheduler_info);
}
bool CaptureOptionsDialog::GetCollectSchedulerInfo() const {
return ui_->schedulerCheckBox->isChecked();
}
void CaptureOptionsDialog::SetCollectThreadStates(bool collect_thread_state) {
ui_->threadStateCheckBox->setChecked(collect_thread_state);
}
bool CaptureOptionsDialog::GetCollectThreadStates() const {
return ui_->threadStateCheckBox->isChecked();
}
void CaptureOptionsDialog::SetTraceGpuSubmissions(bool trace_gpu_submissions) {
ui_->gpuSubmissionsCheckBox->setChecked(trace_gpu_submissions);
}
bool CaptureOptionsDialog::GetTraceGpuSubmissions() const {
return ui_->gpuSubmissionsCheckBox->isChecked();
}
void CaptureOptionsDialog::SetEnableApi(bool enable_api) {
ui_->apiCheckBox->setChecked(enable_api);
}
bool CaptureOptionsDialog::GetEnableApi() const { return ui_->apiCheckBox->isChecked(); }
void CaptureOptionsDialog::SetDynamicInstrumentationMethod(DynamicInstrumentationMethod method) {
switch (method) {
case CaptureOptions::kKernelUprobes:
ui_->uprobesRadioButton->setChecked(true);
break;
case CaptureOptions::kUserSpaceInstrumentation:
ui_->userSpaceRadioButton->setChecked(true);
break;
default:
ORBIT_UNREACHABLE();
}
}
DynamicInstrumentationMethod CaptureOptionsDialog::GetDynamicInstrumentationMethod() const {
if (ui_->uprobesRadioButton->isChecked()) {
ORBIT_CHECK(!ui_->userSpaceRadioButton->isChecked());
return CaptureOptions::kKernelUprobes;
}
if (ui_->userSpaceRadioButton->isChecked()) {
ORBIT_CHECK(!ui_->uprobesRadioButton->isChecked());
return CaptureOptions::kUserSpaceInstrumentation;
}
ORBIT_UNREACHABLE();
}
void CaptureOptionsDialog::SetWineSyscallHandlingMethod(
orbit_client_data::WineSyscallHandlingMethod method) {
switch (method) {
case WineSyscallHandlingMethod::kNoSpecialHandling:
ui_->wineNoneRadioButton->setChecked(true);
break;
case WineSyscallHandlingMethod::kStopUnwinding:
ui_->wineStopRadioButton->setChecked(true);
break;
case WineSyscallHandlingMethod::kRecordUserStack:
ui_->wineRecordRadioButton->setChecked(true);
break;
}
}
WineSyscallHandlingMethod CaptureOptionsDialog::GetWineSyscallHandlingMethod() const {
if (ui_->wineNoneRadioButton->isChecked()) {
ORBIT_CHECK(!ui_->wineStopRadioButton->isChecked() && !ui_->wineRecordRadioButton->isChecked());
return WineSyscallHandlingMethod::kNoSpecialHandling;
}
if (ui_->wineStopRadioButton->isChecked()) {
ORBIT_CHECK(!ui_->wineNoneRadioButton->isChecked() && !ui_->wineRecordRadioButton->isChecked());
return WineSyscallHandlingMethod::kStopUnwinding;
}
if (ui_->wineRecordRadioButton->isChecked()) {
ORBIT_CHECK(!ui_->wineNoneRadioButton->isChecked() && !ui_->wineStopRadioButton->isChecked());
return WineSyscallHandlingMethod::kRecordUserStack;
}
ORBIT_UNREACHABLE();
}
void CaptureOptionsDialog::SetEnableIntrospection(bool enable_introspection) {
ui_->introspectionCheckBox->setChecked(enable_introspection);
}
bool CaptureOptionsDialog::GetEnableIntrospection() const {
return ui_->introspectionCheckBox->isChecked();
}
void CaptureOptionsDialog::SetLimitLocalMarkerDepthPerCommandBuffer(
bool limit_local_marker_depth_per_command_buffer) {
ui_->localMarkerDepthCheckBox->setChecked(limit_local_marker_depth_per_command_buffer);
}
bool CaptureOptionsDialog::GetLimitLocalMarkerDepthPerCommandBuffer() const {
return ui_->localMarkerDepthCheckBox->isChecked();
}
void CaptureOptionsDialog::SetMaxLocalMarkerDepthPerCommandBuffer(
uint64_t local_marker_depth_per_command_buffer) {
ui_->localMarkerDepthLineEdit->setText(QString::number(local_marker_depth_per_command_buffer));
}
uint64_t CaptureOptionsDialog::GetMaxLocalMarkerDepthPerCommandBuffer() const {
ORBIT_CHECK(!ui_->localMarkerDepthLineEdit->text().isEmpty());
bool valid = false;
uint64_t result = ui_->localMarkerDepthLineEdit->text().toULongLong(&valid);
ORBIT_CHECK(valid);
return result;
}
void CaptureOptionsDialog::ResetLocalMarkerDepthLineEdit() {
if (ui_->localMarkerDepthLineEdit->text().isEmpty()) {
ui_->localMarkerDepthLineEdit->setText(QString::number(kLocalMarkerDepthDefaultValue));
}
}
void CaptureOptionsDialog::SetCollectMemoryInfo(bool collect_memory_info) {
ui_->collectMemoryInfoCheckBox->setChecked(collect_memory_info);
}
bool CaptureOptionsDialog::GetCollectMemoryInfo() const {
return ui_->collectMemoryInfoCheckBox->isChecked();
}
void CaptureOptionsDialog::SetMemorySamplingPeriodMs(uint64_t memory_sampling_period_ms) {
ui_->memorySamplingPeriodMsLineEdit->setText(QString::number(memory_sampling_period_ms));
}
void CaptureOptionsDialog::ResetMemorySamplingPeriodMsLineEditWhenEmpty() {
if (!ui_->memorySamplingPeriodMsLineEdit->text().isEmpty()) return;
ui_->memorySamplingPeriodMsLineEdit->setText(
QString::number(kMemorySamplingPeriodMsDefaultValue));
}
uint64_t CaptureOptionsDialog::GetMemorySamplingPeriodMs() const {
ORBIT_CHECK(!ui_->memorySamplingPeriodMsLineEdit->text().isEmpty());
bool valid = false;
uint64_t memory_sampling_period_ms =
ui_->memorySamplingPeriodMsLineEdit->text().toULongLong(&valid);
ORBIT_CHECK(valid);
return memory_sampling_period_ms;
}
void CaptureOptionsDialog::SetMemoryWarningThresholdKb(uint64_t memory_warning_threshold_kb) {
ui_->memoryWarningThresholdKbLineEdit->setText(QString::number(memory_warning_threshold_kb));
}
void CaptureOptionsDialog::ResetMemoryWarningThresholdKbLineEditWhenEmpty() {
if (!ui_->memoryWarningThresholdKbLineEdit->text().isEmpty()) return;
ui_->memoryWarningThresholdKbLineEdit->setText(
QString::number(kMemoryWarningThresholdKbDefaultValue));
}
uint64_t CaptureOptionsDialog::GetMemoryWarningThresholdKb() const {
ORBIT_CHECK(!ui_->memoryWarningThresholdKbLineEdit->text().isEmpty());
bool valid = false;
uint64_t result = ui_->memoryWarningThresholdKbLineEdit->text().toULongLong(&valid);
ORBIT_CHECK(valid);
return result;
}
} // namespace orbit_qt
<|endoftext|>
|
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include <tools/rc.h>
#include <vcl/event.hxx>
#include <vcl/layout.hxx>
#include <vcl/svapp.hxx>
#include <vcl/tabpage.hxx>
#include <vcl/tabctrl.hxx>
#include <vcl/bitmapex.hxx>
#include <vcl/settings.hxx>
#include <svdata.hxx>
#include <com/sun/star/accessibility/XAccessible.hpp>
void TabPage::ImplInit( Window* pParent, WinBits nStyle )
{
if ( !(nStyle & WB_NODIALOGCONTROL) )
nStyle |= WB_DIALOGCONTROL;
Window::ImplInit( pParent, nStyle, NULL );
ImplInitSettings();
// if the tabpage is drawn (ie filled) by a native widget, make sure all contols will have transparent background
// otherwise they will paint with a wrong background
if( IsNativeControlSupported(CTRL_TAB_BODY, PART_ENTIRE_CONTROL) && GetParent() && (GetParent()->GetType() == WINDOW_TABCONTROL) )
EnableChildTransparentMode( true );
}
void TabPage::ImplInitSettings()
{
Window* pParent = GetParent();
if ( pParent->IsChildTransparentModeEnabled() && !IsControlBackground() )
{
EnableChildTransparentMode( true );
SetParentClipMode( PARENTCLIPMODE_NOCLIP );
SetPaintTransparent( true );
SetBackground();
}
else
{
EnableChildTransparentMode( false );
SetParentClipMode( 0 );
SetPaintTransparent( false );
if ( IsControlBackground() )
SetBackground( GetControlBackground() );
else
SetBackground( pParent->GetBackground() );
}
}
TabPage::TabPage( Window* pParent, WinBits nStyle ) :
Window( WINDOW_TABPAGE )
{
ImplInit( pParent, nStyle );
}
TabPage::TabPage( Window* pParent, const ResId& rResId ) :
Window( WINDOW_TABPAGE )
{
rResId.SetRT( RSC_TABPAGE );
WinBits nStyle = ImplInitRes( rResId );
ImplInit( pParent, nStyle );
ImplLoadRes(rResId);
if ( !(nStyle & WB_HIDE) )
Show();
}
TabPage::TabPage(Window *pParent, const OString& rID, const OUString& rUIXMLDescription)
: Window(WINDOW_TABPAGE)
{
ImplInit(pParent, 0);
m_pUIBuilder = new VclBuilder(this, getUIRootDir(), rUIXMLDescription, rID);
}
void TabPage::StateChanged( StateChangedType nType )
{
Window::StateChanged( nType );
if ( nType == STATE_CHANGE_INITSHOW )
{
if ( GetSettings().GetStyleSettings().GetAutoMnemonic() )
ImplWindowAutoMnemonic( this );
// FIXME: no layouting, workaround some clipping issues
ImplAdjustNWFSizes();
}
else if ( nType == STATE_CHANGE_CONTROLBACKGROUND )
{
ImplInitSettings();
Invalidate();
}
}
void TabPage::DataChanged( const DataChangedEvent& rDCEvt )
{
Window::DataChanged( rDCEvt );
if ( (rDCEvt.GetType() == DATACHANGED_SETTINGS) &&
(rDCEvt.GetFlags() & SETTINGS_STYLE) )
{
ImplInitSettings();
Invalidate();
}
}
void TabPage::Paint( const Rectangle& )
{
// draw native tabpage only inside tabcontrols, standalone tabpages look ugly (due to bad dialog design)
if( IsNativeControlSupported(CTRL_TAB_BODY, PART_ENTIRE_CONTROL) && GetParent() && (GetParent()->GetType() == WINDOW_TABCONTROL) )
{
const ImplControlValue aControlValue;
ControlState nState = CTRL_STATE_ENABLED;
int part = PART_ENTIRE_CONTROL;
if ( !IsEnabled() )
nState &= ~CTRL_STATE_ENABLED;
if ( HasFocus() )
nState |= CTRL_STATE_FOCUSED;
Point aPoint;
// pass the whole window region to NWF as the tab body might be a gradient or bitmap
// that has to be scaled properly, clipping makes sure that we do not paint too much
Rectangle aCtrlRegion( aPoint, GetOutputSizePixel() );
DrawNativeControl( CTRL_TAB_BODY, part, aCtrlRegion, nState,
aControlValue, OUString() );
}
}
void TabPage::Draw( OutputDevice* pDev, const Point& rPos, const Size& rSize, sal_uLong )
{
Point aPos = pDev->LogicToPixel( rPos );
Size aSize = pDev->LogicToPixel( rSize );
Wallpaper aWallpaper = GetBackground();
if ( !aWallpaper.IsBitmap() )
ImplInitSettings();
pDev->Push();
pDev->SetMapMode();
pDev->SetLineColor();
if ( aWallpaper.IsBitmap() )
pDev->DrawBitmapEx( aPos, aSize, aWallpaper.GetBitmap() );
else
{
if( aWallpaper.GetColor() == COL_AUTO )
pDev->SetFillColor( GetSettings().GetStyleSettings().GetDialogColor() );
else
pDev->SetFillColor( aWallpaper.GetColor() );
pDev->DrawRect( Rectangle( aPos, aSize ) );
}
pDev->Pop();
}
void TabPage::ActivatePage()
{
}
void TabPage::DeactivatePage()
{
}
OString TabPage::GetConfigId() const
{
OString sId(GetHelpId());
if (sId.isEmpty() && isLayoutEnabled(this))
sId = GetWindow(WINDOW_FIRSTCHILD)->GetHelpId();
return sId;
}
Size TabPage::GetOptimalSize() const
{
if (isLayoutEnabled(this))
return VclContainer::getLayoutRequisition(*GetWindow(WINDOW_FIRSTCHILD));
return getLegacyBestSizeForChildren(*this);
}
void TabPage::SetPosSizePixel(const Point& rAllocPos, const Size& rAllocation)
{
Window::SetPosSizePixel(rAllocPos, rAllocation);
if (isLayoutEnabled(this))
VclContainer::setLayoutAllocation(*GetWindow(WINDOW_FIRSTCHILD), Point(0, 0), rAllocation);
}
void TabPage::SetSizePixel(const Size& rAllocation)
{
Window::SetSizePixel(rAllocation);
if (isLayoutEnabled(this))
VclContainer::setLayoutAllocation(*GetWindow(WINDOW_FIRSTCHILD), Point(0, 0), rAllocation);
}
void TabPage::SetPosPixel(const Point& rAllocPos)
{
Window::SetPosPixel(rAllocPos);
if (isLayoutEnabled(this))
VclContainer::setLayoutAllocation(*GetWindow(WINDOW_FIRSTCHILD), Point(0, 0), GetOutputSizePixel());
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Related: fdo#81457 skip setting an empty allocation<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include <tools/rc.h>
#include <vcl/event.hxx>
#include <vcl/layout.hxx>
#include <vcl/svapp.hxx>
#include <vcl/tabpage.hxx>
#include <vcl/tabctrl.hxx>
#include <vcl/bitmapex.hxx>
#include <vcl/settings.hxx>
#include <svdata.hxx>
#include <com/sun/star/accessibility/XAccessible.hpp>
void TabPage::ImplInit( Window* pParent, WinBits nStyle )
{
if ( !(nStyle & WB_NODIALOGCONTROL) )
nStyle |= WB_DIALOGCONTROL;
Window::ImplInit( pParent, nStyle, NULL );
ImplInitSettings();
// if the tabpage is drawn (ie filled) by a native widget, make sure all contols will have transparent background
// otherwise they will paint with a wrong background
if( IsNativeControlSupported(CTRL_TAB_BODY, PART_ENTIRE_CONTROL) && GetParent() && (GetParent()->GetType() == WINDOW_TABCONTROL) )
EnableChildTransparentMode( true );
}
void TabPage::ImplInitSettings()
{
Window* pParent = GetParent();
if ( pParent->IsChildTransparentModeEnabled() && !IsControlBackground() )
{
EnableChildTransparentMode( true );
SetParentClipMode( PARENTCLIPMODE_NOCLIP );
SetPaintTransparent( true );
SetBackground();
}
else
{
EnableChildTransparentMode( false );
SetParentClipMode( 0 );
SetPaintTransparent( false );
if ( IsControlBackground() )
SetBackground( GetControlBackground() );
else
SetBackground( pParent->GetBackground() );
}
}
TabPage::TabPage( Window* pParent, WinBits nStyle ) :
Window( WINDOW_TABPAGE )
{
ImplInit( pParent, nStyle );
}
TabPage::TabPage( Window* pParent, const ResId& rResId ) :
Window( WINDOW_TABPAGE )
{
rResId.SetRT( RSC_TABPAGE );
WinBits nStyle = ImplInitRes( rResId );
ImplInit( pParent, nStyle );
ImplLoadRes(rResId);
if ( !(nStyle & WB_HIDE) )
Show();
}
TabPage::TabPage(Window *pParent, const OString& rID, const OUString& rUIXMLDescription)
: Window(WINDOW_TABPAGE)
{
ImplInit(pParent, 0);
m_pUIBuilder = new VclBuilder(this, getUIRootDir(), rUIXMLDescription, rID);
}
void TabPage::StateChanged( StateChangedType nType )
{
Window::StateChanged( nType );
if ( nType == STATE_CHANGE_INITSHOW )
{
if ( GetSettings().GetStyleSettings().GetAutoMnemonic() )
ImplWindowAutoMnemonic( this );
// FIXME: no layouting, workaround some clipping issues
ImplAdjustNWFSizes();
}
else if ( nType == STATE_CHANGE_CONTROLBACKGROUND )
{
ImplInitSettings();
Invalidate();
}
}
void TabPage::DataChanged( const DataChangedEvent& rDCEvt )
{
Window::DataChanged( rDCEvt );
if ( (rDCEvt.GetType() == DATACHANGED_SETTINGS) &&
(rDCEvt.GetFlags() & SETTINGS_STYLE) )
{
ImplInitSettings();
Invalidate();
}
}
void TabPage::Paint( const Rectangle& )
{
// draw native tabpage only inside tabcontrols, standalone tabpages look ugly (due to bad dialog design)
if( IsNativeControlSupported(CTRL_TAB_BODY, PART_ENTIRE_CONTROL) && GetParent() && (GetParent()->GetType() == WINDOW_TABCONTROL) )
{
const ImplControlValue aControlValue;
ControlState nState = CTRL_STATE_ENABLED;
int part = PART_ENTIRE_CONTROL;
if ( !IsEnabled() )
nState &= ~CTRL_STATE_ENABLED;
if ( HasFocus() )
nState |= CTRL_STATE_FOCUSED;
Point aPoint;
// pass the whole window region to NWF as the tab body might be a gradient or bitmap
// that has to be scaled properly, clipping makes sure that we do not paint too much
Rectangle aCtrlRegion( aPoint, GetOutputSizePixel() );
DrawNativeControl( CTRL_TAB_BODY, part, aCtrlRegion, nState,
aControlValue, OUString() );
}
}
void TabPage::Draw( OutputDevice* pDev, const Point& rPos, const Size& rSize, sal_uLong )
{
Point aPos = pDev->LogicToPixel( rPos );
Size aSize = pDev->LogicToPixel( rSize );
Wallpaper aWallpaper = GetBackground();
if ( !aWallpaper.IsBitmap() )
ImplInitSettings();
pDev->Push();
pDev->SetMapMode();
pDev->SetLineColor();
if ( aWallpaper.IsBitmap() )
pDev->DrawBitmapEx( aPos, aSize, aWallpaper.GetBitmap() );
else
{
if( aWallpaper.GetColor() == COL_AUTO )
pDev->SetFillColor( GetSettings().GetStyleSettings().GetDialogColor() );
else
pDev->SetFillColor( aWallpaper.GetColor() );
pDev->DrawRect( Rectangle( aPos, aSize ) );
}
pDev->Pop();
}
void TabPage::ActivatePage()
{
}
void TabPage::DeactivatePage()
{
}
OString TabPage::GetConfigId() const
{
OString sId(GetHelpId());
if (sId.isEmpty() && isLayoutEnabled(this))
sId = GetWindow(WINDOW_FIRSTCHILD)->GetHelpId();
return sId;
}
Size TabPage::GetOptimalSize() const
{
if (isLayoutEnabled(this))
return VclContainer::getLayoutRequisition(*GetWindow(WINDOW_FIRSTCHILD));
return getLegacyBestSizeForChildren(*this);
}
void TabPage::SetPosSizePixel(const Point& rAllocPos, const Size& rAllocation)
{
Window::SetPosSizePixel(rAllocPos, rAllocation);
if (isLayoutEnabled(this) && rAllocation.Width() && rAllocation.Height())
VclContainer::setLayoutAllocation(*GetWindow(WINDOW_FIRSTCHILD), Point(0, 0), rAllocation);
}
void TabPage::SetSizePixel(const Size& rAllocation)
{
Window::SetSizePixel(rAllocation);
if (isLayoutEnabled(this) && rAllocation.Width() && rAllocation.Height())
VclContainer::setLayoutAllocation(*GetWindow(WINDOW_FIRSTCHILD), Point(0, 0), rAllocation);
}
void TabPage::SetPosPixel(const Point& rAllocPos)
{
Window::SetPosPixel(rAllocPos);
Size aAllocation(GetOutputSizePixel());
if (isLayoutEnabled(this) && aAllocation.Width() && aAllocation.Height())
{
VclContainer::setLayoutAllocation(*GetWindow(WINDOW_FIRSTCHILD), Point(0, 0), aAllocation);
}
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>
|
<commit_before>/*
* Copyright 2014 Christian Loose <christian.loose@hamburg.de>
*
* 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) The name of the author may not be used to
* endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "htmltemplate.h"
#include <QFile>
HtmlTemplate::HtmlTemplate()
{
QFile f(":/template.html");
if (f.open(QIODevice::ReadOnly | QIODevice::Text)) {
htmlTemplate = f.readAll();
}
}
QString HtmlTemplate::render(const QString &body, RenderOptions options) const
{
// add scrollbar synchronization
options |= Template::ScrollbarSynchronization;
return renderAsHtml(QString(), body, options);
}
QString HtmlTemplate::exportAsHtml(const QString &header, const QString &body, RenderOptions options) const
{
// clear code highlighting option since it depends on the resource file
options &= ~Template::CodeHighlighting;
return renderAsHtml(header, body, options);
}
QString HtmlTemplate::renderAsHtml(const QString &header, const QString &body, Template::RenderOptions options) const
{
if (htmlTemplate.isEmpty()) {
return body;
}
QString htmlHeader = buildHtmlHeader(options);
htmlHeader += header;
return QString(htmlTemplate)
.replace(QLatin1String("<!--__HTML_HEADER__-->"), htmlHeader)
.replace(QLatin1String("<!--__HTML_CONTENT__-->"), body);
}
QString HtmlTemplate::buildHtmlHeader(RenderOptions options) const
{
QString header;
// add javascript for scrollbar synchronization
if (options.testFlag(Template::ScrollbarSynchronization)) {
header += "<script type=\"text/javascript\">window.onscroll = function() { mainwin.webViewScrolled(); }; </script>\n";
}
// add MathJax.js script to HTML header
if (options.testFlag(Template::MathSupport)) {
header += "<script type=\"text/javascript\" src=\"http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML\"></script>\n";
}
// add Highlight.js script to HTML header
if (options.testFlag(Template::CodeHighlighting)) {
header += QString("<link rel=\"stylesheet\" href=\"qrc:/scripts/highlight.js/styles/%1.css\">\n").arg(codeHighlightingStyle());
header += "<script src=\"qrc:/scripts/highlight.js/highlight.pack.js\"></script>\n";
header += "<script>hljs.initHighlightingOnLoad();</script>\n";
}
return header;
}
<commit_msg>Removed writing htmltemplate to filesystem<commit_after>/*
* Copyright 2014 Christian Loose <christian.loose@hamburg.de>
*
* 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) The name of the author may not be used to
* endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "htmltemplate.h"
#include <QFile>
HtmlTemplate::HtmlTemplate()
{
}
QString HtmlTemplate::render(const QString &body, RenderOptions options) const
{
// add scrollbar synchronization
options |= Template::ScrollbarSynchronization;
return renderAsHtml(QString(), body, options);
}
QString HtmlTemplate::exportAsHtml(const QString &header, const QString &body, RenderOptions options) const
{
// clear code highlighting option since it depends on the resource file
options &= ~Template::CodeHighlighting;
return renderAsHtml(header, body, options);
}
QString HtmlTemplate::renderAsHtml(const QString &header, const QString &body, Template::RenderOptions options) const
{
if (htmlTemplate.isEmpty()) {
return body;
}
QString htmlHeader = buildHtmlHeader(options);
htmlHeader += header;
return QString(htmlTemplate)
.replace(QLatin1String("<!--__HTML_HEADER__-->"), htmlHeader)
.replace(QLatin1String("<!--__HTML_CONTENT__-->"), body);
}
QString HtmlTemplate::buildHtmlHeader(RenderOptions options) const
{
QString header;
// add javascript for scrollbar synchronization
if (options.testFlag(Template::ScrollbarSynchronization)) {
header += "<script type=\"text/javascript\">window.onscroll = function() { mainwin.webViewScrolled(); }; </script>\n";
}
// add MathJax.js script to HTML header
if (options.testFlag(Template::MathSupport)) {
header += "<script type=\"text/javascript\" src=\"http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML\"></script>\n";
}
// add Highlight.js script to HTML header
if (options.testFlag(Template::CodeHighlighting)) {
header += QString("<link rel=\"stylesheet\" href=\"qrc:/scripts/highlight.js/styles/%1.css\">\n").arg(codeHighlightingStyle());
header += "<script src=\"qrc:/scripts/highlight.js/highlight.pack.js\"></script>\n";
header += "<script>hljs.initHighlightingOnLoad();</script>\n";
}
return header;
}
<|endoftext|>
|
<commit_before>//
// Created by patryk on 10.12.16.
//
#include <gtest/gtest.h>
#include <zinot-utils/zimesh-json/ZimeshJsonReader.hpp>
class ZimeshJsonTest : public ::testing::Test
{
protected:
Zimesh::ZimeshJsonDao zimeshJsonDao;
};
TEST_F(ZimeshJsonTest, loading)
{
EXPECT_TRUE(Zimesh::ZimeshJsonReader::loadFromJson("media/models/table.json", zimeshJsonDao));
Zimesh::ZimeshJsonDao & dao = zimeshJsonDao;
}
<commit_msg>Fixed testing Zimesh JSON loader<commit_after>//
// Created by patryk on 10.12.16.
//
#include <gtest/gtest.h>
#include <zinot-utils/zimesh-json/ZimeshJsonReader.hpp>
class ZimeshJsonTest : public ::testing::Test
{
protected:
Zimesh::ZimeshJsonDao zimeshJsonDao;
};
TEST_F(ZimeshJsonTest, loading)
{
EXPECT_TRUE(Zimesh::ZimeshJsonReader::loadFromJson("media/models/table/table.json", zimeshJsonDao));
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2007 The Hewlett-Packard Development Company
* All rights reserved.
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Gabe Black
*/
#ifndef __ARCH_X86_FAULTS_HH__
#define __ARCH_X86_FAULTS_HH__
#include <string>
#include "base/bitunion.hh"
#include "base/misc.hh"
#include "sim/faults.hh"
#include "sim/tlb.hh"
namespace X86ISA
{
// Base class for all x86 "faults" where faults is in the m5 sense
class X86FaultBase : public FaultBase
{
protected:
const char * faultName;
const char * mnem;
uint8_t vector;
uint64_t errorCode;
X86FaultBase(const char * _faultName, const char * _mnem,
const uint8_t _vector, uint64_t _errorCode = (uint64_t)-1)
: faultName(_faultName), mnem(_mnem),
vector(_vector), errorCode(_errorCode)
{
}
const char * name() const
{
return faultName;
}
virtual bool isBenign()
{
return true;
}
virtual const char * mnemonic() const
{
return mnem;
}
virtual bool isSoft()
{
return false;
}
void invoke(ThreadContext * tc,
StaticInstPtr inst = StaticInst::nullStaticInstPtr);
virtual std::string describe() const;
};
// Base class for x86 faults which behave as if the underlying instruction
// didn't happen.
class X86Fault : public X86FaultBase
{
protected:
X86Fault(const char * name, const char * mnem,
const uint8_t vector, uint64_t _errorCode = (uint64_t)-1)
: X86FaultBase(name, mnem, vector, _errorCode)
{}
};
// Base class for x86 traps which behave as if the underlying instruction
// completed.
class X86Trap : public X86FaultBase
{
protected:
X86Trap(const char * name, const char * mnem,
const uint8_t vector, uint64_t _errorCode = (uint64_t)-1)
: X86FaultBase(name, mnem, vector, _errorCode)
{}
void invoke(ThreadContext * tc,
StaticInstPtr inst = StaticInst::nullStaticInstPtr);
};
// Base class for x86 aborts which seem to be catastrophic failures.
class X86Abort : public X86FaultBase
{
protected:
X86Abort(const char * name, const char * mnem,
const uint8_t vector, uint64_t _errorCode = (uint64_t)-1)
: X86FaultBase(name, mnem, vector, _errorCode)
{}
void invoke(ThreadContext * tc,
StaticInstPtr inst = StaticInst::nullStaticInstPtr);
};
// Base class for x86 interrupts.
class X86Interrupt : public X86FaultBase
{
protected:
X86Interrupt(const char * name, const char * mnem,
const uint8_t _vector, uint64_t _errorCode = (uint64_t)-1)
: X86FaultBase(name, mnem, _vector, _errorCode)
{}
};
class UnimpInstFault : public FaultBase
{
public:
const char * name() const
{
return "unimplemented_micro";
}
void invoke(ThreadContext * tc,
StaticInstPtr inst = StaticInst::nullStaticInstPtr)
{
panic("Unimplemented instruction!");
}
};
// Below is a summary of the interrupt/exception information in the
// architecture manuals.
// Class | Type | vector | Cause | mnem
//------------------------------------------------------------------------
//Contrib Fault 0 Divide-by-Zero-Error #DE
//Benign Either 1 Debug #DB
//Benign Interrupt 2 Non-Maskable-Interrupt #NMI
//Benign Trap 3 Breakpoint #BP
//Benign Trap 4 Overflow #OF
//Benign Fault 5 Bound-Range #BR
//Benign Fault 6 Invalid-Opcode #UD
//Benign Fault 7 Device-Not-Available #NM
//Benign Abort 8 Double-Fault #DF
// 9 Coprocessor-Segment-Overrun
//Contrib Fault 10 Invalid-TSS #TS
//Contrib Fault 11 Segment-Not-Present #NP
//Contrib Fault 12 Stack #SS
//Contrib Fault 13 General-Protection #GP
//Either Fault 14 Page-Fault #PF
// 15 Reserved
//Benign Fault 16 x87 Floating-Point Exception Pending #MF
//Benign Fault 17 Alignment-Check #AC
//Benign Abort 18 Machine-Check #MC
//Benign Fault 19 SIMD Floating-Point #XF
// 20-29 Reserved
//Contrib ? 30 Security Exception #SX
// 31 Reserved
//Benign Interrupt 0-255 External Interrupts #INTR
//Benign Interrupt 0-255 Software Interrupts INTn
class DivideByZero : public X86Fault
{
public:
DivideByZero() :
X86Fault("Divide-by-Zero-Error", "#DE", 0)
{}
};
class DebugException : public X86FaultBase
{
public:
DebugException() :
X86FaultBase("Debug", "#DB", 1)
{}
};
class NonMaskableInterrupt : public X86Interrupt
{
public:
NonMaskableInterrupt(uint8_t _vector) :
X86Interrupt("Non Maskable Interrupt", "#NMI", 2, _vector)
{}
};
class Breakpoint : public X86Trap
{
public:
Breakpoint() :
X86Trap("Breakpoint", "#BP", 3)
{}
};
class OverflowTrap : public X86Trap
{
public:
OverflowTrap() :
X86Trap("Overflow", "#OF", 4)
{}
};
class BoundRange : public X86Fault
{
public:
BoundRange() :
X86Fault("Bound-Range", "#BR", 5)
{}
};
class InvalidOpcode : public X86Fault
{
public:
InvalidOpcode() :
X86Fault("Invalid-Opcode", "#UD", 6)
{}
void invoke(ThreadContext * tc,
StaticInstPtr inst = StaticInst::nullStaticInstPtr);
};
class DeviceNotAvailable : public X86Fault
{
public:
DeviceNotAvailable() :
X86Fault("Device-Not-Available", "#NM", 7)
{}
};
class DoubleFault : public X86Abort
{
public:
DoubleFault() :
X86Abort("Double-Fault", "#DF", 8, 0)
{}
};
class InvalidTSS : public X86Fault
{
public:
InvalidTSS(uint32_t _errorCode) :
X86Fault("Invalid-TSS", "#TS", 10, _errorCode)
{}
};
class SegmentNotPresent : public X86Fault
{
public:
SegmentNotPresent(uint32_t _errorCode) :
X86Fault("Segment-Not-Present", "#NP", 11, _errorCode)
{}
};
class StackFault : public X86Fault
{
public:
StackFault(uint32_t _errorCode) :
X86Fault("Stack", "#SS", 12, _errorCode)
{}
};
class GeneralProtection : public X86Fault
{
public:
GeneralProtection(uint32_t _errorCode) :
X86Fault("General-Protection", "#GP", 13, _errorCode)
{}
};
class PageFault : public X86Fault
{
protected:
BitUnion32(PageFaultErrorCode)
Bitfield<0> present;
Bitfield<1> write;
Bitfield<2> user;
Bitfield<3> reserved;
Bitfield<4> fetch;
EndBitUnion(PageFaultErrorCode)
Addr addr;
public:
PageFault(Addr _addr, uint32_t _errorCode) :
X86Fault("Page-Fault", "#PF", 14, _errorCode), addr(_addr)
{}
PageFault(Addr _addr, bool present, BaseTLB::Mode mode,
bool user, bool reserved) :
X86Fault("Page-Fault", "#PF", 14, 0), addr(_addr)
{
PageFaultErrorCode code = 0;
code.present = present;
code.write = (mode == BaseTLB::Write);
code.user = user;
code.reserved = reserved;
code.fetch = (mode == BaseTLB::Execute);
errorCode = code;
}
void invoke(ThreadContext * tc,
StaticInstPtr inst = StaticInst::nullStaticInstPtr);
virtual std::string describe() const;
};
class X87FpExceptionPending : public X86Fault
{
public:
X87FpExceptionPending() :
X86Fault("x87 Floating-Point Exception Pending", "#MF", 16)
{}
};
class AlignmentCheck : public X86Fault
{
public:
AlignmentCheck() :
X86Fault("Alignment-Check", "#AC", 17, 0)
{}
};
class MachineCheck : public X86Abort
{
public:
MachineCheck() :
X86Abort("Machine-Check", "#MC", 18)
{}
};
class SIMDFloatingPointFault : public X86Fault
{
public:
SIMDFloatingPointFault() :
X86Fault("SIMD Floating-Point", "#XF", 19)
{}
};
class SecurityException : public X86FaultBase
{
public:
SecurityException() :
X86FaultBase("Security Exception", "#SX", 30)
{}
};
class ExternalInterrupt : public X86Interrupt
{
public:
ExternalInterrupt(uint8_t _vector) :
X86Interrupt("External Interrupt", "#INTR", _vector)
{}
};
class SystemManagementInterrupt : public X86Interrupt
{
public:
SystemManagementInterrupt() :
X86Interrupt("System Management Interrupt", "#SMI", 0)
{}
};
class InitInterrupt : public X86Interrupt
{
public:
InitInterrupt(uint8_t _vector) :
X86Interrupt("INIT Interrupt", "#INIT", _vector)
{}
void invoke(ThreadContext * tc,
StaticInstPtr inst = StaticInst::nullStaticInstPtr);
};
class StartupInterrupt : public X86Interrupt
{
public:
StartupInterrupt(uint8_t _vector) :
X86Interrupt("Startup Interrupt", "#SIPI", _vector)
{}
void invoke(ThreadContext * tc,
StaticInstPtr inst = StaticInst::nullStaticInstPtr);
};
class SoftwareInterrupt : public X86Interrupt
{
public:
SoftwareInterrupt(uint8_t _vector) :
X86Interrupt("Software Interrupt", "#INTR", _vector)
{}
bool isSoft()
{
return true;
}
};
}
#endif // __ARCH_X86_FAULTS_HH__
<commit_msg>x86: Expose the interrupt vector in faults<commit_after>/*
* Copyright (c) 2007 The Hewlett-Packard Development Company
* All rights reserved.
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Gabe Black
*/
#ifndef __ARCH_X86_FAULTS_HH__
#define __ARCH_X86_FAULTS_HH__
#include <string>
#include "base/bitunion.hh"
#include "base/misc.hh"
#include "sim/faults.hh"
#include "sim/tlb.hh"
namespace X86ISA
{
// Base class for all x86 "faults" where faults is in the m5 sense
class X86FaultBase : public FaultBase
{
protected:
const char * faultName;
const char * mnem;
uint8_t vector;
uint64_t errorCode;
X86FaultBase(const char * _faultName, const char * _mnem,
const uint8_t _vector, uint64_t _errorCode = (uint64_t)-1)
: faultName(_faultName), mnem(_mnem),
vector(_vector), errorCode(_errorCode)
{
}
const char * name() const
{
return faultName;
}
virtual bool isBenign()
{
return true;
}
virtual const char * mnemonic() const
{
return mnem;
}
virtual bool isSoft()
{
return false;
}
void invoke(ThreadContext * tc,
StaticInstPtr inst = StaticInst::nullStaticInstPtr);
virtual std::string describe() const;
public:
/**
* Get the vector of an interrupt.
*
* @return interrupt vector number.
*/
virtual uint8_t getVector() const { return vector; }
};
// Base class for x86 faults which behave as if the underlying instruction
// didn't happen.
class X86Fault : public X86FaultBase
{
protected:
X86Fault(const char * name, const char * mnem,
const uint8_t vector, uint64_t _errorCode = (uint64_t)-1)
: X86FaultBase(name, mnem, vector, _errorCode)
{}
};
// Base class for x86 traps which behave as if the underlying instruction
// completed.
class X86Trap : public X86FaultBase
{
protected:
X86Trap(const char * name, const char * mnem,
const uint8_t vector, uint64_t _errorCode = (uint64_t)-1)
: X86FaultBase(name, mnem, vector, _errorCode)
{}
void invoke(ThreadContext * tc,
StaticInstPtr inst = StaticInst::nullStaticInstPtr);
};
// Base class for x86 aborts which seem to be catastrophic failures.
class X86Abort : public X86FaultBase
{
protected:
X86Abort(const char * name, const char * mnem,
const uint8_t vector, uint64_t _errorCode = (uint64_t)-1)
: X86FaultBase(name, mnem, vector, _errorCode)
{}
void invoke(ThreadContext * tc,
StaticInstPtr inst = StaticInst::nullStaticInstPtr);
};
// Base class for x86 interrupts.
class X86Interrupt : public X86FaultBase
{
protected:
X86Interrupt(const char * name, const char * mnem,
const uint8_t _vector, uint64_t _errorCode = (uint64_t)-1)
: X86FaultBase(name, mnem, _vector, _errorCode)
{}
};
class UnimpInstFault : public FaultBase
{
public:
const char * name() const
{
return "unimplemented_micro";
}
void invoke(ThreadContext * tc,
StaticInstPtr inst = StaticInst::nullStaticInstPtr)
{
panic("Unimplemented instruction!");
}
};
// Below is a summary of the interrupt/exception information in the
// architecture manuals.
// Class | Type | vector | Cause | mnem
//------------------------------------------------------------------------
//Contrib Fault 0 Divide-by-Zero-Error #DE
//Benign Either 1 Debug #DB
//Benign Interrupt 2 Non-Maskable-Interrupt #NMI
//Benign Trap 3 Breakpoint #BP
//Benign Trap 4 Overflow #OF
//Benign Fault 5 Bound-Range #BR
//Benign Fault 6 Invalid-Opcode #UD
//Benign Fault 7 Device-Not-Available #NM
//Benign Abort 8 Double-Fault #DF
// 9 Coprocessor-Segment-Overrun
//Contrib Fault 10 Invalid-TSS #TS
//Contrib Fault 11 Segment-Not-Present #NP
//Contrib Fault 12 Stack #SS
//Contrib Fault 13 General-Protection #GP
//Either Fault 14 Page-Fault #PF
// 15 Reserved
//Benign Fault 16 x87 Floating-Point Exception Pending #MF
//Benign Fault 17 Alignment-Check #AC
//Benign Abort 18 Machine-Check #MC
//Benign Fault 19 SIMD Floating-Point #XF
// 20-29 Reserved
//Contrib ? 30 Security Exception #SX
// 31 Reserved
//Benign Interrupt 0-255 External Interrupts #INTR
//Benign Interrupt 0-255 Software Interrupts INTn
class DivideByZero : public X86Fault
{
public:
DivideByZero() :
X86Fault("Divide-by-Zero-Error", "#DE", 0)
{}
};
class DebugException : public X86FaultBase
{
public:
DebugException() :
X86FaultBase("Debug", "#DB", 1)
{}
};
class NonMaskableInterrupt : public X86Interrupt
{
public:
NonMaskableInterrupt(uint8_t _vector) :
X86Interrupt("Non Maskable Interrupt", "#NMI", 2, _vector)
{}
};
class Breakpoint : public X86Trap
{
public:
Breakpoint() :
X86Trap("Breakpoint", "#BP", 3)
{}
};
class OverflowTrap : public X86Trap
{
public:
OverflowTrap() :
X86Trap("Overflow", "#OF", 4)
{}
};
class BoundRange : public X86Fault
{
public:
BoundRange() :
X86Fault("Bound-Range", "#BR", 5)
{}
};
class InvalidOpcode : public X86Fault
{
public:
InvalidOpcode() :
X86Fault("Invalid-Opcode", "#UD", 6)
{}
void invoke(ThreadContext * tc,
StaticInstPtr inst = StaticInst::nullStaticInstPtr);
};
class DeviceNotAvailable : public X86Fault
{
public:
DeviceNotAvailable() :
X86Fault("Device-Not-Available", "#NM", 7)
{}
};
class DoubleFault : public X86Abort
{
public:
DoubleFault() :
X86Abort("Double-Fault", "#DF", 8, 0)
{}
};
class InvalidTSS : public X86Fault
{
public:
InvalidTSS(uint32_t _errorCode) :
X86Fault("Invalid-TSS", "#TS", 10, _errorCode)
{}
};
class SegmentNotPresent : public X86Fault
{
public:
SegmentNotPresent(uint32_t _errorCode) :
X86Fault("Segment-Not-Present", "#NP", 11, _errorCode)
{}
};
class StackFault : public X86Fault
{
public:
StackFault(uint32_t _errorCode) :
X86Fault("Stack", "#SS", 12, _errorCode)
{}
};
class GeneralProtection : public X86Fault
{
public:
GeneralProtection(uint32_t _errorCode) :
X86Fault("General-Protection", "#GP", 13, _errorCode)
{}
};
class PageFault : public X86Fault
{
protected:
BitUnion32(PageFaultErrorCode)
Bitfield<0> present;
Bitfield<1> write;
Bitfield<2> user;
Bitfield<3> reserved;
Bitfield<4> fetch;
EndBitUnion(PageFaultErrorCode)
Addr addr;
public:
PageFault(Addr _addr, uint32_t _errorCode) :
X86Fault("Page-Fault", "#PF", 14, _errorCode), addr(_addr)
{}
PageFault(Addr _addr, bool present, BaseTLB::Mode mode,
bool user, bool reserved) :
X86Fault("Page-Fault", "#PF", 14, 0), addr(_addr)
{
PageFaultErrorCode code = 0;
code.present = present;
code.write = (mode == BaseTLB::Write);
code.user = user;
code.reserved = reserved;
code.fetch = (mode == BaseTLB::Execute);
errorCode = code;
}
void invoke(ThreadContext * tc,
StaticInstPtr inst = StaticInst::nullStaticInstPtr);
virtual std::string describe() const;
};
class X87FpExceptionPending : public X86Fault
{
public:
X87FpExceptionPending() :
X86Fault("x87 Floating-Point Exception Pending", "#MF", 16)
{}
};
class AlignmentCheck : public X86Fault
{
public:
AlignmentCheck() :
X86Fault("Alignment-Check", "#AC", 17, 0)
{}
};
class MachineCheck : public X86Abort
{
public:
MachineCheck() :
X86Abort("Machine-Check", "#MC", 18)
{}
};
class SIMDFloatingPointFault : public X86Fault
{
public:
SIMDFloatingPointFault() :
X86Fault("SIMD Floating-Point", "#XF", 19)
{}
};
class SecurityException : public X86FaultBase
{
public:
SecurityException() :
X86FaultBase("Security Exception", "#SX", 30)
{}
};
class ExternalInterrupt : public X86Interrupt
{
public:
ExternalInterrupt(uint8_t _vector) :
X86Interrupt("External Interrupt", "#INTR", _vector)
{}
};
class SystemManagementInterrupt : public X86Interrupt
{
public:
SystemManagementInterrupt() :
X86Interrupt("System Management Interrupt", "#SMI", 0)
{}
};
class InitInterrupt : public X86Interrupt
{
public:
InitInterrupt(uint8_t _vector) :
X86Interrupt("INIT Interrupt", "#INIT", _vector)
{}
void invoke(ThreadContext * tc,
StaticInstPtr inst = StaticInst::nullStaticInstPtr);
};
class StartupInterrupt : public X86Interrupt
{
public:
StartupInterrupt(uint8_t _vector) :
X86Interrupt("Startup Interrupt", "#SIPI", _vector)
{}
void invoke(ThreadContext * tc,
StaticInstPtr inst = StaticInst::nullStaticInstPtr);
};
class SoftwareInterrupt : public X86Interrupt
{
public:
SoftwareInterrupt(uint8_t _vector) :
X86Interrupt("Software Interrupt", "#INTR", _vector)
{}
bool isSoft()
{
return true;
}
};
}
#endif // __ARCH_X86_FAULTS_HH__
<|endoftext|>
|
<commit_before>#ifndef DESOLIN_TG_OBJECTS_HPP
#define DESOLIN_TG_OBJECTS_HPP
#include <boost/functional/hash.hpp>
#include <typeinfo>
#include <cassert>
#include <string>
#include <map>
#include <boost/format.hpp>
#include <TaskGraph>
#include <desolin/tg/Desolin_tg_fwd.hpp>
namespace desolin_internal
{
template<typename T_elementType>
class TGScalar
{
public:
virtual const TGScalarExpr<T_elementType> getExpression() const = 0;
virtual void setExpression(const TGScalarExpr<T_elementType>& e) = 0;
virtual void addExpression(const TGScalarExpr<T_elementType>& e) = 0;
virtual ~TGScalar() {}
virtual InternalScalar<T_elementType>* createInternalRep() const = 0;
virtual bool isParameter() const = 0;
virtual void addParameterMappings(InternalScalar<T_elementType>& internal, ParameterHolder& params) const = 0;
virtual std::size_t hashValue() const = 0;
};
template<typename T_elementType>
class TGVector
{
public:
virtual const TGScalarExpr<T_elementType> getExpression(const tg::TaskExpression& row) const = 0;
virtual void setExpression(const tg::TaskExpression& row, const TGScalarExpr<T_elementType>& e) = 0;
virtual void addExpression(const tg::TaskExpression& row, const TGScalarExpr<T_elementType>& e) = 0;
virtual int getRows() const = 0;
virtual ~TGVector() {}
virtual InternalVector<T_elementType>* createInternalRep() const = 0;
virtual bool isParameter() const = 0;
virtual void addParameterMappings(InternalVector<T_elementType>& internal, ParameterHolder& params) const = 0;
virtual std::size_t hashValue() const = 0;
};
template<typename T_elementType>
class TGMatrix
{
public:
virtual const TGScalarExpr<T_elementType> getExpression(const tg::TaskExpression& row, const tg::TaskExpression& col) const = 0;
virtual void setExpression(const tg::TaskExpression& row, const tg::TaskExpression& col, const TGScalarExpr<T_elementType>& e) = 0;
virtual void addExpression(const tg::TaskExpression& row, const tg::TaskExpression& col, const TGScalarExpr<T_elementType>& e) = 0;
virtual int getRows() const = 0;
virtual int getCols() const = 0;
virtual ~TGMatrix() {}
virtual InternalMatrix<T_elementType>* createInternalRep() const = 0;
virtual bool isParameter() const = 0;
virtual void addParameterMappings(InternalMatrix<T_elementType>& internal, ParameterHolder& params) const = 0;
virtual std::size_t hashValue() const = 0;
};
template<typename T_elementType>
class TGScalarExpr
{
const tg::TaskExpression expr;
public:
TGScalarExpr() : expr(0)
{
}
TGScalarExpr(const tg::TaskExpression& e) : expr(e)
{
}
inline const tg::TaskExpression getExpression() const
{
return expr;
}
inline const TGScalarExpr mul(const TGScalarExpr& right) const
{
return TGScalarExpr(expr*right.expr);
}
inline const TGScalarExpr div(const TGScalarExpr& right) const
{
return TGScalarExpr(expr/right.expr);
}
inline const TGScalarExpr add(const TGScalarExpr& right) const
{
return TGScalarExpr(expr+right.expr);
}
inline const TGScalarExpr sub(const TGScalarExpr& right) const
{
return TGScalarExpr(expr-right.expr);
}
inline const TGScalarExpr sqrt() const
{
return TGScalarExpr(tSqrt(expr));
}
inline const TGScalarExpr abs() const
{
return TGScalarExpr(tAbs(expr));
}
inline const TGScalarExpr negate() const
{
return TGScalarExpr(-expr);
}
};
template<typename T_elementType>
class TGConventionalScalar : public TGScalar<T_elementType>
{
friend class Mapper;
private:
const bool parameter;
const std::string name;
tg::TaskScalarVariable value;
static tg::TaskScalarVariable createValue(bool param, const std::string& name)
{
if (param)
{
tParameter(tVarNamedTemplateType(T_elementType, val, name.c_str()));
return val;
}
else
{
tVarNamedTemplateType(T_elementType, val, name.c_str());
return val;
}
}
static inline const std::string getPrefix()
{
return std::string("convScalar");
}
public:
TGConventionalScalar(NameGenerator& generator, const ConventionalScalar<T_elementType>& internal) : parameter(true), name(generator.getName(getPrefix())), value(createValue(true, name))
{
}
TGConventionalScalar(bool param, NameGenerator& generator, const ExprNode<scalar, T_elementType>& s) : parameter(param), name(generator.getName(getPrefix())), value(createValue(param, name))
{
}
const TGScalarExpr<T_elementType> getExpression() const
{
return TGScalarExpr<T_elementType>(value);
}
void setExpression(const TGScalarExpr<T_elementType>& e)
{
value = e.getExpression();
}
void addExpression(const TGScalarExpr<T_elementType>& e)
{
value += e.getExpression();
}
virtual InternalScalar<T_elementType>* createInternalRep() const
{
assert(parameter);
return new ConventionalScalar<T_elementType>();
}
virtual bool isParameter() const
{
return parameter;
}
virtual std::size_t hashValue() const
{
std::size_t seed = boost::hash<std::string>()(typeid(*this).name());
boost::hash_combine(seed, parameter);
return seed;
}
virtual void addParameterMappings(InternalScalar<T_elementType>& internal, ParameterHolder& params) const
{
assert(parameter);
Mapper mapper(*this, params);
internal.accept(mapper);
}
class Mapper : public InternalScalarVisitor<T_elementType>
{
private:
const TGConventionalScalar<T_elementType>& internal;
ParameterHolder& parameterHolder;
public:
Mapper(const TGConventionalScalar<T_elementType>& i, ParameterHolder& p) : internal(i), parameterHolder(p)
{
}
virtual void visit(ConventionalScalar<T_elementType>& s)
{
assert(s.isAllocated());
parameterHolder.addParameter(internal.name, s.getValue());
}
};
};
template<typename T_elementType>
class TGConventionalVector : public TGVector<T_elementType>
{
private:
const bool parameter;
const std::string name;
const int rows;
tg::TaskArray<1> value;
static tg::TaskArray<1> createValue(bool param, const std::string& name, int rows)
{
unsigned dims[1] = {rows};
if (param)
{
tParameter(tArrayFromListNamed(T_elementType, val, 1, dims, name.c_str()));
return val;
}
else
{
tArrayFromListNamed(T_elementType, val, 1, dims, name.c_str());
return val;
}
}
static inline const std::string getPrefix()
{
return std::string("convVector");
}
public:
TGConventionalVector(NameGenerator& generator, const ConventionalVector<T_elementType>& internal) : parameter(true), name(generator.getName(getPrefix())), rows(internal.getRowCount()), value(createValue(true, name, rows))
{
}
TGConventionalVector(bool param, NameGenerator& generator, const ExprNode<vector, T_elementType>& v) : parameter(param), name(generator.getName(getPrefix())), rows(v.getRowCount()), value(createValue(param, name, rows))
{
}
const TGScalarExpr<T_elementType> getExpression(const tg::TaskExpression& row) const
{
return TGScalarExpr<T_elementType>(value[row]);
}
void setExpression(const tg::TaskExpression& row, const TGScalarExpr<T_elementType>& e)
{
value[row] = e.getExpression();
}
void addExpression(const tg::TaskExpression& row, const TGScalarExpr<T_elementType>& e)
{
value[row] += e.getExpression();
}
virtual int getRows() const
{
return rows;
}
virtual InternalVector<T_elementType>* createInternalRep() const
{
assert(parameter);
return new ConventionalVector<T_elementType>(rows);
}
virtual bool isParameter() const
{
return parameter;
}
virtual void addParameterMappings(InternalVector<T_elementType>& internal, ParameterHolder& params) const
{
assert(parameter);
Mapper mapper(*this, params);
internal.accept(mapper);
}
virtual std::size_t hashValue() const
{
std::size_t seed = boost::hash<std::string>()(typeid(*this).name());
boost::hash_combine(seed, parameter);
boost::hash_combine(seed, rows);
return seed;
}
class Mapper : public InternalVectorVisitor<T_elementType>
{
private:
const TGConventionalVector<T_elementType>& internal;
ParameterHolder& parameterHolder;
public:
Mapper(const TGConventionalVector<T_elementType>& i, ParameterHolder& p) : internal(i), parameterHolder(p)
{
}
virtual void visit(ConventionalVector<T_elementType>& v)
{
assert(v.isAllocated());
parameterHolder.addParameter(internal.name, v.getValue());
}
};
};
template<typename T_elementType>
class TGConventionalMatrix : public TGMatrix<T_elementType>
{
private:
const bool parameter;
const std::string name;
const int rows;
const int cols;
tg::TaskArray<2> value;
static tg::TaskArray<2> createValue(bool param, const std::string& name, int rows, int cols)
{
unsigned dims[2] = {rows, cols};
if (param)
{
tParameter(tArrayFromListNamed(T_elementType, val, 2, dims, name.c_str()));
return val;
}
else
{
tArrayFromListNamed(T_elementType, val, 2, dims, name.c_str());
return val;
}
}
static inline const std::string getPrefix()
{
return std::string("convMatrix");
}
public:
TGConventionalMatrix(NameGenerator& generator, ConventionalMatrix<T_elementType>& internal) : parameter(true), name(generator.getName(getPrefix())), rows(internal.getRowCount()), cols(internal.getColCount()), value(createValue(true, name, rows, cols))
{
}
TGConventionalMatrix(bool param, NameGenerator& generator, const ExprNode<matrix, T_elementType>& m) : parameter(param), name(generator.getName(getPrefix())), rows(m.getRowCount()), cols(m.getColCount()), value(createValue(param, name, rows, cols))
{
}
const TGScalarExpr<T_elementType> getExpression(const tg::TaskExpression& row, const tg::TaskExpression& col) const
{
return TGScalarExpr<T_elementType>(value[row][col]);
}
void setExpression(const tg::TaskExpression& row, const tg::TaskExpression& col, const TGScalarExpr<T_elementType>& e)
{
value[row][col] = e.getExpression();
}
void addExpression(const tg::TaskExpression& row, const tg::TaskExpression& col, const TGScalarExpr<T_elementType>& e)
{
value[row][col] += e.getExpression();
}
virtual int getRows() const
{
return rows;
}
virtual int getCols() const
{
return cols;
}
virtual InternalMatrix<T_elementType>* createInternalRep() const
{
assert(parameter);
return new ConventionalMatrix<T_elementType>(rows, cols);
}
virtual bool isParameter() const
{
return parameter;
}
virtual void addParameterMappings(InternalMatrix<T_elementType>& internal, ParameterHolder& params) const
{
assert(parameter);
Mapper mapper(*this, params);
internal.accept(mapper);
}
virtual std::size_t hashValue() const
{
std::size_t seed = boost::hash<std::string>()(typeid(*this).name());
boost::hash_combine(seed, parameter);
boost::hash_combine(seed, rows);
boost::hash_combine(seed, cols);
return seed;
}
class Mapper : public InternalMatrixVisitor<T_elementType>
{
private:
const TGConventionalMatrix<T_elementType>& internal;
ParameterHolder& parameterHolder;
public:
Mapper(const TGConventionalMatrix<T_elementType>& i, ParameterHolder& p) : internal(i), parameterHolder(p)
{
}
virtual void visit(ConventionalMatrix<T_elementType>& m)
{
assert(m.isAllocated());
parameterHolder.addParameter(internal.name, m.getValue());
}
};
};
template<typename T_elementType>
class TGMatrixGen : public InternalMatrixVisitor<T_elementType>
{
NameGenerator& generator;
TGMatrix<T_elementType>* result;
public:
TGMatrixGen(NameGenerator& g) : generator(g)
{
}
void visit(ConventionalMatrix<T_elementType>& m)
{
result = new TGConventionalMatrix<T_elementType>(generator, m);
}
TGMatrix<T_elementType>* getResult() const
{
assert(result != NULL);
return result;
}
};
template<typename T_elementType>
class TGVectorGen : public InternalVectorVisitor<T_elementType>
{
NameGenerator& generator;
TGVector<T_elementType>* result;
public:
TGVectorGen(NameGenerator& g) : generator(g)
{
}
void visit(ConventionalVector<T_elementType>& m)
{
result = new TGConventionalVector<T_elementType>(generator, m);
}
TGVector<T_elementType>* getResult() const
{
assert(result != NULL);
return result;
}
};
template<typename T_elementType>
class TGScalarGen : public InternalScalarVisitor<T_elementType>
{
NameGenerator& generator;
TGScalar<T_elementType>* result;
public:
TGScalarGen(NameGenerator& g) : generator(g)
{
}
void visit(ConventionalScalar<T_elementType>& m)
{
result = new TGConventionalScalar<T_elementType>(generator, m);
}
TGScalar<T_elementType>* getResult() const
{
assert(result != NULL);
return result;
}
};
}
#endif
<commit_msg>Added name hashing to TaskGraph internal reprentation hashes.<commit_after>#ifndef DESOLIN_TG_OBJECTS_HPP
#define DESOLIN_TG_OBJECTS_HPP
#include <boost/functional/hash.hpp>
#include <typeinfo>
#include <cassert>
#include <string>
#include <map>
#include <boost/format.hpp>
#include <TaskGraph>
#include <desolin/tg/Desolin_tg_fwd.hpp>
namespace desolin_internal
{
template<typename T_elementType>
class TGScalar
{
public:
virtual const TGScalarExpr<T_elementType> getExpression() const = 0;
virtual void setExpression(const TGScalarExpr<T_elementType>& e) = 0;
virtual void addExpression(const TGScalarExpr<T_elementType>& e) = 0;
virtual ~TGScalar() {}
virtual InternalScalar<T_elementType>* createInternalRep() const = 0;
virtual bool isParameter() const = 0;
virtual void addParameterMappings(InternalScalar<T_elementType>& internal, ParameterHolder& params) const = 0;
virtual std::size_t hashValue() const = 0;
};
template<typename T_elementType>
class TGVector
{
public:
virtual const TGScalarExpr<T_elementType> getExpression(const tg::TaskExpression& row) const = 0;
virtual void setExpression(const tg::TaskExpression& row, const TGScalarExpr<T_elementType>& e) = 0;
virtual void addExpression(const tg::TaskExpression& row, const TGScalarExpr<T_elementType>& e) = 0;
virtual int getRows() const = 0;
virtual ~TGVector() {}
virtual InternalVector<T_elementType>* createInternalRep() const = 0;
virtual bool isParameter() const = 0;
virtual void addParameterMappings(InternalVector<T_elementType>& internal, ParameterHolder& params) const = 0;
virtual std::size_t hashValue() const = 0;
};
template<typename T_elementType>
class TGMatrix
{
public:
virtual const TGScalarExpr<T_elementType> getExpression(const tg::TaskExpression& row, const tg::TaskExpression& col) const = 0;
virtual void setExpression(const tg::TaskExpression& row, const tg::TaskExpression& col, const TGScalarExpr<T_elementType>& e) = 0;
virtual void addExpression(const tg::TaskExpression& row, const tg::TaskExpression& col, const TGScalarExpr<T_elementType>& e) = 0;
virtual int getRows() const = 0;
virtual int getCols() const = 0;
virtual ~TGMatrix() {}
virtual InternalMatrix<T_elementType>* createInternalRep() const = 0;
virtual bool isParameter() const = 0;
virtual void addParameterMappings(InternalMatrix<T_elementType>& internal, ParameterHolder& params) const = 0;
virtual std::size_t hashValue() const = 0;
};
template<typename T_elementType>
class TGScalarExpr
{
const tg::TaskExpression expr;
public:
TGScalarExpr() : expr(0)
{
}
TGScalarExpr(const tg::TaskExpression& e) : expr(e)
{
}
inline const tg::TaskExpression getExpression() const
{
return expr;
}
inline const TGScalarExpr mul(const TGScalarExpr& right) const
{
return TGScalarExpr(expr*right.expr);
}
inline const TGScalarExpr div(const TGScalarExpr& right) const
{
return TGScalarExpr(expr/right.expr);
}
inline const TGScalarExpr add(const TGScalarExpr& right) const
{
return TGScalarExpr(expr+right.expr);
}
inline const TGScalarExpr sub(const TGScalarExpr& right) const
{
return TGScalarExpr(expr-right.expr);
}
inline const TGScalarExpr sqrt() const
{
return TGScalarExpr(tSqrt(expr));
}
inline const TGScalarExpr abs() const
{
return TGScalarExpr(tAbs(expr));
}
inline const TGScalarExpr negate() const
{
return TGScalarExpr(-expr);
}
};
template<typename T_elementType>
class TGConventionalScalar : public TGScalar<T_elementType>
{
friend class Mapper;
private:
const bool parameter;
const std::string name;
tg::TaskScalarVariable value;
static tg::TaskScalarVariable createValue(bool param, const std::string& name)
{
if (param)
{
tParameter(tVarNamedTemplateType(T_elementType, val, name.c_str()));
return val;
}
else
{
tVarNamedTemplateType(T_elementType, val, name.c_str());
return val;
}
}
static inline const std::string getPrefix()
{
return std::string("convScalar");
}
public:
TGConventionalScalar(NameGenerator& generator, const ConventionalScalar<T_elementType>& internal) : parameter(true), name(generator.getName(getPrefix())), value(createValue(true, name))
{
}
TGConventionalScalar(bool param, NameGenerator& generator, const ExprNode<scalar, T_elementType>& s) : parameter(param), name(generator.getName(getPrefix())), value(createValue(param, name))
{
}
const TGScalarExpr<T_elementType> getExpression() const
{
return TGScalarExpr<T_elementType>(value);
}
void setExpression(const TGScalarExpr<T_elementType>& e)
{
value = e.getExpression();
}
void addExpression(const TGScalarExpr<T_elementType>& e)
{
value += e.getExpression();
}
virtual InternalScalar<T_elementType>* createInternalRep() const
{
assert(parameter);
return new ConventionalScalar<T_elementType>();
}
virtual bool isParameter() const
{
return parameter;
}
virtual std::size_t hashValue() const
{
std::size_t seed = boost::hash<std::string>()(typeid(*this).name());
boost::hash_combine(seed, parameter);
boost::hash_combine(seed, name);
return seed;
}
virtual void addParameterMappings(InternalScalar<T_elementType>& internal, ParameterHolder& params) const
{
assert(parameter);
Mapper mapper(*this, params);
internal.accept(mapper);
}
class Mapper : public InternalScalarVisitor<T_elementType>
{
private:
const TGConventionalScalar<T_elementType>& internal;
ParameterHolder& parameterHolder;
public:
Mapper(const TGConventionalScalar<T_elementType>& i, ParameterHolder& p) : internal(i), parameterHolder(p)
{
}
virtual void visit(ConventionalScalar<T_elementType>& s)
{
assert(s.isAllocated());
parameterHolder.addParameter(internal.name, s.getValue());
}
};
};
template<typename T_elementType>
class TGConventionalVector : public TGVector<T_elementType>
{
private:
const bool parameter;
const std::string name;
const int rows;
tg::TaskArray<1> value;
static tg::TaskArray<1> createValue(bool param, const std::string& name, int rows)
{
unsigned dims[1] = {rows};
if (param)
{
tParameter(tArrayFromListNamed(T_elementType, val, 1, dims, name.c_str()));
return val;
}
else
{
tArrayFromListNamed(T_elementType, val, 1, dims, name.c_str());
return val;
}
}
static inline const std::string getPrefix()
{
return std::string("convVector");
}
public:
TGConventionalVector(NameGenerator& generator, const ConventionalVector<T_elementType>& internal) : parameter(true), name(generator.getName(getPrefix())), rows(internal.getRowCount()), value(createValue(true, name, rows))
{
}
TGConventionalVector(bool param, NameGenerator& generator, const ExprNode<vector, T_elementType>& v) : parameter(param), name(generator.getName(getPrefix())), rows(v.getRowCount()), value(createValue(param, name, rows))
{
}
const TGScalarExpr<T_elementType> getExpression(const tg::TaskExpression& row) const
{
return TGScalarExpr<T_elementType>(value[row]);
}
void setExpression(const tg::TaskExpression& row, const TGScalarExpr<T_elementType>& e)
{
value[row] = e.getExpression();
}
void addExpression(const tg::TaskExpression& row, const TGScalarExpr<T_elementType>& e)
{
value[row] += e.getExpression();
}
virtual int getRows() const
{
return rows;
}
virtual InternalVector<T_elementType>* createInternalRep() const
{
assert(parameter);
return new ConventionalVector<T_elementType>(rows);
}
virtual bool isParameter() const
{
return parameter;
}
virtual void addParameterMappings(InternalVector<T_elementType>& internal, ParameterHolder& params) const
{
assert(parameter);
Mapper mapper(*this, params);
internal.accept(mapper);
}
virtual std::size_t hashValue() const
{
std::size_t seed = boost::hash<std::string>()(typeid(*this).name());
boost::hash_combine(seed, parameter);
boost::hash_combine(seed, rows);
boost::hash_combine(seed, name);
return seed;
}
class Mapper : public InternalVectorVisitor<T_elementType>
{
private:
const TGConventionalVector<T_elementType>& internal;
ParameterHolder& parameterHolder;
public:
Mapper(const TGConventionalVector<T_elementType>& i, ParameterHolder& p) : internal(i), parameterHolder(p)
{
}
virtual void visit(ConventionalVector<T_elementType>& v)
{
assert(v.isAllocated());
parameterHolder.addParameter(internal.name, v.getValue());
}
};
};
template<typename T_elementType>
class TGConventionalMatrix : public TGMatrix<T_elementType>
{
private:
const bool parameter;
const std::string name;
const int rows;
const int cols;
tg::TaskArray<2> value;
static tg::TaskArray<2> createValue(bool param, const std::string& name, int rows, int cols)
{
unsigned dims[2] = {rows, cols};
if (param)
{
tParameter(tArrayFromListNamed(T_elementType, val, 2, dims, name.c_str()));
return val;
}
else
{
tArrayFromListNamed(T_elementType, val, 2, dims, name.c_str());
return val;
}
}
static inline const std::string getPrefix()
{
return std::string("convMatrix");
}
public:
TGConventionalMatrix(NameGenerator& generator, ConventionalMatrix<T_elementType>& internal) : parameter(true), name(generator.getName(getPrefix())), rows(internal.getRowCount()), cols(internal.getColCount()), value(createValue(true, name, rows, cols))
{
}
TGConventionalMatrix(bool param, NameGenerator& generator, const ExprNode<matrix, T_elementType>& m) : parameter(param), name(generator.getName(getPrefix())), rows(m.getRowCount()), cols(m.getColCount()), value(createValue(param, name, rows, cols))
{
}
const TGScalarExpr<T_elementType> getExpression(const tg::TaskExpression& row, const tg::TaskExpression& col) const
{
return TGScalarExpr<T_elementType>(value[row][col]);
}
void setExpression(const tg::TaskExpression& row, const tg::TaskExpression& col, const TGScalarExpr<T_elementType>& e)
{
value[row][col] = e.getExpression();
}
void addExpression(const tg::TaskExpression& row, const tg::TaskExpression& col, const TGScalarExpr<T_elementType>& e)
{
value[row][col] += e.getExpression();
}
virtual int getRows() const
{
return rows;
}
virtual int getCols() const
{
return cols;
}
virtual InternalMatrix<T_elementType>* createInternalRep() const
{
assert(parameter);
return new ConventionalMatrix<T_elementType>(rows, cols);
}
virtual bool isParameter() const
{
return parameter;
}
virtual void addParameterMappings(InternalMatrix<T_elementType>& internal, ParameterHolder& params) const
{
assert(parameter);
Mapper mapper(*this, params);
internal.accept(mapper);
}
virtual std::size_t hashValue() const
{
std::size_t seed = boost::hash<std::string>()(typeid(*this).name());
boost::hash_combine(seed, parameter);
boost::hash_combine(seed, rows);
boost::hash_combine(seed, cols);
boost::hash_combine(sees, name);
return seed;
}
class Mapper : public InternalMatrixVisitor<T_elementType>
{
private:
const TGConventionalMatrix<T_elementType>& internal;
ParameterHolder& parameterHolder;
public:
Mapper(const TGConventionalMatrix<T_elementType>& i, ParameterHolder& p) : internal(i), parameterHolder(p)
{
}
virtual void visit(ConventionalMatrix<T_elementType>& m)
{
assert(m.isAllocated());
parameterHolder.addParameter(internal.name, m.getValue());
}
};
};
template<typename T_elementType>
class TGMatrixGen : public InternalMatrixVisitor<T_elementType>
{
NameGenerator& generator;
TGMatrix<T_elementType>* result;
public:
TGMatrixGen(NameGenerator& g) : generator(g)
{
}
void visit(ConventionalMatrix<T_elementType>& m)
{
result = new TGConventionalMatrix<T_elementType>(generator, m);
}
TGMatrix<T_elementType>* getResult() const
{
assert(result != NULL);
return result;
}
};
template<typename T_elementType>
class TGVectorGen : public InternalVectorVisitor<T_elementType>
{
NameGenerator& generator;
TGVector<T_elementType>* result;
public:
TGVectorGen(NameGenerator& g) : generator(g)
{
}
void visit(ConventionalVector<T_elementType>& m)
{
result = new TGConventionalVector<T_elementType>(generator, m);
}
TGVector<T_elementType>* getResult() const
{
assert(result != NULL);
return result;
}
};
template<typename T_elementType>
class TGScalarGen : public InternalScalarVisitor<T_elementType>
{
NameGenerator& generator;
TGScalar<T_elementType>* result;
public:
TGScalarGen(NameGenerator& g) : generator(g)
{
}
void visit(ConventionalScalar<T_elementType>& m)
{
result = new TGConventionalScalar<T_elementType>(generator, m);
}
TGScalar<T_elementType>* getResult() const
{
assert(result != NULL);
return result;
}
};
}
#endif
<|endoftext|>
|
<commit_before>/**
* These codes are licensed under the Unlicense.
* http://unlicense.org
*/
#ifndef COMMATA_GUARD_F6071085_9476_4724_95ED_E1DA376E837C
#define COMMATA_GUARD_F6071085_9476_4724_95ED_E1DA376E837C
#include <memory>
#include <type_traits>
#include <utility>
#include "member_like_base.hpp"
namespace commata {
namespace detail {
template <class A, class = void>
struct reference_forwarded
{
using type = typename A::value_type&;
};
template <class A>
struct reference_forwarded<A, typename A::reference>
{
using type = typename A::reference;
};
template <class A, class = void>
struct const_reference_forwarded
{
using type = const typename A::value_type&;
};
template <class A>
struct const_reference_forwarded<A, typename A::const_reference>
{
using type = typename A::const_reference;
};
template <class Allocator>
class allocation_only_allocator :
member_like_base<Allocator>
{
using base_traits = typename std::allocator_traits<Allocator>;
// To rebind
template <class Allocator2>
friend class allocation_only_allocator;
public:
using pointer = typename base_traits::pointer;
using const_pointer = typename base_traits::const_pointer;
using void_pointer = typename base_traits::void_pointer;
using const_void_pointer = typename base_traits::const_void_pointer;
using value_type = typename base_traits::value_type;
using size_type = typename base_traits::size_type;
using difference_type = typename base_traits::difference_type;
// These types are not required by the C++14 standard, but
// std::basic_string which comes with gcc 7.3.1 seems to do
using reference = typename reference_forwarded<Allocator>::type;
using const_reference =
typename const_reference_forwarded<Allocator>::type;
template <class U>
struct rebind
{
using other = allocation_only_allocator<
typename base_traits::template rebind_alloc<U>>;
};
// Default-constructibility of an allocator is not mandated by the C++14
// standard, but std::basic_string which comes with gcc 7.3.1 requires it
allocation_only_allocator() noexcept
{}
// To make wrappers
explicit allocation_only_allocator(const Allocator& other) noexcept :
member_like_base<Allocator>(other)
{}
// ditto
explicit allocation_only_allocator(Allocator&& other) noexcept :
member_like_base<Allocator>(std::move(other))
{}
// To make rebound copies
template <class Allocator2>
explicit allocation_only_allocator(
const allocation_only_allocator<Allocator2>& other) noexcept :
member_like_base<Allocator>(Allocator(other.get()))
{}
// C++14 standard does not require this
template <class OtherAllocator>
allocation_only_allocator& operator=(
const allocation_only_allocator<OtherAllocator>& other)
noexcept(std::is_nothrow_assignable<
Allocator&, const OtherAllocator&>::value)
{
static_cast<Allocator&>(*this) = other;
return *this;
}
// ditto
template <class OtherAllocator>
allocation_only_allocator& operator=(
allocation_only_allocator<OtherAllocator>&& other)
noexcept(std::is_nothrow_assignable<
Allocator&, OtherAllocator>::value)
{
static_cast<Allocator&>(*this) = std::move(other);
return *this;
}
template <class... Args>
auto allocate(size_type n, Args&&... args)
{
return base_traits::allocate(base(),
n, std::forward<Args>(args)...);
}
auto deallocate(pointer p, size_type n) noexcept
{
return base_traits::deallocate(base(), p, n);
}
auto max_size() noexcept
{
return base_traits::max_size(base());
}
template <class T, class... Args>
void construct(T* p, Args&&... args)
{
::new(p) T(std::forward<Args>(args)...);
}
template <class T>
void destroy(T* p)
{
destroy(p, std::is_trivially_destructible<T>());
}
auto select_on_container_copy_construction() noexcept
{
return base_traits::select_on_container_copy_construction(base());
}
using propagate_on_container_copy_assignment =
typename base_traits::propagate_on_container_copy_assignment;
using propagate_on_container_move_assignment =
typename base_traits::propagate_on_container_move_assignment;
using propagate_on_container_swap =
typename base_traits::propagate_on_container_swap;
decltype(auto) base() noexcept
{
return this->get();
}
decltype(auto) base() const noexcept
{
return this->get();
}
private:
template <class T>
void destroy(T*, std::true_type)
{}
template <class T>
void destroy(T* p, std::false_type)
{
p->~T();
}
};
template <class Allocator1, class Allocator2>
inline bool operator==(
const allocation_only_allocator<Allocator1>& left,
const allocation_only_allocator<Allocator2>& right) noexcept
{
return left.base() == right.base();
}
template <class Allocator1, class Allocator2>
inline bool operator!=(
const allocation_only_allocator<Allocator1>& left,
const allocation_only_allocator<Allocator2>& right) noexcept
{
return !(left == right);
}
}}
#endif
<commit_msg>Potential bug fix: add generous ctors to allocation_only_allocator<commit_after>/**
* These codes are licensed under the Unlicense.
* http://unlicense.org
*/
#ifndef COMMATA_GUARD_F6071085_9476_4724_95ED_E1DA376E837C
#define COMMATA_GUARD_F6071085_9476_4724_95ED_E1DA376E837C
#include <memory>
#include <type_traits>
#include <utility>
#include "member_like_base.hpp"
namespace commata {
namespace detail {
template <class A, class = void>
struct reference_forwarded
{
using type = typename A::value_type&;
};
template <class A>
struct reference_forwarded<A, typename A::reference>
{
using type = typename A::reference;
};
template <class A, class = void>
struct const_reference_forwarded
{
using type = const typename A::value_type&;
};
template <class A>
struct const_reference_forwarded<A, typename A::const_reference>
{
using type = typename A::const_reference;
};
template <class Allocator>
class allocation_only_allocator;
template <class T>
class is_allocation_only_allocator : std::false_type
{};
template <class Allocator>
class is_allocation_only_allocator<allocation_only_allocator<Allocator>> :
std::true_type
{};
template <class Allocator>
class allocation_only_allocator :
member_like_base<Allocator>
{
using base_traits = typename std::allocator_traits<Allocator>;
// To rebind
template <class Allocator2>
friend class allocation_only_allocator;
public:
using pointer = typename base_traits::pointer;
using const_pointer = typename base_traits::const_pointer;
using void_pointer = typename base_traits::void_pointer;
using const_void_pointer = typename base_traits::const_void_pointer;
using value_type = typename base_traits::value_type;
using size_type = typename base_traits::size_type;
using difference_type = typename base_traits::difference_type;
// These types are not required by the C++14 standard, but
// std::basic_string which comes with gcc 7.3.1 seems to do
using reference = typename reference_forwarded<Allocator>::type;
using const_reference =
typename const_reference_forwarded<Allocator>::type;
template <class U>
struct rebind
{
using other = allocation_only_allocator<
typename base_traits::template rebind_alloc<U>>;
};
// Default-constructibility of an allocator is not mandated by the C++14
// standard, but std::basic_string which comes with gcc 7.3.1 requires it
allocation_only_allocator() noexcept
{}
// To make wrappers
explicit allocation_only_allocator(const Allocator& other) noexcept :
member_like_base<Allocator>(other)
{}
// ditto
explicit allocation_only_allocator(Allocator&& other) noexcept :
member_like_base<Allocator>(std::move(other))
{}
// To make rebound copies
template <class Allocator2>
explicit allocation_only_allocator(
const allocation_only_allocator<Allocator2>& other) noexcept :
member_like_base<Allocator>(Allocator(other.get()))
{}
// ditto
template <class Allocator2,
std::enable_if_t<
!is_allocation_only_allocator<Allocator2>::value_type>>
explicit allocation_only_allocator(const Allocator2& other) noexcept :
member_like_base<Allocator>(
typename std::allocator_traits<Allocator2>::template
rebind_alloc<value_type>(other))
{}
// ditto
template <class Allocator2,
std::enable_if_t<
!is_allocation_only_allocator<Allocator2>::value_type>>
explicit allocation_only_allocator(Allocator2&& other) noexcept :
member_like_base<Allocator>(
typename std::allocator_traits<Allocator2>::template
rebind_alloc<value_type>(std::move(other)))
{}
// C++14 standard does not require this
template <class OtherAllocator>
allocation_only_allocator& operator=(
const allocation_only_allocator<OtherAllocator>& other)
noexcept(std::is_nothrow_assignable<
Allocator&, const OtherAllocator&>::value)
{
static_cast<Allocator&>(*this) = other;
return *this;
}
// ditto
template <class OtherAllocator>
allocation_only_allocator& operator=(
allocation_only_allocator<OtherAllocator>&& other)
noexcept(std::is_nothrow_assignable<
Allocator&, OtherAllocator>::value)
{
static_cast<Allocator&>(*this) = std::move(other);
return *this;
}
template <class... Args>
auto allocate(size_type n, Args&&... args)
{
return base_traits::allocate(base(),
n, std::forward<Args>(args)...);
}
auto deallocate(pointer p, size_type n) noexcept
{
return base_traits::deallocate(base(), p, n);
}
auto max_size() noexcept
{
return base_traits::max_size(base());
}
template <class T, class... Args>
void construct(T* p, Args&&... args)
{
::new(p) T(std::forward<Args>(args)...);
}
template <class T>
void destroy(T* p)
{
destroy(p, std::is_trivially_destructible<T>());
}
auto select_on_container_copy_construction() noexcept
{
return base_traits::select_on_container_copy_construction(base());
}
using propagate_on_container_copy_assignment =
typename base_traits::propagate_on_container_copy_assignment;
using propagate_on_container_move_assignment =
typename base_traits::propagate_on_container_move_assignment;
using propagate_on_container_swap =
typename base_traits::propagate_on_container_swap;
decltype(auto) base() noexcept
{
return this->get();
}
decltype(auto) base() const noexcept
{
return this->get();
}
private:
template <class T>
void destroy(T*, std::true_type)
{}
template <class T>
void destroy(T* p, std::false_type)
{
p->~T();
}
};
template <class Allocator1, class Allocator2>
inline bool operator==(
const allocation_only_allocator<Allocator1>& left,
const allocation_only_allocator<Allocator2>& right) noexcept
{
return left.base() == right.base();
}
template <class Allocator1, class Allocator2>
inline bool operator!=(
const allocation_only_allocator<Allocator1>& left,
const allocation_only_allocator<Allocator2>& right) noexcept
{
return !(left == right);
}
}}
#endif
<|endoftext|>
|
<commit_before>
/**
Sketch of the L1 ring buffer desired API -- what the RPC server would
look like.
*/
/*
For RPC write_chunks: we need to keep the assembled_chunks alive via
a shared_ptr. This can be achieved by the RPC server pulling
requests off the client-facing socket in one thread, retrieving
shared_ptrs to the assembled_chunks, and putting them in a
(thread-safe) queue which will keep the shared_ptrs alive. After
enqueuing a chunk + args, it should send a request to a back-end
worker to pull some work from the queue. The worker can dequeue the
assembled_chunk, msgpack it or otherwise write it to disk, and then
drop the shared_ptr.
ZMQ_DONTWAIT -- blocks on zmq_send when high-water-mark is reached (DEALER)
//#include <zmq.hpp>
*/
/*
For the telescoping time-sampling, we want to keep ~4 ring buffers.
The property they have is that as the oldest data are dropped off the
end of the ring buffer, we want to take two chunks and compile them
into one chunk. While this is happening, we still want to be able to
access them. (ie, the RPC callbacks should still know about them).
Each of these ~4 ring buffers should use a fixed amount of space; we
may want to re-use the assembled_chunk memory.
*/
/*
One idea: rather than explicitly "pinning" assembled_chunks, we could
use shared_ptr.unique() -- if only the ring buffer has a copy of the
shared_ptr, then that assembled_chunk can be dropped.
*/
/*
Another idea is to use the assembled_chunk (or a wrapper of it)'s
destructor to notify the ring buffer (or an allocator) that it is
being deleted.
*/
/*
For the telescoping chain, we want the ring buffer to tell us when an
assembled_chunk is being dropped.
*/
/*
assembled_chunk::make() is a factory for assembled_chunks.
assembled_chunk_ringbuf::_make_assembled_chunk() wraps that or calls directly
assembled_chunk_ringbuf holds active_chunk0 and active_chunk1
*outside* the ringbuf.
_put_assembled_chunk is where assembled_chunks get added to the ring buffer.
*/
/*
assembled_chunk_ringbuf: needs to allocate a new chunk when it
receives a packet with ichunk >= active_ichunk + 2.
Could do:
- try to allocate a new assembled_chunk. If that fails:
- if assembled_ringbuf_size == assembled_ringbuf_capacity,
then the buffer is full of chunks waiting for the consumer thread.
-> drop data? This means we keep the oldest data; alternative
would be to drop the oldest frame and keep the newest data
instead.
- iteratively: go to the next ringbuf position and drop that chunk
off the back -- call callback, then reset the shared_ptr. Then try
to allocate a new assembled_chunk. If resetting the shared_ptr
drop the last reference to an assembled_chunk, then that chunk will
become available. If not (eg, if RPC thread has a copy of the
shared_ptr), continue on to the next position. This process will
stop once we drop (assembled_ringbuf_capacity -
assembled_ringbuf_size) chunks -- ie, all the chunks left in the
buffer are the ones waiting to be consumed.
- there will be a callback for when a chunk is being dropped. This
is where we handle the telescoping: we'll hold zero or one older
chunks, and when a chunk is about to be dropped, if we had an older
one, then we can downsample the two and then enqueue the resulting
new chunk. This enqueue call could (typically will, in
steady-state) cause a cascade of dropping the oldest frame from the
next ring buffer.
- the longer-duration ring buffers do not have 'downstream'
consumers.
- Huh, what if the queue of assembled chunks waiting for the
downstream consumer and the ring buffer per se are two separate data
structures that each hold shared_ptrs?
- ring buffer could allocate an assembled_chunk *subclass* that tells
the ring buffer when it is deleted.
*/
/*
Single ringbuffer public API.
ringbuf<T>(int size)
// called when an item is about to be dropped off the end.
virtual void drop(T);
// try to enqueue an element; returns false if the ring buffer is full.
bool enqueue(const T&)
bool enqueue(T*)?
shared_ptr<T> enqueue(T*)?
//
vector<T> snapshot(bool test(T*)) ?
where T : shared_ptr<assembled_chunk> and we will subclass it to
override drop() to do the telescoping.
*/
#include <iostream>
#include <queue>
#include <deque>
using namespace std;
using namespace std::placeholders;
#include "ch_frb_io.hpp"
using namespace ch_frb_io;
std::ostream& operator<<(std::ostream& s, const assembled_chunk& ch) {
s << "assembled_chunk(beam " << ch.beam_id << ", ichunk " << ch.ichunk << ")";
return s;
}
// forward decl
template<class T>
class RingbufDeleter;
template<class T>
class Ringbuf {
friend class RingbufDeleter<T>;
public:
/*
Creates a new Ringbuf with the given maximum quota size.
*/
Ringbuf(int maxsize) :
_deleter(this),
_q(maxsize),
_live(0),
_maxsize(maxsize)
{}
virtual ~Ringbuf() {}
/*
Tries to push a new frame onto the ring buffer. If the quota of
frames has been reached, frames will be popped off the front
until the buffer is empty. If space is still not available, will
return an empty shared_ptr.
Returns the enqueued shared_ptr if successful.
*/
shared_ptr<T> push(T* t) {
while (_live >= _maxsize) {
cout << "Push: _live >= _maxsize." << " (" << _live << " >= " << _maxsize << ")" << endl;
if (_q.empty()) {
cout << "Ring buffer empty but still too many live elements -- push fails" << endl;
return shared_ptr<T>();
}
cout << "Dropping an element..." << endl;
shared_ptr<T> p = _q.front();
_q.pop_front();
dropping(p);
p.reset();
cout << "Now " << _live << " live" << endl;
}
cout << "Creating shared_ptr..." << endl;
shared_ptr<T> p(t, _deleter);
_live++;
_q.push_back(p);
cout << "Now " << _live << " objects are live" << endl;
return p;
}
/*
Pops the oldest frame from this buffer.
*/
shared_ptr<T> pop() {
cout << "Popping..." << endl;
shared_ptr<T> p = _q.pop_front();
cout << "Pop: returning " << *p << endl;
return p;
}
vector<shared_ptr<T> > snapshot(bool (*testFunc)(const shared_ptr<T>)) {
vector<shared_ptr<T> > vec;
for (auto it = _q.begin(); it != _q.end(); it++) {
if (!testFunc || testFunc(*it))
vec.push_back(*it);
}
return vec;
}
protected:
// Small helper class that calls deleted() when one of our frames
// is deleted.
RingbufDeleter<T> _deleter;
// The actual queue of frames.
deque<shared_ptr<T> > _q;
// Number of live frames.
size_t _live;
// Maximum allowable number of live frames.
size_t _maxsize;
// We're about to drop this frame.
virtual void dropping(shared_ptr<T> t) {}
// Called by the RingbufDeleter when a shared_ptr is deleted
void deleted(T* t) {
cout << "Deleting object: " << *t << endl;
_live--;
cout << "Now " << _live << " objects are live" << endl;
// FIXME --?
delete t;
}
};
template<class T>
class RingbufDeleter {
public:
RingbufDeleter(Ringbuf<T>* rb) : _ringbuf(rb) {}
void operator()(T* t) {
cout << "RingbufDelete::operator() called." << endl;
_ringbuf->deleted(t);
}
protected:
Ringbuf<T>* _ringbuf;
};
class L1Ringbuf;
class AssembledChunkRingbuf : public Ringbuf<assembled_chunk> {
public:
AssembledChunkRingbuf(int binlevel, L1Ringbuf* parent, int maxsize) :
Ringbuf<assembled_chunk>(maxsize),
_binlevel(binlevel),
_parent(parent)
{}
virtual ~AssembledChunkRingbuf() {}
protected:
// my time-binning. level: 0 = original intensity stream; 1 =
// binned x 2, 2 = binned x 4.
int _binlevel;
L1Ringbuf* _parent;
// Called when the given frame *t* is being dropped off the buffer
// to free up some space for a new frame.
virtual void dropping(shared_ptr<assembled_chunk> t);
};
class L1Ringbuf {
friend class AssembledChunkRingbuf;
static const size_t Nbins = 4;
public:
L1Ringbuf() :
_q(),
_rb(),
_dropped()
{
for (int i=0; i<Nbins; i++)
_rb.push_back(new AssembledChunkRingbuf(i, this, 4));
//_rb[i] = new AssembledChunkRingbuf(i, this, 4);
for (int i=0; i<Nbins-1; i++)
_dropped.push_back(shared_ptr<assembled_chunk>());
}
~L1Ringbuf() {
for (int i=0; i<Nbins; i++)
delete _rb[i];
}
bool push(assembled_chunk* ch) {
shared_ptr<assembled_chunk> p = _rb[0]->push(ch);
if (!p)
return false;
_q.push(p);
return true;
}
shared_ptr<assembled_chunk> pop() {
shared_ptr<assembled_chunk> p = _q.front();
_q.pop();
return p;
}
void print() {
cout << "L1 ringbuf:" << endl;
for (int i=0; i<Nbins; i++) {
vector<shared_ptr<assembled_chunk> > v = _rb[i]->snapshot(NULL);
cout << " binning " << i << ": [ ";
for (auto it = v.begin(); it != v.end(); it++) {
cout << (*it)->ichunk << " ";
}
cout << "]" << endl;
if (i < Nbins-1) {
cout << " dropped " << i << ": ";
if (_dropped[i])
cout << _dropped[i]->ichunk << endl;
else
cout << "none" << endl;
}
}
}
protected:
// The queue for downstream
queue<shared_ptr<assembled_chunk> > _q;
vector<AssembledChunkRingbuf*> _rb;
//array<AssembledChunkRingbuf*, Nbins> _rb;
vector<shared_ptr<assembled_chunk> > _dropped;
//array<shared_ptr<assembled_chunk>, Nbins> _dropped;
void dropping(int binlevel, shared_ptr<assembled_chunk> ch) {
cout << "Bin level " << binlevel << " dropping a chunk" << endl;
if (binlevel >= Nbins-1)
return;
if (_dropped[binlevel]) {
cout << "Now have 2 dropped chunks from bin level " << binlevel << endl;
// FIXME -- bin down
assembled_chunk* binned = new assembled_chunk(ch->beam_id, ch->nupfreq, ch->nt_per_packet, ch->fpga_counts_per_sample, _dropped[binlevel]->ichunk);
// push onto _rb[level+1]
_rb[binlevel+1]->push(binned);
_dropped[binlevel].reset();
} else {
// Keep this one until its partner arrives!
cout << "Saving as _dropped" << binlevel << endl;
_dropped[binlevel] = ch;
}
}
};
// after L1Ringbuf has been declared...
void AssembledChunkRingbuf::dropping(shared_ptr<assembled_chunk> t) {
_parent->dropping(_binlevel, t);
}
int main() {
L1Ringbuf rb;
int beam = 77;
int nupfreq = 4;
int nt_per = 16;
int fpga_per = 400;
assembled_chunk* ch;
//ch = assembled_chunk::make(4, nupfreq, nt_per, fpga_per, 42);
for (int i=0; i<32; i++) {
ch = new assembled_chunk(beam, nupfreq, nt_per, fpga_per, i);
rb.push(ch);
cout << "Pushed " << i << endl;
rb.print();
cout << endl;
// downstream thread consumes with a lag of 2...
if (i >= 2) {
rb.pop();
}
}
}
/*
int main() {
cout << "Creating ringbuf..." << endl;
Ringbuf<int> rb(4);
int a = 42;
int b = 43;
int c = 44;
cout << "Pushing" << endl;
rb.push(&a);
cout << "Pushing" << endl;
rb.push(&b);
cout << "Pushing" << endl;
rb.push(&c);
cout << "Popping" << endl;
shared_ptr<int> p1 = rb.pop();
cout << "Popping" << endl;
shared_ptr<int> p2 = rb.pop();
cout << "Dropping" << endl;
p1.reset();
cout << endl;
int d = 45;
int e = 46;
int f = 47;
int g = 48;
cout << "Pushing d..." << endl;
shared_ptr<int> pd = rb.push(&d);
cout << endl;
cout << "Pushing e..." << endl;
shared_ptr<int> pe = rb.push(&e);
cout << endl;
cout << "Pushing f..." << endl;
shared_ptr<int> pf = rb.push(&f);
cout << endl;
cout << "Pushing g..." << endl;
rb.push(&g);
cout << "Done" << endl;
}
*/
<commit_msg>oops, dequeue(int) constructor adds default-constructed elements<commit_after>
/**
Sketch of the L1 ring buffer desired API -- what the RPC server would
look like.
*/
/*
For RPC write_chunks: we need to keep the assembled_chunks alive via
a shared_ptr. This can be achieved by the RPC server pulling
requests off the client-facing socket in one thread, retrieving
shared_ptrs to the assembled_chunks, and putting them in a
(thread-safe) queue which will keep the shared_ptrs alive. After
enqueuing a chunk + args, it should send a request to a back-end
worker to pull some work from the queue. The worker can dequeue the
assembled_chunk, msgpack it or otherwise write it to disk, and then
drop the shared_ptr.
ZMQ_DONTWAIT -- blocks on zmq_send when high-water-mark is reached (DEALER)
//#include <zmq.hpp>
*/
/*
For the telescoping time-sampling, we want to keep ~4 ring buffers.
The property they have is that as the oldest data are dropped off the
end of the ring buffer, we want to take two chunks and compile them
into one chunk. While this is happening, we still want to be able to
access them. (ie, the RPC callbacks should still know about them).
Each of these ~4 ring buffers should use a fixed amount of space; we
may want to re-use the assembled_chunk memory.
*/
/*
One idea: rather than explicitly "pinning" assembled_chunks, we could
use shared_ptr.unique() -- if only the ring buffer has a copy of the
shared_ptr, then that assembled_chunk can be dropped.
*/
/*
Another idea is to use the assembled_chunk (or a wrapper of it)'s
destructor to notify the ring buffer (or an allocator) that it is
being deleted.
*/
/*
For the telescoping chain, we want the ring buffer to tell us when an
assembled_chunk is being dropped.
*/
/*
assembled_chunk::make() is a factory for assembled_chunks.
assembled_chunk_ringbuf::_make_assembled_chunk() wraps that or calls directly
assembled_chunk_ringbuf holds active_chunk0 and active_chunk1
*outside* the ringbuf.
_put_assembled_chunk is where assembled_chunks get added to the ring buffer.
*/
/*
assembled_chunk_ringbuf: needs to allocate a new chunk when it
receives a packet with ichunk >= active_ichunk + 2.
Could do:
- try to allocate a new assembled_chunk. If that fails:
- if assembled_ringbuf_size == assembled_ringbuf_capacity,
then the buffer is full of chunks waiting for the consumer thread.
-> drop data? This means we keep the oldest data; alternative
would be to drop the oldest frame and keep the newest data
instead.
- iteratively: go to the next ringbuf position and drop that chunk
off the back -- call callback, then reset the shared_ptr. Then try
to allocate a new assembled_chunk. If resetting the shared_ptr
drop the last reference to an assembled_chunk, then that chunk will
become available. If not (eg, if RPC thread has a copy of the
shared_ptr), continue on to the next position. This process will
stop once we drop (assembled_ringbuf_capacity -
assembled_ringbuf_size) chunks -- ie, all the chunks left in the
buffer are the ones waiting to be consumed.
- there will be a callback for when a chunk is being dropped. This
is where we handle the telescoping: we'll hold zero or one older
chunks, and when a chunk is about to be dropped, if we had an older
one, then we can downsample the two and then enqueue the resulting
new chunk. This enqueue call could (typically will, in
steady-state) cause a cascade of dropping the oldest frame from the
next ring buffer.
- the longer-duration ring buffers do not have 'downstream'
consumers.
- Huh, what if the queue of assembled chunks waiting for the
downstream consumer and the ring buffer per se are two separate data
structures that each hold shared_ptrs?
- ring buffer could allocate an assembled_chunk *subclass* that tells
the ring buffer when it is deleted.
*/
/*
Single ringbuffer public API.
ringbuf<T>(int size)
// called when an item is about to be dropped off the end.
virtual void drop(T);
// try to enqueue an element; returns false if the ring buffer is full.
bool enqueue(const T&)
bool enqueue(T*)?
shared_ptr<T> enqueue(T*)?
//
vector<T> snapshot(bool test(T*)) ?
where T : shared_ptr<assembled_chunk> and we will subclass it to
override drop() to do the telescoping.
*/
#include <iostream>
#include <queue>
#include <deque>
#include <functional>
using namespace std;
using namespace std::placeholders;
#include "ch_frb_io.hpp"
using namespace ch_frb_io;
std::ostream& operator<<(std::ostream& s, const assembled_chunk& ch) {
s << "assembled_chunk(beam " << ch.beam_id << ", ichunk " << ch.ichunk << ")";
return s;
}
// forward decl
template<class T>
class RingbufDeleter;
template<class T>
class Ringbuf {
friend class RingbufDeleter<T>;
public:
/*
Creates a new Ringbuf with the given maximum quota size.
*/
Ringbuf(int maxsize) :
_deleter(this),
_q(),
_live(0),
_maxsize(maxsize)
{}
virtual ~Ringbuf() {}
/*
Tries to push a new frame onto the ring buffer. If the quota of
frames has been reached, frames will be popped off the front
until the buffer is empty. If space is still not available, will
return an empty shared_ptr.
Returns the enqueued shared_ptr if successful.
*/
shared_ptr<T> push(T* t) {
while (_live >= _maxsize) {
cout << "Push: _live >= _maxsize." << " (" << _live << " >= " << _maxsize << ")" << endl;
if (_q.empty()) {
cout << "Ring buffer empty but still too many live elements -- push fails" << endl;
return shared_ptr<T>();
}
cout << "Dropping an element..." << endl;
shared_ptr<T> p = _q.front();
_q.pop_front();
dropping(p);
p.reset();
cout << "Now " << _live << " live" << endl;
}
cout << "Creating shared_ptr..." << endl;
shared_ptr<T> p(t, _deleter);
_live++;
_q.push_back(p);
cout << "Now " << _live << " objects are live" << endl;
return p;
}
/*
Pops the oldest frame from this buffer.
*/
shared_ptr<T> pop() {
cout << "Popping..." << endl;
shared_ptr<T> p = _q.pop_front();
cout << "Pop: returning " << *p << endl;
return p;
}
vector<shared_ptr<T> > snapshot(bool (*testFunc)(const shared_ptr<T>)) {
vector<shared_ptr<T> > vec;
for (auto it = _q.begin(); it != _q.end(); it++) {
if (!testFunc || testFunc(*it)) {
cout << "snapshot: " << (*it) << endl;
vec.push_back(*it);
}
}
return vec;
}
protected:
// Small helper class that calls deleted() when one of our frames
// is deleted.
RingbufDeleter<T> _deleter;
// The actual queue of frames.
deque<shared_ptr<T> > _q;
// Number of live frames.
size_t _live;
// Maximum allowable number of live frames.
size_t _maxsize;
// We're about to drop this frame.
virtual void dropping(shared_ptr<T> t) {}
// Called by the RingbufDeleter when a shared_ptr is deleted
void deleted(T* t) {
cout << "Deleting object: " << *t << endl;
_live--;
cout << "Now " << _live << " objects are live" << endl;
// FIXME --?
delete t;
}
};
template<class T>
class RingbufDeleter {
public:
RingbufDeleter(Ringbuf<T>* rb) : _ringbuf(rb) {}
void operator()(T* t) {
cout << "RingbufDelete::operator() called." << endl;
_ringbuf->deleted(t);
}
protected:
Ringbuf<T>* _ringbuf;
};
class L1Ringbuf;
class AssembledChunkRingbuf : public Ringbuf<assembled_chunk> {
public:
AssembledChunkRingbuf(int binlevel, L1Ringbuf* parent, int maxsize) :
Ringbuf<assembled_chunk>(maxsize),
_binlevel(binlevel),
_parent(parent)
{}
virtual ~AssembledChunkRingbuf() {}
protected:
// my time-binning. level: 0 = original intensity stream; 1 =
// binned x 2, 2 = binned x 4.
int _binlevel;
L1Ringbuf* _parent;
// Called when the given frame *t* is being dropped off the buffer
// to free up some space for a new frame.
virtual void dropping(shared_ptr<assembled_chunk> t);
};
class L1Ringbuf {
friend class AssembledChunkRingbuf;
static const size_t Nbins = 4;
public:
L1Ringbuf() :
_q(),
_rb(),
_dropped()
{
for (size_t i=0; i<Nbins; i++)
_rb.push_back(new AssembledChunkRingbuf(i, this, 4));
//_rb[i] = new AssembledChunkRingbuf(i, this, 4);
for (size_t i=0; i<Nbins-1; i++)
_dropped.push_back(shared_ptr<assembled_chunk>());
}
~L1Ringbuf() {
for (size_t i=0; i<Nbins; i++)
delete _rb[i];
}
bool push(assembled_chunk* ch) {
shared_ptr<assembled_chunk> p = _rb[0]->push(ch);
if (!p)
return false;
_q.push(p);
return true;
}
shared_ptr<assembled_chunk> pop() {
shared_ptr<assembled_chunk> p = _q.front();
_q.pop();
return p;
}
void print() {
cout << "L1 ringbuf:" << endl;
for (size_t i=0; i<Nbins; i++) {
vector<shared_ptr<assembled_chunk> > v = _rb[i]->snapshot(NULL);
cout << " binning " << i << ": [ ";
for (auto it = v.begin(); it != v.end(); it++) {
cout << (*it)->ichunk << " ";
}
cout << "]" << endl;
if (i < Nbins-1) {
cout << " dropped " << i << ": ";
if (_dropped[i])
cout << _dropped[i]->ichunk << endl;
else
cout << "none" << endl;
}
}
}
protected:
// The queue for downstream
queue<shared_ptr<assembled_chunk> > _q;
vector<AssembledChunkRingbuf*> _rb;
//array<AssembledChunkRingbuf*, Nbins> _rb;
vector<shared_ptr<assembled_chunk> > _dropped;
//array<shared_ptr<assembled_chunk>, Nbins> _dropped;
void dropping(int binlevel, shared_ptr<assembled_chunk> ch) {
cout << "Bin level " << binlevel << " dropping a chunk" << endl;
if (binlevel >= (int)(Nbins-1))
return;
if (_dropped[binlevel]) {
cout << "Now have 2 dropped chunks from bin level " << binlevel << endl;
// FIXME -- bin down
assembled_chunk* binned = new assembled_chunk(ch->beam_id, ch->nupfreq, ch->nt_per_packet, ch->fpga_counts_per_sample, _dropped[binlevel]->ichunk);
// push onto _rb[level+1]
_rb[binlevel+1]->push(binned);
_dropped[binlevel].reset();
} else {
// Keep this one until its partner arrives!
cout << "Saving as _dropped" << binlevel << endl;
_dropped[binlevel] = ch;
}
}
};
// after L1Ringbuf has been declared...
void AssembledChunkRingbuf::dropping(shared_ptr<assembled_chunk> t) {
_parent->dropping(_binlevel, t);
}
int main() {
L1Ringbuf rb;
int beam = 77;
int nupfreq = 4;
int nt_per = 16;
int fpga_per = 400;
assembled_chunk* ch;
//ch = assembled_chunk::make(4, nupfreq, nt_per, fpga_per, 42);
for (int i=0; i<32; i++) {
ch = new assembled_chunk(beam, nupfreq, nt_per, fpga_per, i);
rb.push(ch);
cout << "Pushed " << i << endl;
rb.print();
cout << endl;
// downstream thread consumes with a lag of 2...
if (i >= 2) {
rb.pop();
}
}
}
/*
int main() {
cout << "Creating ringbuf..." << endl;
Ringbuf<int> rb(4);
int a = 42;
int b = 43;
int c = 44;
cout << "Pushing" << endl;
rb.push(&a);
cout << "Pushing" << endl;
rb.push(&b);
cout << "Pushing" << endl;
rb.push(&c);
cout << "Popping" << endl;
shared_ptr<int> p1 = rb.pop();
cout << "Popping" << endl;
shared_ptr<int> p2 = rb.pop();
cout << "Dropping" << endl;
p1.reset();
cout << endl;
int d = 45;
int e = 46;
int f = 47;
int g = 48;
cout << "Pushing d..." << endl;
shared_ptr<int> pd = rb.push(&d);
cout << endl;
cout << "Pushing e..." << endl;
shared_ptr<int> pe = rb.push(&e);
cout << endl;
cout << "Pushing f..." << endl;
shared_ptr<int> pf = rb.push(&f);
cout << endl;
cout << "Pushing g..." << endl;
rb.push(&g);
cout << "Done" << endl;
}
*/
<|endoftext|>
|
<commit_before>#include <QtNetwork>
#include "api-request.h"
#include "api-client.h"
SeafileApiRequest::SeafileApiRequest(const QUrl& url, Method method, const QString& token)
: url_(url),
method_(method),
token_(token)
{
api_client_ = new SeafileApiClient;
}
SeafileApiRequest::~SeafileApiRequest()
{
delete api_client_;
}
void SeafileApiRequest::setParam(const QString& name, const QString& value)
{
params_.addQueryItem(name, value);
}
void SeafileApiRequest::send()
{
if (token_.size() > 0) {
api_client_->setToken(token_);
}
switch (method_) {
case METHOD_GET:
api_client_->get(url_);
break;
case METHOD_POST:
api_client_->post(url_, params_.encodedQuery());
break;
}
connect(api_client_, SIGNAL(requestSuccess(QNetworkReply&)),
this, SLOT(requestSuccess(QNetworkReply&)));
connect(api_client_, SIGNAL(requestFailed(int)),
this, SIGNAL(failed(int)));
}
json_t* SeafileApiRequest::parseJSON(QNetworkReply &reply, json_error_t *error)
{
QByteArray raw = reply.readAll();
//qDebug("\n%s\n", raw.data());
json_t *root = json_loads(raw.data(), 0, error);
return root;
}
<commit_msg>fixed api request post param escaping<commit_after>#include <QtNetwork>
#include "api-request.h"
#include "api-client.h"
SeafileApiRequest::SeafileApiRequest(const QUrl& url, Method method, const QString& token)
: url_(url),
method_(method),
token_(token)
{
api_client_ = new SeafileApiClient;
}
SeafileApiRequest::~SeafileApiRequest()
{
delete api_client_;
}
void SeafileApiRequest::setParam(const QString& name, const QString& value)
{
params_.addEncodedQueryItem(QUrl::toPercentEncoding(name),
QUrl::toPercentEncoding(value));
}
void SeafileApiRequest::send()
{
if (token_.size() > 0) {
api_client_->setToken(token_);
}
switch (method_) {
case METHOD_GET:
api_client_->get(url_);
break;
case METHOD_POST:
api_client_->post(url_, params_.encodedQuery());
break;
}
connect(api_client_, SIGNAL(requestSuccess(QNetworkReply&)),
this, SLOT(requestSuccess(QNetworkReply&)));
connect(api_client_, SIGNAL(requestFailed(int)),
this, SIGNAL(failed(int)));
}
json_t* SeafileApiRequest::parseJSON(QNetworkReply &reply, json_error_t *error)
{
QByteArray raw = reply.readAll();
//qDebug("\n%s\n", raw.data());
json_t *root = json_loads(raw.data(), 0, error);
return root;
}
<|endoftext|>
|
<commit_before>//=======================================================================
// Copyright (c) 2014 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#ifndef DLL_OPENCV_RBM_VISUALIZER_HPP
#define DLL_OPENCV_RBM_VISUALIZER_HPP
#include "dll/stop_watch.hpp"
#include "dll/rbm_traits.hpp"
#include "dll/dbn_traits.hpp"
#include <opencv2/opencv.hpp>
namespace dll {
template<typename RBM>
struct opencv_rbm_visualizer {
stop_watch<std::chrono::seconds> watch;
const std::size_t shape = 28;
const std::size_t num_hidden = 10;
const bool scale = true;
const std::size_t padding = 20;
const std::size_t width;
const std::size_t height;
cv::Mat buffer_image;
opencv_rbm_visualizer(std::size_t shape = 28, std::size_t num_hidden = 10, bool scale = true, std::size_t padding = 10) :
shape(shape),
num_hidden(num_hidden),
scale(scale),
padding(padding),
width(shape * num_hidden + (num_hidden + 1) * 1 + 2 * padding),
height(shape * num_hidden + (num_hidden + 1) * 1 + 2 * padding),
buffer_image(cv::Size(width, height), CV_8UC1) {}
void training_begin(const RBM& rbm){
std::cout << "Train RBM with \"" << RBM::desc::template trainer_t<RBM>::name() << "\"" << std::endl;
std::cout << "With parameters:" << std::endl;
std::cout << " learning_rate=" << rbm.learning_rate << std::endl;
if(rbm_traits<RBM>::has_momentum()){
std::cout << " momentum=" << rbm.momentum << std::endl;
}
if(rbm_traits<RBM>::decay() == decay_type::L1 || rbm_traits<RBM>::decay() == decay_type::L1_FULL){
std::cout << " weight_cost(L1)=" << rbm.weight_cost << std::endl;
}
if(rbm_traits<RBM>::decay() == decay_type::L2 || rbm_traits<RBM>::decay() == decay_type::L2_FULL){
std::cout << " weight_cost(L2)=" << rbm.weight_cost << std::endl;
}
if(rbm_traits<RBM>::has_sparsity()){
std::cout << " sparsity_target=" << rbm.sparsity_target << std::endl;
}
cv::namedWindow("RBM Training", cv::WINDOW_NORMAL);
refresh();
}
void epoch_end(std::size_t epoch, double error, double free_energy, const RBM& rbm){
printf("epoch %ld - Reconstruction error average: %.5f - Free energy average: %.3f\n", epoch, error, free_energy);
buffer_image = cv::Scalar(255);
cv::putText(buffer_image, "epoch " + std::to_string(epoch), cv::Point(10,12), CV_FONT_NORMAL, 0.3, cv::Scalar(0), 1, 2);
for(std::size_t hi = 0; hi < num_hidden; ++hi){
for(std::size_t hj = 0; hj < num_hidden; ++hj){
auto real_h = hi * num_hidden + hj;
typename RBM::weight min = 100.0;
typename RBM::weight max = 0.0;
if(scale){
for(std::size_t real_v = 0; real_v < shape * shape; ++real_v){
min = std::min(rbm.w(real_v, real_h), min);
max = std::max(rbm.w(real_v, real_h), max);
}
}
for(std::size_t i = 0; i < shape; ++i){
for(std::size_t j = 0; j < shape; ++j){
auto real_v = i * shape + j;
auto value = rbm.w(real_v, real_h);
if(scale){
value -= min;
value *= 1.0 / (max + 1e-8);
}
buffer_image.at<uint8_t>(padding+1+hi*(shape+1)+i, padding+1+hj*(shape+1)+j) = value * 255;
}
}
}
}
refresh();
}
void training_end(const RBM&){
std::cout << "Training took " << watch.elapsed() << "s" << std::endl;
cv::waitKey(0);
}
void refresh(){
cv::imshow("RBM Training", buffer_image);
cv::waitKey(30);
}
};
} //end of dll namespace
#endif<commit_msg>Fix default values<commit_after>//=======================================================================
// Copyright (c) 2014 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#ifndef DLL_OPENCV_RBM_VISUALIZER_HPP
#define DLL_OPENCV_RBM_VISUALIZER_HPP
#include "dll/stop_watch.hpp"
#include "dll/rbm_traits.hpp"
#include "dll/dbn_traits.hpp"
#include <opencv2/opencv.hpp>
namespace dll {
template<typename RBM>
struct opencv_rbm_visualizer {
stop_watch<std::chrono::seconds> watch;
const std::size_t shape = 28;
const std::size_t num_hidden = 10;
const bool scale = true;
const std::size_t padding = 20;
const std::size_t width;
const std::size_t height;
cv::Mat buffer_image;
opencv_rbm_visualizer(std::size_t shape = 28, std::size_t num_hidden = 10, bool scale = true, std::size_t padding = 20) :
shape(shape),
num_hidden(num_hidden),
scale(scale),
padding(padding),
width(shape * num_hidden + (num_hidden + 1) * 1 + 2 * padding),
height(shape * num_hidden + (num_hidden + 1) * 1 + 2 * padding),
buffer_image(cv::Size(width, height), CV_8UC1) {}
void training_begin(const RBM& rbm){
std::cout << "Train RBM with \"" << RBM::desc::template trainer_t<RBM>::name() << "\"" << std::endl;
std::cout << "With parameters:" << std::endl;
std::cout << " learning_rate=" << rbm.learning_rate << std::endl;
if(rbm_traits<RBM>::has_momentum()){
std::cout << " momentum=" << rbm.momentum << std::endl;
}
if(rbm_traits<RBM>::decay() == decay_type::L1 || rbm_traits<RBM>::decay() == decay_type::L1_FULL){
std::cout << " weight_cost(L1)=" << rbm.weight_cost << std::endl;
}
if(rbm_traits<RBM>::decay() == decay_type::L2 || rbm_traits<RBM>::decay() == decay_type::L2_FULL){
std::cout << " weight_cost(L2)=" << rbm.weight_cost << std::endl;
}
if(rbm_traits<RBM>::has_sparsity()){
std::cout << " sparsity_target=" << rbm.sparsity_target << std::endl;
}
cv::namedWindow("RBM Training", cv::WINDOW_NORMAL);
refresh();
}
void epoch_end(std::size_t epoch, double error, double free_energy, const RBM& rbm){
printf("epoch %ld - Reconstruction error average: %.5f - Free energy average: %.3f\n", epoch, error, free_energy);
buffer_image = cv::Scalar(255);
cv::putText(buffer_image, "epoch " + std::to_string(epoch), cv::Point(10,12), CV_FONT_NORMAL, 0.3, cv::Scalar(0), 1, 2);
for(std::size_t hi = 0; hi < num_hidden; ++hi){
for(std::size_t hj = 0; hj < num_hidden; ++hj){
auto real_h = hi * num_hidden + hj;
typename RBM::weight min = 100.0;
typename RBM::weight max = 0.0;
if(scale){
for(std::size_t real_v = 0; real_v < shape * shape; ++real_v){
min = std::min(rbm.w(real_v, real_h), min);
max = std::max(rbm.w(real_v, real_h), max);
}
}
for(std::size_t i = 0; i < shape; ++i){
for(std::size_t j = 0; j < shape; ++j){
auto real_v = i * shape + j;
auto value = rbm.w(real_v, real_h);
if(scale){
value -= min;
value *= 1.0 / (max + 1e-8);
}
buffer_image.at<uint8_t>(padding+1+hi*(shape+1)+i, padding+1+hj*(shape+1)+j) = value * 255;
}
}
}
}
refresh();
}
void training_end(const RBM&){
std::cout << "Training took " << watch.elapsed() << "s" << std::endl;
cv::waitKey(0);
}
void refresh(){
cv::imshow("RBM Training", buffer_image);
cv::waitKey(30);
}
};
} //end of dll namespace
#endif<|endoftext|>
|
<commit_before>//*****************************************************************************
// Copyright 2017-2018 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//*****************************************************************************
#include <set>
#include <sstream>
#include "ngraph/op/batch_norm.hpp"
#include "ngraph/op/constant.hpp"
#include "ngraph/op/get_output_element.hpp"
#include "ngraph/validation_util.hpp"
ngraph::op::BatchNormInference::BatchNormInference(double eps,
std::shared_ptr<ngraph::Node> gamma,
std::shared_ptr<ngraph::Node> beta,
std::shared_ptr<ngraph::Node> input,
std::shared_ptr<ngraph::Node> mean,
std::shared_ptr<ngraph::Node> variance)
: Op("BatchNormInference", check_single_output_args({gamma, beta, input, mean, variance}))
, m_epsilon(eps)
{
constructor_validate_and_infer_types();
}
ngraph::op::BatchNormTraining::BatchNormTraining(double eps,
std::shared_ptr<ngraph::Node> gamma,
std::shared_ptr<ngraph::Node> beta,
std::shared_ptr<ngraph::Node> input)
: Op("BatchNormTraining", check_single_output_args({gamma, beta, input}))
, m_epsilon(eps)
{
constructor_validate_and_infer_types();
}
void ngraph::op::BatchNormInference::validate_and_infer_types()
{
element::Type result_et;
PartialShape result_batch_shape;
PartialShape result_channel_shape; // unused here
std::tie(result_et, result_batch_shape, result_channel_shape) =
infer_batch_norm_forward(this,
get_input_element_type(INPUT_DATA),
get_input_element_type(INPUT_GAMMA),
get_input_element_type(INPUT_BETA),
get_input_element_type(INPUT_MEAN),
get_input_element_type(INPUT_VARIANCE),
get_input_partial_shape(INPUT_DATA),
get_input_partial_shape(INPUT_GAMMA),
get_input_partial_shape(INPUT_BETA),
get_input_partial_shape(INPUT_MEAN),
get_input_partial_shape(INPUT_VARIANCE));
set_output_size(1);
set_output_type(0, result_et, result_batch_shape);
}
void ngraph::op::BatchNormTraining::validate_and_infer_types()
{
element::Type result_et;
PartialShape result_batch_shape;
PartialShape result_channel_shape;
std::tie(result_et, result_batch_shape, result_channel_shape) =
infer_batch_norm_forward(this,
get_input_element_type(INPUT_DATA),
get_input_element_type(INPUT_GAMMA),
get_input_element_type(INPUT_BETA),
get_input_partial_shape(INPUT_DATA),
get_input_partial_shape(INPUT_GAMMA),
get_input_partial_shape(INPUT_BETA));
set_output_size(3);
set_output_type(0, result_et, result_batch_shape);
set_output_type(1, result_et, result_channel_shape);
set_output_type(2, result_et, result_channel_shape);
}
std::shared_ptr<ngraph::Node>
ngraph::op::BatchNormInference::copy_with_new_args(const NodeVector& new_args) const
{
check_new_args_count(this, new_args);
return std::make_shared<BatchNormInference>(
m_epsilon, new_args.at(0), new_args.at(1), new_args.at(2), new_args.at(3), new_args.at(4));
}
std::shared_ptr<ngraph::Node>
ngraph::op::BatchNormTraining::copy_with_new_args(const NodeVector& new_args) const
{
check_new_args_count(this, new_args);
return std::make_shared<BatchNormTraining>(
m_epsilon, new_args.at(0), new_args.at(1), new_args.at(2));
}
ngraph::op::BatchNormTrainingBackprop::BatchNormTrainingBackprop(
double eps,
std::shared_ptr<ngraph::Node> gamma,
std::shared_ptr<ngraph::Node> beta,
std::shared_ptr<ngraph::Node> input,
std::shared_ptr<ngraph::Node> mean,
std::shared_ptr<ngraph::Node> variance,
std::shared_ptr<ngraph::Node> delta)
: Op("BatchNormTrainingBackprop",
check_single_output_args({gamma, beta, input, mean, variance, delta}))
, m_epsilon(eps)
{
constructor_validate_and_infer_types();
}
void ngraph::op::BatchNormTrainingBackprop::validate_and_infer_types()
{
PartialShape input_and_delta_shape{get_input_partial_shape(INPUT_DATA)};
NODE_VALIDATION_ASSERT(
this, PartialShape::merge_into(input_and_delta_shape, get_input_partial_shape(INPUT_DELTA)))
<< "Shape of delta does not match the shape of the input data (input data shape: "
<< get_input_partial_shape(INPUT_DATA)
<< ", delta shape: " << get_input_partial_shape(INPUT_DELTA) << ").";
element::Type input_and_delta_et;
NODE_VALIDATION_ASSERT(this,
element::Type::merge(input_and_delta_et,
get_input_element_type(INPUT_DATA),
get_input_element_type(INPUT_DELTA)))
<< "Element type for input (" << get_input_element_type(INPUT_DATA)
<< ") does not match element type for delta (" << get_input_element_type(INPUT_DATA)
<< ").";
element::Type result_et;
PartialShape result_batch_shape;
PartialShape result_channel_shape;
std::tie(result_et, result_batch_shape, result_channel_shape) =
infer_batch_norm_forward(this,
input_and_delta_et,
get_input_element_type(INPUT_GAMMA),
get_input_element_type(INPUT_BETA),
get_input_element_type(INPUT_MEAN),
get_input_element_type(INPUT_VARIANCE),
input_and_delta_shape,
get_input_partial_shape(INPUT_GAMMA),
get_input_partial_shape(INPUT_BETA),
get_input_partial_shape(INPUT_MEAN),
get_input_partial_shape(INPUT_VARIANCE));
set_output_size(3);
set_output_type(0, result_et, result_batch_shape);
set_output_type(1, result_et, result_channel_shape);
set_output_type(2, result_et, result_channel_shape);
}
std::shared_ptr<ngraph::Node>
ngraph::op::BatchNormTrainingBackprop::copy_with_new_args(const NodeVector& new_args) const
{
check_new_args_count(this, new_args);
return std::make_shared<op::BatchNormTrainingBackprop>(m_epsilon,
new_args.at(0),
new_args.at(1),
new_args.at(2),
new_args.at(3),
new_args.at(4),
new_args.at(5));
}
void ngraph::op::BatchNormTraining::generate_adjoints(autodiff::Adjoints& adjoints,
const NodeVector& deltas)
{
auto gamma = get_argument(0);
auto beta = get_argument(1);
auto input = get_argument(2);
std::shared_ptr<Node> mean = nullptr;
std::shared_ptr<Node> var = nullptr;
// Extract mean and variance outputs from BatchNormBase
// as these are used by BatchNormTrainingBackprop.
// The users of the outputs (GetOutputElements' Inputs) aren't sorted
// and get_n() is used to sort the inputs in the same order as Batchnorm's outputs
// Next, Mean and Variance (`at(1)` and `at(2)`) are extracted
// Please see `add_output` in `BatchNormBase::BatchNormBase` for more details
auto goes = op::get_output_elements(shared_from_this());
mean = goes.at(1);
var = goes.at(2);
if (!mean)
{
throw ngraph_error("GetOutputElement for mean is missing");
}
if (!var)
{
throw ngraph_error("GetOutputElement for variance is missing");
}
auto bbn = std::make_shared<op::BatchNormTrainingBackprop>(
get_eps_value(), gamma, beta, input, mean, var, deltas.at(0));
auto dinput = std::make_shared<op::GetOutputElement>(bbn, 0);
auto dgamma = std::make_shared<op::GetOutputElement>(bbn, 1);
auto dbeta = std::make_shared<op::GetOutputElement>(bbn, 2);
adjoints.add_delta(input, dinput);
adjoints.add_delta(gamma, dgamma);
adjoints.add_delta(beta, dbeta);
}
<commit_msg>Update BatchNorm to set_output_size at construction time (#1963)<commit_after>//*****************************************************************************
// Copyright 2017-2018 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//*****************************************************************************
#include <set>
#include <sstream>
#include "ngraph/op/batch_norm.hpp"
#include "ngraph/op/constant.hpp"
#include "ngraph/op/get_output_element.hpp"
#include "ngraph/validation_util.hpp"
ngraph::op::BatchNormInference::BatchNormInference(double eps,
std::shared_ptr<ngraph::Node> gamma,
std::shared_ptr<ngraph::Node> beta,
std::shared_ptr<ngraph::Node> input,
std::shared_ptr<ngraph::Node> mean,
std::shared_ptr<ngraph::Node> variance)
: Op("BatchNormInference", check_single_output_args({gamma, beta, input, mean, variance}))
, m_epsilon(eps)
{
set_output_size(1);
constructor_validate_and_infer_types();
}
ngraph::op::BatchNormTraining::BatchNormTraining(double eps,
std::shared_ptr<ngraph::Node> gamma,
std::shared_ptr<ngraph::Node> beta,
std::shared_ptr<ngraph::Node> input)
: Op("BatchNormTraining", check_single_output_args({gamma, beta, input}))
, m_epsilon(eps)
{
set_output_size(3);
constructor_validate_and_infer_types();
}
void ngraph::op::BatchNormInference::validate_and_infer_types()
{
element::Type result_et;
PartialShape result_batch_shape;
PartialShape result_channel_shape; // unused here
std::tie(result_et, result_batch_shape, result_channel_shape) =
infer_batch_norm_forward(this,
get_input_element_type(INPUT_DATA),
get_input_element_type(INPUT_GAMMA),
get_input_element_type(INPUT_BETA),
get_input_element_type(INPUT_MEAN),
get_input_element_type(INPUT_VARIANCE),
get_input_partial_shape(INPUT_DATA),
get_input_partial_shape(INPUT_GAMMA),
get_input_partial_shape(INPUT_BETA),
get_input_partial_shape(INPUT_MEAN),
get_input_partial_shape(INPUT_VARIANCE));
set_output_type(0, result_et, result_batch_shape);
}
void ngraph::op::BatchNormTraining::validate_and_infer_types()
{
element::Type result_et;
PartialShape result_batch_shape;
PartialShape result_channel_shape;
std::tie(result_et, result_batch_shape, result_channel_shape) =
infer_batch_norm_forward(this,
get_input_element_type(INPUT_DATA),
get_input_element_type(INPUT_GAMMA),
get_input_element_type(INPUT_BETA),
get_input_partial_shape(INPUT_DATA),
get_input_partial_shape(INPUT_GAMMA),
get_input_partial_shape(INPUT_BETA));
set_output_type(0, result_et, result_batch_shape);
set_output_type(1, result_et, result_channel_shape);
set_output_type(2, result_et, result_channel_shape);
}
std::shared_ptr<ngraph::Node>
ngraph::op::BatchNormInference::copy_with_new_args(const NodeVector& new_args) const
{
check_new_args_count(this, new_args);
return std::make_shared<BatchNormInference>(
m_epsilon, new_args.at(0), new_args.at(1), new_args.at(2), new_args.at(3), new_args.at(4));
}
std::shared_ptr<ngraph::Node>
ngraph::op::BatchNormTraining::copy_with_new_args(const NodeVector& new_args) const
{
check_new_args_count(this, new_args);
return std::make_shared<BatchNormTraining>(
m_epsilon, new_args.at(0), new_args.at(1), new_args.at(2));
}
ngraph::op::BatchNormTrainingBackprop::BatchNormTrainingBackprop(
double eps,
std::shared_ptr<ngraph::Node> gamma,
std::shared_ptr<ngraph::Node> beta,
std::shared_ptr<ngraph::Node> input,
std::shared_ptr<ngraph::Node> mean,
std::shared_ptr<ngraph::Node> variance,
std::shared_ptr<ngraph::Node> delta)
: Op("BatchNormTrainingBackprop",
check_single_output_args({gamma, beta, input, mean, variance, delta}))
, m_epsilon(eps)
{
set_output_size(3);
constructor_validate_and_infer_types();
}
void ngraph::op::BatchNormTrainingBackprop::validate_and_infer_types()
{
PartialShape input_and_delta_shape{get_input_partial_shape(INPUT_DATA)};
NODE_VALIDATION_ASSERT(
this, PartialShape::merge_into(input_and_delta_shape, get_input_partial_shape(INPUT_DELTA)))
<< "Shape of delta does not match the shape of the input data (input data shape: "
<< get_input_partial_shape(INPUT_DATA)
<< ", delta shape: " << get_input_partial_shape(INPUT_DELTA) << ").";
element::Type input_and_delta_et;
NODE_VALIDATION_ASSERT(this,
element::Type::merge(input_and_delta_et,
get_input_element_type(INPUT_DATA),
get_input_element_type(INPUT_DELTA)))
<< "Element type for input (" << get_input_element_type(INPUT_DATA)
<< ") does not match element type for delta (" << get_input_element_type(INPUT_DATA)
<< ").";
element::Type result_et;
PartialShape result_batch_shape;
PartialShape result_channel_shape;
std::tie(result_et, result_batch_shape, result_channel_shape) =
infer_batch_norm_forward(this,
input_and_delta_et,
get_input_element_type(INPUT_GAMMA),
get_input_element_type(INPUT_BETA),
get_input_element_type(INPUT_MEAN),
get_input_element_type(INPUT_VARIANCE),
input_and_delta_shape,
get_input_partial_shape(INPUT_GAMMA),
get_input_partial_shape(INPUT_BETA),
get_input_partial_shape(INPUT_MEAN),
get_input_partial_shape(INPUT_VARIANCE));
set_output_type(0, result_et, result_batch_shape);
set_output_type(1, result_et, result_channel_shape);
set_output_type(2, result_et, result_channel_shape);
}
std::shared_ptr<ngraph::Node>
ngraph::op::BatchNormTrainingBackprop::copy_with_new_args(const NodeVector& new_args) const
{
check_new_args_count(this, new_args);
return std::make_shared<op::BatchNormTrainingBackprop>(m_epsilon,
new_args.at(0),
new_args.at(1),
new_args.at(2),
new_args.at(3),
new_args.at(4),
new_args.at(5));
}
void ngraph::op::BatchNormTraining::generate_adjoints(autodiff::Adjoints& adjoints,
const NodeVector& deltas)
{
auto gamma = get_argument(0);
auto beta = get_argument(1);
auto input = get_argument(2);
std::shared_ptr<Node> mean = nullptr;
std::shared_ptr<Node> var = nullptr;
// Extract mean and variance outputs from BatchNormBase
// as these are used by BatchNormTrainingBackprop.
// The users of the outputs (GetOutputElements' Inputs) aren't sorted
// and get_n() is used to sort the inputs in the same order as Batchnorm's outputs
// Next, Mean and Variance (`at(1)` and `at(2)`) are extracted
// Please see `add_output` in `BatchNormBase::BatchNormBase` for more details
auto goes = op::get_output_elements(shared_from_this());
mean = goes.at(1);
var = goes.at(2);
if (!mean)
{
throw ngraph_error("GetOutputElement for mean is missing");
}
if (!var)
{
throw ngraph_error("GetOutputElement for variance is missing");
}
auto bbn = std::make_shared<op::BatchNormTrainingBackprop>(
get_eps_value(), gamma, beta, input, mean, var, deltas.at(0));
auto dinput = std::make_shared<op::GetOutputElement>(bbn, 0);
auto dgamma = std::make_shared<op::GetOutputElement>(bbn, 1);
auto dbeta = std::make_shared<op::GetOutputElement>(bbn, 2);
adjoints.add_delta(input, dinput);
adjoints.add_delta(gamma, dgamma);
adjoints.add_delta(beta, dbeta);
}
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2006, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef ROUTING_TABLE_HPP
#define ROUTING_TABLE_HPP
#include <vector>
#include <boost/cstdint.hpp>
#include <boost/utility.hpp>
#include <boost/tuple/tuple.hpp>
#include <boost/array.hpp>
#include <set>
#include <libtorrent/kademlia/logging.hpp>
#include <libtorrent/kademlia/node_id.hpp>
#include <libtorrent/kademlia/node_entry.hpp>
#include <libtorrent/session_settings.hpp>
#include <libtorrent/size_type.hpp>
#include <libtorrent/assert.hpp>
#include <libtorrent/ptime.hpp>
namespace libtorrent
{
struct session_status;
}
namespace libtorrent { namespace dht
{
#ifdef TORRENT_DHT_VERBOSE_LOGGING
TORRENT_DECLARE_LOG(table);
#endif
typedef std::vector<node_entry> bucket_t;
struct routing_table_node
{
bucket_t replacements;
bucket_t live_nodes;
ptime last_active;
};
// differences in the implementation from the description in
// the paper:
//
// * Nodes are not marked as being stale, they keep a counter
// that tells how many times in a row they have failed. When
// a new node is to be inserted, the node that has failed
// the most times is replaced. If none of the nodes in the
// bucket has failed, then it is put in the replacement
// cache (just like in the paper).
class TORRENT_EXPORT routing_table
{
public:
routing_table(node_id const& id, int bucket_size
, dht_settings const& settings);
void status(session_status& s) const;
void node_failed(node_id const& id);
// adds an endpoint that will never be added to
// the routing table
void add_router_node(udp::endpoint router);
// iterates over the router nodes added
typedef std::set<udp::endpoint>::const_iterator router_iterator;
router_iterator router_begin() const { return m_router_nodes.begin(); }
router_iterator router_end() const { return m_router_nodes.end(); }
bool add_node(node_entry const& e);
// this function is called every time the node sees
// a sign of a node being alive. This node will either
// be inserted in the k-buckets or be moved to the top
// of its bucket.
bool node_seen(node_id const& id, udp::endpoint ep);
// this may add a node to the routing table and mark it as
// not pinged. If the bucket the node falls into is full,
// the node will be ignored.
void heard_about(node_id const& id, udp::endpoint const& ep);
// if any bucket in the routing table needs to be refreshed
// this function will return true and set the target to an
// appropriate target inside that bucket
bool need_refresh(node_id& target) const;
enum
{
include_failed = 1
};
// fills the vector with the count nodes from our buckets that
// are nearest to the given id.
void find_node(node_id const& id, std::vector<node_entry>& l
, int options, int count = 0);
int bucket_size(int bucket)
{
int num_buckets = m_buckets.size();
if (bucket < num_buckets) bucket = num_buckets - 1;
table_t::iterator i = m_buckets.begin();
std::advance(i, bucket);
return (int)i->live_nodes.size();
}
void for_each_node(void (*)(void*, node_entry const&)
, void (*)(void*, node_entry const&), void* userdata) const;
int bucket_size() const { return m_bucket_size; }
boost::tuple<int, int> size() const;
size_type num_global_nodes() const;
// returns true if there are no working nodes
// in the routing table
bool need_bootstrap() const;
int num_active_buckets() const { return m_buckets.size(); }
void replacement_cache(bucket_t& nodes) const;
#if defined TORRENT_DHT_VERBOSE_LOGGING || defined TORRENT_DEBUG
// used for debug and monitoring purposes. This will print out
// the state of the routing table to the given stream
void print_state(std::ostream& os) const;
#endif
void touch_bucket(node_id const& target);
private:
typedef std::list<routing_table_node> table_t;
table_t::iterator find_bucket(node_id const& id);
// constant called k in paper
int m_bucket_size;
dht_settings const& m_settings;
// (k-bucket, replacement cache) pairs
// the first entry is the bucket the furthest
// away from our own ID. Each time the bucket
// closest to us (m_buckets.back()) has more than
// bucket size nodes in it, another bucket is
// added to the end and it's split up between them
table_t m_buckets;
node_id m_id; // our own node id
// the last time need_bootstrap() returned true
mutable ptime m_last_bootstrap;
// this is a set of all the endpoints that have
// been identified as router nodes. They will
// be used in searches, but they will never
// be added to the routing table.
std::set<udp::endpoint> m_router_nodes;
};
} } // namespace libtorrent::dht
#endif // ROUTING_TABLE_HPP
<commit_msg>added missing include<commit_after>/*
Copyright (c) 2006, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef ROUTING_TABLE_HPP
#define ROUTING_TABLE_HPP
#include <vector>
#include <boost/cstdint.hpp>
#include <boost/utility.hpp>
#include <boost/tuple/tuple.hpp>
#include <boost/array.hpp>
#include <set>
#include <list>
#include <libtorrent/kademlia/logging.hpp>
#include <libtorrent/kademlia/node_id.hpp>
#include <libtorrent/kademlia/node_entry.hpp>
#include <libtorrent/session_settings.hpp>
#include <libtorrent/size_type.hpp>
#include <libtorrent/assert.hpp>
#include <libtorrent/ptime.hpp>
namespace libtorrent
{
struct session_status;
}
namespace libtorrent { namespace dht
{
#ifdef TORRENT_DHT_VERBOSE_LOGGING
TORRENT_DECLARE_LOG(table);
#endif
typedef std::vector<node_entry> bucket_t;
struct routing_table_node
{
bucket_t replacements;
bucket_t live_nodes;
ptime last_active;
};
// differences in the implementation from the description in
// the paper:
//
// * Nodes are not marked as being stale, they keep a counter
// that tells how many times in a row they have failed. When
// a new node is to be inserted, the node that has failed
// the most times is replaced. If none of the nodes in the
// bucket has failed, then it is put in the replacement
// cache (just like in the paper).
class TORRENT_EXPORT routing_table
{
public:
routing_table(node_id const& id, int bucket_size
, dht_settings const& settings);
void status(session_status& s) const;
void node_failed(node_id const& id);
// adds an endpoint that will never be added to
// the routing table
void add_router_node(udp::endpoint router);
// iterates over the router nodes added
typedef std::set<udp::endpoint>::const_iterator router_iterator;
router_iterator router_begin() const { return m_router_nodes.begin(); }
router_iterator router_end() const { return m_router_nodes.end(); }
bool add_node(node_entry const& e);
// this function is called every time the node sees
// a sign of a node being alive. This node will either
// be inserted in the k-buckets or be moved to the top
// of its bucket.
bool node_seen(node_id const& id, udp::endpoint ep);
// this may add a node to the routing table and mark it as
// not pinged. If the bucket the node falls into is full,
// the node will be ignored.
void heard_about(node_id const& id, udp::endpoint const& ep);
// if any bucket in the routing table needs to be refreshed
// this function will return true and set the target to an
// appropriate target inside that bucket
bool need_refresh(node_id& target) const;
enum
{
include_failed = 1
};
// fills the vector with the count nodes from our buckets that
// are nearest to the given id.
void find_node(node_id const& id, std::vector<node_entry>& l
, int options, int count = 0);
int bucket_size(int bucket)
{
int num_buckets = m_buckets.size();
if (bucket < num_buckets) bucket = num_buckets - 1;
table_t::iterator i = m_buckets.begin();
std::advance(i, bucket);
return (int)i->live_nodes.size();
}
void for_each_node(void (*)(void*, node_entry const&)
, void (*)(void*, node_entry const&), void* userdata) const;
int bucket_size() const { return m_bucket_size; }
boost::tuple<int, int> size() const;
size_type num_global_nodes() const;
// returns true if there are no working nodes
// in the routing table
bool need_bootstrap() const;
int num_active_buckets() const { return m_buckets.size(); }
void replacement_cache(bucket_t& nodes) const;
#if defined TORRENT_DHT_VERBOSE_LOGGING || defined TORRENT_DEBUG
// used for debug and monitoring purposes. This will print out
// the state of the routing table to the given stream
void print_state(std::ostream& os) const;
#endif
void touch_bucket(node_id const& target);
private:
typedef std::list<routing_table_node> table_t;
table_t::iterator find_bucket(node_id const& id);
// constant called k in paper
int m_bucket_size;
dht_settings const& m_settings;
// (k-bucket, replacement cache) pairs
// the first entry is the bucket the furthest
// away from our own ID. Each time the bucket
// closest to us (m_buckets.back()) has more than
// bucket size nodes in it, another bucket is
// added to the end and it's split up between them
table_t m_buckets;
node_id m_id; // our own node id
// the last time need_bootstrap() returned true
mutable ptime m_last_bootstrap;
// this is a set of all the endpoints that have
// been identified as router nodes. They will
// be used in searches, but they will never
// be added to the routing table.
std::set<udp::endpoint> m_router_nodes;
};
} } // namespace libtorrent::dht
#endif // ROUTING_TABLE_HPP
<|endoftext|>
|
<commit_before>#include <iostream>
int main(int argc ,char *argv[]) {
std::cout << "Hello World" << std::endl;
return 0;
}
<commit_msg>Change hello_world.cxx<commit_after>#include <iostream>
int main(int argc ,char *argv[]) {
std::cout << "Hello World" << std::endl;
return 0;
}
<|endoftext|>
|
<commit_before>#include <taichi/visualization/image_buffer.h>
#include <taichi/math/linalg.h>
#define STB_IMAGE_IMPLEMENTATION
#define STBI_FAILURE_USERMSG
#include <stb_image.h>
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include <stb_image_write.h>
#define STB_TRUETYPE_IMPLEMENTATION
#include <stb_truetype.h>
TC_NAMESPACE_BEGIN
template<typename T>
void Array2D<T>::load(const std::string &filename) {
int channels;
FILE *f = fopen(filename.c_str(), "rb");
assert_info(f != nullptr, "Image file not found: " + filename);
real *data = stbi_loadf(filename.c_str(), &this->width, &this->height, &channels, 0);
P(stbi_is_hdr(filename.c_str()));
assert_info(data != nullptr, "Image file load failed: " + filename + " # Msg: " + std::string(stbi_failure_reason()));
assert_info(channels == 3 || channels == 4, "Image must have channel 3 or 4: " + filename);
this->initialize(this->width, this->height);
for (int i = 0; i < this->width; i++) {
for (int j = 0; j < this->height; j++) {
real *pixel = data + ((this->height - 1 - j) * this->width + i) * channels;
(*this)[i][j][0] = pixel[0];
(*this)[i][j][1] = pixel[1];
(*this)[i][j][2] = pixel[2];
if (channels == 4 && same_type<T, Vector4>())
(*this)[i][j][3] = pixel[3];
}
}
stbi_image_free(data);
}
template<typename T>
void Array2D<T>::write(const std::string &filename)
{
int comp = 3;
std::vector<unsigned char> data(this->width * this->height * comp);
for (int i = 0; i < this->width; i++) {
for (int j = 0; j < this->height; j++) {
for (int k = 0; k < comp; k++) {
data[j * this->width * comp + i * comp + k] =
(unsigned char)(255.0f * clamp(this->data[i * this->height + (this->height - j - 1)][k], 0.0f, 1.0f));
}
}
}
int write_result = stbi_write_png(filename.c_str(), this->width, this->height, comp, &data[0], comp * this->width);
// assert_info((bool)write_result, "Can not write image file");
}
template<typename T>
void Array2D<T>::write_text(const std::string &font_fn, const std::string &content_, real size,
int dx, int dy) {
std::vector<unsigned char> buffer(24 << 20, (unsigned char)0);
std::vector<unsigned char> screen_buffer((size_t)(this->width * this->height), (unsigned char)0);
static stbtt_fontinfo font;
int i, j, ascent, baseline, ch = 0;
float xpos = 2; // leave a little padding in case the character extends left
static float scale;
// TODO: cache loaded fonts?
FILE *font_file = fopen(font_fn.c_str(), "rb");
assert_info(font_file != nullptr, "Font file not found: " + std::string(font_fn));
fread(&buffer[0], 1, 24 << 20, font_file);
stbtt_InitFont(&font, &buffer[0], 0);
scale = stbtt_ScaleForPixelHeight(&font, size);
stbtt_GetFontVMetrics(&font, &ascent, 0, 0);
baseline = (int)(ascent*scale);
const std::string c_content = content_;
const char *content = c_content.c_str();
while (content[ch]) {
int advance, lsb, x0, y0, x1, y1;
float x_shift = xpos - (float)floor(xpos);
stbtt_GetCodepointHMetrics(&font, content[ch], &advance, &lsb);
stbtt_GetCodepointBitmapBoxSubpixel(&font, content[ch], scale, scale, x_shift, 0, &x0, &y0, &x1, &y1);
stbtt_MakeCodepointBitmapSubpixel(&font, &screen_buffer[0] + this->width * (baseline + y0) + (int)xpos + x0,
x1 - x0, y1 - y0, 200, scale, scale, x_shift, 0, content[ch]);
// note that this stomps the old data, so where character boxes overlap (e.g. 'lj') it's wrong
// because this API is really for baking character bitmaps into textures. if you want to render
// a sequence of characters, you really need to render each bitmap to a temp buffer, then
// "alpha blend" that into the working buffer
xpos += (advance * scale);
if (content[ch + 1])
xpos += scale * stbtt_GetCodepointKernAdvance(&font, content[ch], content[ch + 1]);
++ch;
}
if (dy < 0) {
dy = this->height + dy - 1;
}
for (j = 0; j < this->height; ++j) {
for (i = 0; i < this->width; ++i) {
int x = dx + i, y = dy + j;
float alpha = screen_buffer[(this->height - j - 1) * this->width + i] / 255.0f;
(*this)[x][y] = lerp(alpha, this->get(x, y), T(1.0f));
}
}
}
template
void Array2D<Vector3>::write_text(const std::string &font_fn, const std::string &content_, real size,
int dx, int dy);
template
void Array2D<Vector4>::write_text(const std::string &font_fn, const std::string &content_, real size,
int dx, int dy);
template void Array2D<Vector3>::load(const std::string &filename);
template void Array2D<Vector4>::load(const std::string &filename);
template void Array2D<Vector3>::write(const std::string &filename);
template void Array2D<Vector4>::write(const std::string &filename);
TC_NAMESPACE_END
<commit_msg>Remove debugging statement<commit_after>#include <taichi/visualization/image_buffer.h>
#include <taichi/math/linalg.h>
#define STB_IMAGE_IMPLEMENTATION
#define STBI_FAILURE_USERMSG
#include <stb_image.h>
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include <stb_image_write.h>
#define STB_TRUETYPE_IMPLEMENTATION
#include <stb_truetype.h>
TC_NAMESPACE_BEGIN
template<typename T>
void Array2D<T>::load(const std::string &filename) {
int channels;
FILE *f = fopen(filename.c_str(), "rb");
assert_info(f != nullptr, "Image file not found: " + filename);
real *data = stbi_loadf(filename.c_str(), &this->width, &this->height, &channels, 0);
assert_info(data != nullptr, "Image file load failed: " + filename + " # Msg: " + std::string(stbi_failure_reason()));
assert_info(channels == 3 || channels == 4, "Image must have channel 3 or 4: " + filename);
this->initialize(this->width, this->height);
for (int i = 0; i < this->width; i++) {
for (int j = 0; j < this->height; j++) {
real *pixel = data + ((this->height - 1 - j) * this->width + i) * channels;
(*this)[i][j][0] = pixel[0];
(*this)[i][j][1] = pixel[1];
(*this)[i][j][2] = pixel[2];
if (channels == 4 && same_type<T, Vector4>())
(*this)[i][j][3] = pixel[3];
}
}
stbi_image_free(data);
}
template<typename T>
void Array2D<T>::write(const std::string &filename)
{
int comp = 3;
std::vector<unsigned char> data(this->width * this->height * comp);
for (int i = 0; i < this->width; i++) {
for (int j = 0; j < this->height; j++) {
for (int k = 0; k < comp; k++) {
data[j * this->width * comp + i * comp + k] =
(unsigned char)(255.0f * clamp(this->data[i * this->height + (this->height - j - 1)][k], 0.0f, 1.0f));
}
}
}
int write_result = stbi_write_png(filename.c_str(), this->width, this->height, comp, &data[0], comp * this->width);
// assert_info((bool)write_result, "Can not write image file");
}
template<typename T>
void Array2D<T>::write_text(const std::string &font_fn, const std::string &content_, real size,
int dx, int dy) {
std::vector<unsigned char> buffer(24 << 20, (unsigned char)0);
std::vector<unsigned char> screen_buffer((size_t)(this->width * this->height), (unsigned char)0);
static stbtt_fontinfo font;
int i, j, ascent, baseline, ch = 0;
float xpos = 2; // leave a little padding in case the character extends left
static float scale;
// TODO: cache loaded fonts?
FILE *font_file = fopen(font_fn.c_str(), "rb");
assert_info(font_file != nullptr, "Font file not found: " + std::string(font_fn));
fread(&buffer[0], 1, 24 << 20, font_file);
stbtt_InitFont(&font, &buffer[0], 0);
scale = stbtt_ScaleForPixelHeight(&font, size);
stbtt_GetFontVMetrics(&font, &ascent, 0, 0);
baseline = (int)(ascent*scale);
const std::string c_content = content_;
const char *content = c_content.c_str();
while (content[ch]) {
int advance, lsb, x0, y0, x1, y1;
float x_shift = xpos - (float)floor(xpos);
stbtt_GetCodepointHMetrics(&font, content[ch], &advance, &lsb);
stbtt_GetCodepointBitmapBoxSubpixel(&font, content[ch], scale, scale, x_shift, 0, &x0, &y0, &x1, &y1);
stbtt_MakeCodepointBitmapSubpixel(&font, &screen_buffer[0] + this->width * (baseline + y0) + (int)xpos + x0,
x1 - x0, y1 - y0, 200, scale, scale, x_shift, 0, content[ch]);
// note that this stomps the old data, so where character boxes overlap (e.g. 'lj') it's wrong
// because this API is really for baking character bitmaps into textures. if you want to render
// a sequence of characters, you really need to render each bitmap to a temp buffer, then
// "alpha blend" that into the working buffer
xpos += (advance * scale);
if (content[ch + 1])
xpos += scale * stbtt_GetCodepointKernAdvance(&font, content[ch], content[ch + 1]);
++ch;
}
if (dy < 0) {
dy = this->height + dy - 1;
}
for (j = 0; j < this->height; ++j) {
for (i = 0; i < this->width; ++i) {
int x = dx + i, y = dy + j;
float alpha = screen_buffer[(this->height - j - 1) * this->width + i] / 255.0f;
(*this)[x][y] = lerp(alpha, this->get(x, y), T(1.0f));
}
}
}
template
void Array2D<Vector3>::write_text(const std::string &font_fn, const std::string &content_, real size,
int dx, int dy);
template
void Array2D<Vector4>::write_text(const std::string &font_fn, const std::string &content_, real size,
int dx, int dy);
template void Array2D<Vector3>::load(const std::string &filename);
template void Array2D<Vector4>::load(const std::string &filename);
template void Array2D<Vector3>::write(const std::string &filename);
template void Array2D<Vector4>::write(const std::string &filename);
TC_NAMESPACE_END
<|endoftext|>
|
<commit_before>#ifndef GP_NODE_CONST_NODE
#define GP_NODE_CONST_NODE
#include "node_base.hpp"
#include <sstream>
namespace gp::node {
namespace const_node {
constexpr const char* nameHeader = "Const[";
constexpr char nameDelimiter = ']';
constexpr char propertySeparator = ',';
}
template <typename T>
class ConstNode: public NodeBase<T(void)> {
private:
using ThisType = ConstNode;
using node_instance_type = NodeInterface::node_instance_type;
T data;
private:
T evaluationDefinition(utility::EvaluationContext& evaluationContext)const override {
return data;
}
public:
std::string getNodeName()const override {
std::stringstream sstream;
sstream << const_node::propertySeparator << data;
return std::string(const_node::nameHeader) + utility::typeInfo<T>().name() + sstream.str() + std::string(1, const_node::nameDelimiter);
}
node_instance_type clone()const override {return NodeInterface::createInstance<ThisType>(data);}
NodeType getNodeType()const noexcept override final {return NodeType::Const;}
void setNodePropertyByNodeName(const std::string& name) override {
auto beg = name.find('[');
auto end = name.find(']');
if(beg == std::string::npos || end == std::string::npos || end < beg) throw std::invalid_argument("invalid node name of const node");
auto sep = name.find(',', beg);
if(sep == std::string::npos || end < sep) throw std::invalid_argument("invalid node name of const node");
std::stringstream sstream;
sstream << name.substr(sep + 1, end - sep - 1);
sstream >> data;
}
void setNodePropertyByAny(const std::any& prop) override {
assert(prop.type() == typeid(T));
data = std::any_cast<T>(prop);
}
std::any getNodePropertyByAny()const override {return data;}
public:
ConstNode(T&& val): data(std::move(val)){}
ConstNode(const T& val): data(val){}
ConstNode() = default;
ConstNode(const ConstNode&) = default;
ConstNode(ConstNode&&) = default;
ConstNode& operator=(const ConstNode&) = default;
ConstNode& operator=(ConstNode&&) = default;
~ConstNode() = default;
};
}
#endif
<commit_msg>add static_assertion<commit_after>#ifndef GP_NODE_CONST_NODE
#define GP_NODE_CONST_NODE
#include "node_base.hpp"
#include <gp/utility/is_match_template.hpp>
#include <sstream>
namespace gp::node {
namespace const_node {
constexpr const char* nameHeader = "Const[";
constexpr char nameDelimiter = ']';
constexpr char propertySeparator = ',';
}
template <typename T>
class ConstNode: public NodeBase<T(void)> {
static_assert(!utility::is_match_template_v<utility::LeftHandValue, T>
&& !utility::is_match_template_v<utility::Reference, T>);
private:
using ThisType = ConstNode;
using node_instance_type = NodeInterface::node_instance_type;
T data;
private:
T evaluationDefinition(utility::EvaluationContext& evaluationContext)const override {
return data;
}
public:
std::string getNodeName()const override {
std::stringstream sstream;
sstream << const_node::propertySeparator << data;
return std::string(const_node::nameHeader) + utility::typeInfo<T>().name() + sstream.str() + std::string(1, const_node::nameDelimiter);
}
node_instance_type clone()const override {return NodeInterface::createInstance<ThisType>(data);}
NodeType getNodeType()const noexcept override final {return NodeType::Const;}
void setNodePropertyByNodeName(const std::string& name) override {
auto beg = name.find('[');
auto end = name.find(']');
if(beg == std::string::npos || end == std::string::npos || end < beg) throw std::invalid_argument("invalid node name of const node");
auto sep = name.find(',', beg);
if(sep == std::string::npos || end < sep) throw std::invalid_argument("invalid node name of const node");
std::stringstream sstream;
sstream << name.substr(sep + 1, end - sep - 1);
sstream >> data;
}
void setNodePropertyByAny(const std::any& prop) override {
assert(prop.type() == typeid(T));
data = std::any_cast<T>(prop);
}
std::any getNodePropertyByAny()const override {return data;}
public:
ConstNode(T&& val): data(std::move(val)){}
ConstNode(const T& val): data(val){}
ConstNode() = default;
ConstNode(const ConstNode&) = default;
ConstNode(ConstNode&&) = default;
ConstNode& operator=(const ConstNode&) = default;
ConstNode& operator=(ConstNode&&) = default;
~ConstNode() = default;
};
}
#endif
<|endoftext|>
|
<commit_before>/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/tf2tensorrt/convert/trt_optimization_pass.h"
#include "absl/strings/ascii.h"
#include "absl/strings/escaping.h"
#include "absl/strings/str_cat.h"
#include "tensorflow/compiler/tf2tensorrt/convert/convert_graph.h"
#include "tensorflow/compiler/tf2tensorrt/convert/utils.h"
#include "tensorflow/core/grappler/clusters/cluster.h"
#include "tensorflow/core/grappler/grappler_item.h"
#include "tensorflow/core/grappler/optimizers/custom_graph_optimizer_registry.h"
#include "tensorflow/core/lib/strings/numbers.h"
#include "tensorflow/core/lib/strings/str_util.h"
#include "tensorflow/core/lib/strings/strcat.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/stacktrace.h"
#if GOOGLE_CUDA && GOOGLE_TENSORRT
namespace tensorflow {
namespace tensorrt {
namespace convert {
// TODO(sami): Remove VLOG messages once the code matures
using absl::AsciiStrToUpper;
using absl::StrAppend;
using absl::StrCat;
Status TRTOptimizationPass::Init(
const RewriterConfig_CustomGraphOptimizer* config) {
VLOG(1) << "Called INIT for " << name_ << " with config = " << config;
if (config == nullptr) {
return Status::OK();
}
VLOG(1) << "config = " << config->DebugString();
const auto params = config->parameter_map();
if (params.count("minimum_segment_size")) {
minimum_segment_size_ = params.at("minimum_segment_size").i();
}
if (params.count("max_batch_size")) {
maximum_batch_size_ = params.at("max_batch_size").i();
}
if (params.count("is_dynamic_op")) {
is_dynamic_op_ = params.at("is_dynamic_op").b();
}
if (params.count("maximum_cached_engines")) {
max_cached_batches_ = params.at("maximum_cached_engines").i();
}
if (params.count("max_workspace_size_bytes")) {
max_workspace_size_bytes_ = params.at("max_workspace_size_bytes").i();
}
if (params.count("precision_mode")) {
TF_RETURN_IF_ERROR(TrtPrecisionModeFromName(
AsciiStrToUpper(params.at("precision_mode").s()), &precision_mode_));
}
if (params.count("use_calibration")) {
use_calibration_ = params.at("use_calibration").b();
}
if (params.count("trt_logger")) {
trt_logger_name_ = params.at("trt_logger").s();
}
if (params.count("allow_build_at_runtime")) {
allow_build_at_runtime_ = params.at("allow_build_at_runtime").b();
}
if (params.count("use_implicit_batch")) {
use_implicit_batch_ = params.at("use_implicit_batch").b();
}
return Status::OK();
}
void TRTOptimizationPass::PrintDebugInfo(grappler::Cluster* cluster,
const grappler::GrapplerItem& item) {
LOG(INFO) << "Cluster = " << cluster;
string offset(" ");
string offset2 = StrCat(offset, offset);
string offset3 = StrCat(offset2, offset);
string offset4 = StrCat(offset2, offset2);
if (cluster) {
LOG(INFO) << offset << "type = " << cluster->type();
LOG(INFO) << offset << "num warmup steps = " << cluster->NumWarmupSteps();
const auto dev_names = cluster->GetDeviceNames();
if (!dev_names.empty()) {
LOG(INFO) << offset << " Device names:";
for (const auto& s : dev_names) {
LOG(INFO) << offset2 << s;
}
}
std::unordered_map<string, uint64> peak_mem;
auto status = cluster->GetPeakMemoryUsage(&peak_mem);
if (status == Status::OK()) {
LOG(INFO) << offset << "Peak Memory Usage :";
for (const auto& s : peak_mem) {
LOG(INFO) << offset2 << s.first << " = " << s.second;
}
}
const auto dev_props = cluster->GetDevices();
if (!dev_props.empty()) {
LOG(INFO) << offset << "Device properties:";
for (const auto& k : dev_props) {
LOG(INFO) << offset2 << k.first;
const auto& dt = k.second;
LOG(INFO) << offset3 << "type = " << dt.type();
LOG(INFO) << offset3 << "vendor = " << dt.vendor();
LOG(INFO) << offset3 << "model = " << dt.model();
LOG(INFO) << offset3 << "frequency = " << dt.frequency();
LOG(INFO) << offset3 << "num cores = " << dt.num_cores();
LOG(INFO) << offset3 << "num registers = " << dt.num_registers();
LOG(INFO) << offset3 << "L1 cache size = " << dt.l1_cache_size();
LOG(INFO) << offset3 << "L2 cache size = " << dt.l2_cache_size();
LOG(INFO) << offset3 << "L3 cache size = " << dt.l3_cache_size();
LOG(INFO) << offset3 << "SHMem per SMP = "
<< dt.shared_memory_size_per_multiprocessor();
LOG(INFO) << offset3 << "memory size = " << dt.memory_size();
LOG(INFO) << offset3 << "bandwidth = " << dt.bandwidth();
if (dt.environment_size()) {
LOG(INFO) << offset3 << "environment :";
for (const auto& e : dt.environment()) {
LOG(INFO) << offset4 << e.first << " = " << e.second;
}
}
}
}
}
LOG(INFO) << "item: " << item.id;
if (!item.feed.empty()) {
LOG(INFO) << offset << "Feeds :";
for (const auto& f : item.feed) {
const auto& shape = f.second.shape();
LOG(INFO) << offset2 << f.first << " = shaped " << shape.DebugString();
}
} else {
LOG(INFO) << offset << "No Feeds";
}
if (!item.fetch.empty()) {
LOG(INFO) << offset << "Fetches :";
for (const auto& f : item.fetch) {
LOG(INFO) << offset2 << f;
}
} else {
LOG(INFO) << offset << "No Fetches";
}
if (!item.init_ops.empty()) {
LOG(INFO) << offset << "init ops :";
for (const auto& f : item.init_ops) {
LOG(INFO) << offset2 << f;
}
} else {
LOG(INFO) << offset << "No init ops";
}
LOG(INFO) << "Save Op = " << item.save_op;
LOG(INFO) << "Restore Op = " << item.restore_op;
LOG(INFO) << "save_restore_loc_tensor = " << item.save_restore_loc_tensor;
if (!item.keep_ops.empty()) {
LOG(INFO) << offset << "keep ops :";
for (const auto& f : item.keep_ops) {
LOG(INFO) << offset2 << f;
}
} else {
LOG(INFO) << offset << "No keep ops";
}
for (const auto dev : cluster->GetDeviceSet()->devices()) {
const auto& pname = dev->parsed_name();
LOG(INFO) << "Device name= " << dev->name()
<< " parsedname job= " << pname.job << " id= " << pname.id
<< " has_id: " << pname.has_id << " has_job: " << pname.has_job
<< "has_type: " << pname.has_type << " type =" << pname.type;
}
}
Status TRTOptimizationPass::Optimize(grappler::Cluster* cluster,
const grappler::GrapplerItem& item,
GraphDef* optimized_graph) {
VLOG(1) << "Called TRTOptimization Pass " << name_;
// This is a hack to workaround optimizer issue. MetaOptimizer calls
// optimization passes on function objects as well, we should not modify
// generated funcdefs! This is fragile but we don't have any other option
// until framework fixes it.
if (item.id != "tf_graph") {
VLOG(1) << "Called TRTOptimization Pass " << name_
<< " on a grappler item with id=" << item.id
<< ", which is probably a function object (funcdef). "
<< "Skipping optimization because TensorRTOptimizer "
<< "should not be called on function objects.";
*optimized_graph = item.graph;
return Status::OK();
}
if (VLOG_IS_ON(3)) {
LOG(INFO) << CurrentStackTrace();
PrintDebugInfo(cluster, item);
}
if (!is_dynamic_op_) {
int max_batch_dim = -1;
if (!item.feed.empty()) {
for (const auto& f : item.feed) {
const auto& shape = f.second.shape();
if (shape.dims() > 0) {
if (shape.dim_size(0) > max_batch_dim)
max_batch_dim = shape.dim_size(0);
VLOG(2) << "Setting max_batch_dim to " << max_batch_dim
<< " using batch dimension of " << f.first << " with shape "
<< shape;
}
}
}
if (max_batch_dim > maximum_batch_size_) {
return errors::InvalidArgument(
"Specified max_batch_size=", maximum_batch_size_,
" is less than maximum batch dimension of inputs (", max_batch_dim,
"). ", "To continue, set max_batch_size to >= ", max_batch_dim);
} else if (max_batch_dim < maximum_batch_size_) {
LOG(INFO) << "Specified max_batch_size=" << maximum_batch_size_
<< " is larger than maximum batch dimension of inputs ("
<< max_batch_dim << "). "
<< "This can result in poor performance.";
}
}
if (use_calibration_ && precision_mode_ != TrtPrecisionMode::INT8) {
VLOG(1) << "Calibration with FP32 or FP16 is not implemented. "
<< "Falling back to use_calibration = False."
<< "Note that the default value of use_calibration is True.";
use_calibration_ = false;
}
std::vector<string> nodes_to_preserve;
for (const auto& n : item.NodesToPreserve()) {
auto tokens = str_util::Split(n, ":");
string s = tokens.at(0);
for (int i = 1; i < tokens.size() - 1; ++i) {
StrAppend(&s, ":", tokens.at(i));
}
int dumm_port = -1;
// If the last token is not an integer, it must be part of the name.
// Otherwise it is port number.
if (tokens.size() > 1 &&
!strings::safe_strto32(tokens.back(), &dumm_port)) { // non-absl ok
StrAppend(&s, ":", tokens.back());
}
nodes_to_preserve.push_back(s);
}
ConversionParams cp;
cp.grappler_item = &item;
cp.output_names = &nodes_to_preserve;
cp.trt_logger_name = trt_logger_name_;
cp.max_batch_size = maximum_batch_size_;
cp.max_workspace_size_bytes = max_workspace_size_bytes_;
cp.output_graph_def = optimized_graph;
cp.precision_mode = precision_mode_;
cp.minimum_segment_size = minimum_segment_size_;
cp.cluster = cluster;
cp.is_dyn_op = is_dynamic_op_;
cp.max_cached_engines = max_cached_batches_;
cp.use_calibration = use_calibration_;
cp.use_implicit_batch = use_implicit_batch_;
cp.allow_build_at_runtime = allow_build_at_runtime_;
auto status = ConvertAfterShapes(cp);
VLOG(1) << "Returning from " << name_;
return status;
}
void TRTOptimizationPass::Feedback(grappler::Cluster* cluster,
const grappler::GrapplerItem& item,
const GraphDef& optimized_graph,
double result) {}
class VerboseCustomGraphOptimizerRegistrar
: public grappler::CustomGraphOptimizerRegistrar {
public:
VerboseCustomGraphOptimizerRegistrar(
const grappler::CustomGraphOptimizerRegistry::Creator& cr,
const string& name)
: grappler::CustomGraphOptimizerRegistrar(cr, name) {
VLOG(1) << "Constructing a CustomOptimizationPass registration object for "
<< name;
}
};
static VerboseCustomGraphOptimizerRegistrar TRTOptimizationPass_Registrar(
[]() {
VLOG(1)
<< "Instantiating CustomOptimizationPass object TensorRTOptimizer";
return new TRTOptimizationPass("TensorRTOptimizer");
},
("TensorRTOptimizer"));
} // namespace convert
} // namespace tensorrt
} // namespace tensorflow
#endif // GOOGLE_CUDA && GOOGLE_TENSORRT
<commit_msg>[TF:TRT] Avoid null pointer accesses in TRTOptimizationPass::PrintDebugInfo.<commit_after>/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/tf2tensorrt/convert/trt_optimization_pass.h"
#include "absl/strings/ascii.h"
#include "absl/strings/escaping.h"
#include "absl/strings/str_cat.h"
#include "tensorflow/compiler/tf2tensorrt/convert/convert_graph.h"
#include "tensorflow/compiler/tf2tensorrt/convert/utils.h"
#include "tensorflow/core/grappler/clusters/cluster.h"
#include "tensorflow/core/grappler/grappler_item.h"
#include "tensorflow/core/grappler/optimizers/custom_graph_optimizer_registry.h"
#include "tensorflow/core/lib/strings/numbers.h"
#include "tensorflow/core/lib/strings/str_util.h"
#include "tensorflow/core/lib/strings/strcat.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/stacktrace.h"
#if GOOGLE_CUDA && GOOGLE_TENSORRT
namespace tensorflow {
namespace tensorrt {
namespace convert {
// TODO(sami): Remove VLOG messages once the code matures
using absl::AsciiStrToUpper;
using absl::StrAppend;
using absl::StrCat;
Status TRTOptimizationPass::Init(
const RewriterConfig_CustomGraphOptimizer* config) {
VLOG(1) << "Called INIT for " << name_ << " with config = " << config;
if (config == nullptr) {
return Status::OK();
}
VLOG(1) << "config = " << config->DebugString();
const auto params = config->parameter_map();
if (params.count("minimum_segment_size")) {
minimum_segment_size_ = params.at("minimum_segment_size").i();
}
if (params.count("max_batch_size")) {
maximum_batch_size_ = params.at("max_batch_size").i();
}
if (params.count("is_dynamic_op")) {
is_dynamic_op_ = params.at("is_dynamic_op").b();
}
if (params.count("maximum_cached_engines")) {
max_cached_batches_ = params.at("maximum_cached_engines").i();
}
if (params.count("max_workspace_size_bytes")) {
max_workspace_size_bytes_ = params.at("max_workspace_size_bytes").i();
}
if (params.count("precision_mode")) {
TF_RETURN_IF_ERROR(TrtPrecisionModeFromName(
AsciiStrToUpper(params.at("precision_mode").s()), &precision_mode_));
}
if (params.count("use_calibration")) {
use_calibration_ = params.at("use_calibration").b();
}
if (params.count("trt_logger")) {
trt_logger_name_ = params.at("trt_logger").s();
}
if (params.count("allow_build_at_runtime")) {
allow_build_at_runtime_ = params.at("allow_build_at_runtime").b();
}
if (params.count("use_implicit_batch")) {
use_implicit_batch_ = params.at("use_implicit_batch").b();
}
return Status::OK();
}
void TRTOptimizationPass::PrintDebugInfo(grappler::Cluster* cluster,
const grappler::GrapplerItem& item) {
LOG(INFO) << "Cluster = " << cluster;
string offset(" ");
string offset2 = StrCat(offset, offset);
string offset3 = StrCat(offset2, offset);
string offset4 = StrCat(offset2, offset2);
if (cluster) {
LOG(INFO) << offset << "type = " << cluster->type();
LOG(INFO) << offset << "num warmup steps = " << cluster->NumWarmupSteps();
const auto dev_names = cluster->GetDeviceNames();
if (!dev_names.empty()) {
LOG(INFO) << offset << " Device names:";
for (const auto& s : dev_names) {
LOG(INFO) << offset2 << s;
}
}
std::unordered_map<string, uint64> peak_mem;
auto status = cluster->GetPeakMemoryUsage(&peak_mem);
if (status == Status::OK()) {
LOG(INFO) << offset << "Peak Memory Usage :";
for (const auto& s : peak_mem) {
LOG(INFO) << offset2 << s.first << " = " << s.second;
}
}
const auto dev_props = cluster->GetDevices();
if (!dev_props.empty()) {
LOG(INFO) << offset << "Device properties:";
for (const auto& k : dev_props) {
LOG(INFO) << offset2 << k.first;
const auto& dt = k.second;
LOG(INFO) << offset3 << "type = " << dt.type();
LOG(INFO) << offset3 << "vendor = " << dt.vendor();
LOG(INFO) << offset3 << "model = " << dt.model();
LOG(INFO) << offset3 << "frequency = " << dt.frequency();
LOG(INFO) << offset3 << "num cores = " << dt.num_cores();
LOG(INFO) << offset3 << "num registers = " << dt.num_registers();
LOG(INFO) << offset3 << "L1 cache size = " << dt.l1_cache_size();
LOG(INFO) << offset3 << "L2 cache size = " << dt.l2_cache_size();
LOG(INFO) << offset3 << "L3 cache size = " << dt.l3_cache_size();
LOG(INFO) << offset3 << "SHMem per SMP = "
<< dt.shared_memory_size_per_multiprocessor();
LOG(INFO) << offset3 << "memory size = " << dt.memory_size();
LOG(INFO) << offset3 << "bandwidth = " << dt.bandwidth();
if (dt.environment_size()) {
LOG(INFO) << offset3 << "environment :";
for (const auto& e : dt.environment()) {
LOG(INFO) << offset4 << e.first << " = " << e.second;
}
}
}
}
if (cluster->GetDeviceSet()) {
for (const auto dev : cluster->GetDeviceSet()->devices()) {
LOG(INFO) << "Device name= " << dev->name() << "Pased name= "
<< DeviceNameUtils::ParsedNameToString(dev->parsed_name());
}
}
}
LOG(INFO) << "item: " << item.id;
if (!item.feed.empty()) {
LOG(INFO) << offset << "Feeds :";
for (const auto& f : item.feed) {
const auto& shape = f.second.shape();
LOG(INFO) << offset2 << f.first << " = shaped " << shape.DebugString();
}
} else {
LOG(INFO) << offset << "No Feeds";
}
if (!item.fetch.empty()) {
LOG(INFO) << offset << "Fetches :";
for (const auto& f : item.fetch) {
LOG(INFO) << offset2 << f;
}
} else {
LOG(INFO) << offset << "No Fetches";
}
if (!item.init_ops.empty()) {
LOG(INFO) << offset << "init ops :";
for (const auto& f : item.init_ops) {
LOG(INFO) << offset2 << f;
}
} else {
LOG(INFO) << offset << "No init ops";
}
LOG(INFO) << "Save Op = " << item.save_op;
LOG(INFO) << "Restore Op = " << item.restore_op;
LOG(INFO) << "save_restore_loc_tensor = " << item.save_restore_loc_tensor;
if (!item.keep_ops.empty()) {
LOG(INFO) << offset << "keep ops :";
for (const auto& f : item.keep_ops) {
LOG(INFO) << offset2 << f;
}
} else {
LOG(INFO) << offset << "No keep ops";
}
}
Status TRTOptimizationPass::Optimize(grappler::Cluster* cluster,
const grappler::GrapplerItem& item,
GraphDef* optimized_graph) {
VLOG(1) << "Called TRTOptimization Pass " << name_;
// This is a hack to workaround optimizer issue. MetaOptimizer calls
// optimization passes on function objects as well, we should not modify
// generated funcdefs! This is fragile but we don't have any other option
// until framework fixes it.
if (item.id != "tf_graph") {
VLOG(1) << "Called TRTOptimization Pass " << name_
<< " on a grappler item with id=" << item.id
<< ", which is probably a function object (funcdef). "
<< "Skipping optimization because TensorRTOptimizer "
<< "should not be called on function objects.";
*optimized_graph = item.graph;
return Status::OK();
}
if (VLOG_IS_ON(3)) {
LOG(INFO) << CurrentStackTrace();
PrintDebugInfo(cluster, item);
}
if (!is_dynamic_op_) {
int max_batch_dim = -1;
if (!item.feed.empty()) {
for (const auto& f : item.feed) {
const auto& shape = f.second.shape();
if (shape.dims() > 0) {
if (shape.dim_size(0) > max_batch_dim)
max_batch_dim = shape.dim_size(0);
VLOG(2) << "Setting max_batch_dim to " << max_batch_dim
<< " using batch dimension of " << f.first << " with shape "
<< shape;
}
}
}
if (max_batch_dim > maximum_batch_size_) {
return errors::InvalidArgument(
"Specified max_batch_size=", maximum_batch_size_,
" is less than maximum batch dimension of inputs (", max_batch_dim,
"). ", "To continue, set max_batch_size to >= ", max_batch_dim);
} else if (max_batch_dim < maximum_batch_size_) {
LOG(INFO) << "Specified max_batch_size=" << maximum_batch_size_
<< " is larger than maximum batch dimension of inputs ("
<< max_batch_dim << "). "
<< "This can result in poor performance.";
}
}
if (use_calibration_ && precision_mode_ != TrtPrecisionMode::INT8) {
VLOG(1) << "Calibration with FP32 or FP16 is not implemented. "
<< "Falling back to use_calibration = False."
<< "Note that the default value of use_calibration is True.";
use_calibration_ = false;
}
std::vector<string> nodes_to_preserve;
for (const auto& n : item.NodesToPreserve()) {
auto tokens = str_util::Split(n, ":");
string s = tokens.at(0);
for (int i = 1; i < tokens.size() - 1; ++i) {
StrAppend(&s, ":", tokens.at(i));
}
int dumm_port = -1;
// If the last token is not an integer, it must be part of the name.
// Otherwise it is port number.
if (tokens.size() > 1 &&
!strings::safe_strto32(tokens.back(), &dumm_port)) { // non-absl ok
StrAppend(&s, ":", tokens.back());
}
nodes_to_preserve.push_back(s);
}
ConversionParams cp;
cp.grappler_item = &item;
cp.output_names = &nodes_to_preserve;
cp.trt_logger_name = trt_logger_name_;
cp.max_batch_size = maximum_batch_size_;
cp.max_workspace_size_bytes = max_workspace_size_bytes_;
cp.output_graph_def = optimized_graph;
cp.precision_mode = precision_mode_;
cp.minimum_segment_size = minimum_segment_size_;
cp.cluster = cluster;
cp.is_dyn_op = is_dynamic_op_;
cp.max_cached_engines = max_cached_batches_;
cp.use_calibration = use_calibration_;
cp.use_implicit_batch = use_implicit_batch_;
cp.allow_build_at_runtime = allow_build_at_runtime_;
auto status = ConvertAfterShapes(cp);
VLOG(1) << "Returning from " << name_;
return status;
}
void TRTOptimizationPass::Feedback(grappler::Cluster* cluster,
const grappler::GrapplerItem& item,
const GraphDef& optimized_graph,
double result) {}
class VerboseCustomGraphOptimizerRegistrar
: public grappler::CustomGraphOptimizerRegistrar {
public:
VerboseCustomGraphOptimizerRegistrar(
const grappler::CustomGraphOptimizerRegistry::Creator& cr,
const string& name)
: grappler::CustomGraphOptimizerRegistrar(cr, name) {
VLOG(1) << "Constructing a CustomOptimizationPass registration object for "
<< name;
}
};
static VerboseCustomGraphOptimizerRegistrar TRTOptimizationPass_Registrar(
[]() {
VLOG(1)
<< "Instantiating CustomOptimizationPass object TensorRTOptimizer";
return new TRTOptimizationPass("TensorRTOptimizer");
},
("TensorRTOptimizer"));
} // namespace convert
} // namespace tensorrt
} // namespace tensorflow
#endif // GOOGLE_CUDA && GOOGLE_TENSORRT
<|endoftext|>
|
<commit_before>//
// frame_selector.cpp
// Projectname: amos-ss16-proj5
//
// Created on 21.05.2016.
// 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 <sstream>
#include "frame_selector.h"
namespace patch{
template < typename T > std::string to_string( const T& n ){
std::ostringstream stm ;
stm << n ;
return stm.str() ;
}
}
FrameSelector::FrameSelector(std::string file){
file_name_ = file;
hdf_reader_ = new HDFReader(file);
// read hdf5 file
hdf_reader_->ReadFile();
}
FrameSelector::~FrameSelector(){
delete hdf_reader_;
}
Image FrameSelector::ReadImage(unsigned int frame_index){
// get the protobuf payload from hdf5 reader
std::vector<int64_t> protobuf_file_buffer = hdf_reader_->ReadOneProtobufFile(frame_index);
int protobuf_file_size = protobuf_file_buffer.size();
// convert to char array
unsigned char* file = ConvertProtobufFileToArray(protobuf_file_buffer);
//convert protobuf file buffer to msgCameraImage and read image from protobuf file
ProtobufImageWrapper protobuf_image;
protobuf_image.ParseFromArray(file, protobuf_file_size);
// create an Image from msgCameraImage
Image result_image(protobuf_image.GetImagePayload(), protobuf_image.GetImageWidth(), protobuf_image.GetImageHeight());
std::cout << "Protobuf file: WIDTH: " << result_image.GetImageWidth() << " HEIGHT: " << result_image.GetImageHeight() << std::endl;
std::cout << " Size of payload: " << result_image.GetImagePayload().size() << std::endl;
std::cout << " Hash of payload: " << std::hash<std::string>()(result_image.GetImagePayload()) << std::endl;
return result_image;
}
int FrameSelector::GetImageCount(){
return hdf_reader_->GetNumberOfProtobufFiles();
}
std::vector<Image> FrameSelector::ReadAllImages(){
std::vector<std::vector<int64_t> > all_protobuf_files = hdf_reader_->ReadAllProtobufFiles();
//all result images
std::vector<Image> result_images;
for(int i = 0; i < all_protobuf_files.size(); i++){
// convert current image
unsigned char* file = ConvertProtobufFileToArray(all_protobuf_files.at(i));
ProtobufImageWrapper protobuf_image;
protobuf_image.ParseFromArray(file, all_protobuf_files.at(i).size());
Image current_image(protobuf_image.GetImagePayload(), protobuf_image.GetImageWidth(), protobuf_image.GetImageHeight());
result_images.push_back(current_image);
}
return result_images;
}
unsigned char* FrameSelector::ConvertProtobufFileToArray(std::vector<int64_t> file){
int size = file.size();
unsigned char *file_array = new unsigned char[size];
for(int i = 0; i < size; i++){
file_array[i] = static_cast<unsigned char>(file.at(i));
}
return file_array;
}
<commit_msg>removed hash because the travis compiler does not support it<commit_after>//
// frame_selector.cpp
// Projectname: amos-ss16-proj5
//
// Created on 21.05.2016.
// 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 <sstream>
#include "frame_selector.h"
namespace patch{
template < typename T > std::string to_string( const T& n ){
std::ostringstream stm ;
stm << n ;
return stm.str() ;
}
}
FrameSelector::FrameSelector(std::string file){
file_name_ = file;
hdf_reader_ = new HDFReader(file);
// read hdf5 file
hdf_reader_->ReadFile();
}
FrameSelector::~FrameSelector(){
delete hdf_reader_;
}
Image FrameSelector::ReadImage(unsigned int frame_index){
// get the protobuf payload from hdf5 reader
std::vector<int64_t> protobuf_file_buffer = hdf_reader_->ReadOneProtobufFile(frame_index);
int protobuf_file_size = protobuf_file_buffer.size();
// convert to char array
unsigned char* file = ConvertProtobufFileToArray(protobuf_file_buffer);
//convert protobuf file buffer to msgCameraImage and read image from protobuf file
ProtobufImageWrapper protobuf_image;
protobuf_image.ParseFromArray(file, protobuf_file_size);
// create an Image from msgCameraImage
Image result_image(protobuf_image.GetImagePayload(), protobuf_image.GetImageWidth(), protobuf_image.GetImageHeight());
std::cout << "Protobuf file: WIDTH: " << result_image.GetImageWidth() << " HEIGHT: " << result_image.GetImageHeight() << std::endl;
std::cout << " Size of payload: " << result_image.GetImagePayload().size() << std::endl;
return result_image;
}
int FrameSelector::GetImageCount(){
return hdf_reader_->GetNumberOfProtobufFiles();
}
std::vector<Image> FrameSelector::ReadAllImages(){
std::vector<std::vector<int64_t> > all_protobuf_files = hdf_reader_->ReadAllProtobufFiles();
//all result images
std::vector<Image> result_images;
for(int i = 0; i < all_protobuf_files.size(); i++){
// convert current image
unsigned char* file = ConvertProtobufFileToArray(all_protobuf_files.at(i));
ProtobufImageWrapper protobuf_image;
protobuf_image.ParseFromArray(file, all_protobuf_files.at(i).size());
Image current_image(protobuf_image.GetImagePayload(), protobuf_image.GetImageWidth(), protobuf_image.GetImageHeight());
result_images.push_back(current_image);
}
return result_images;
}
unsigned char* FrameSelector::ConvertProtobufFileToArray(std::vector<int64_t> file){
int size = file.size();
unsigned char *file_array = new unsigned char[size];
for(int i = 0; i < size; i++){
file_array[i] = static_cast<unsigned char>(file.at(i));
}
return file_array;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2007 Digital Bazaar, Inc. All rights reserved.
*/
#include "db/event/Observable.h"
using namespace std;
using namespace db::event;
using namespace db::modest;
using namespace db::rt;
Observable::Observable()
{
// no events to dispatch yet
mDispatch = false;
}
Observable::~Observable()
{
// ensure event dispatching is stopped
stop();
}
void Observable::dispatchEvent(
Event& e, EventId id, OperationList& opList)
{
// go through the list of EventId taps
EventIdMap::iterator ti = mTaps.find(id);
if(ti != mTaps.end())
{
EventIdMap::iterator end = mTaps.upper_bound(id);
for(; ti != end; ti++)
{
// dispatch event if the tap is the EventId itself
if(ti->second == id)
{
// go through the list of observers for the EventId tap
ObserverMap::iterator oi = mObservers.find(id);
if(oi != mObservers.end())
{
ObserverMap::iterator oend = mObservers.upper_bound(id);
for(; oi != oend; oi++)
{
// create and run event dispatcher for each observable
CollectableRunnable ed = new EventDispatcher(oi->second, &e);
Operation op(ed);
mOpRunner->runOperation(op);
opList.add(op);
}
}
}
else
{
// dispatch event to tap
dispatchEvent(e, ti->second, opList);
}
}
}
}
void Observable::dispatchEvent(Event& e)
{
// create an operation list
OperationList opList;
// get the EventId for the event and dispatch it
EventId id = e["id"]->getUInt64();
dispatchEvent(e, id, opList);
if(!opList.isEmpty())
{
// unlock, wait for dispatch operations to complete, relock
unlock();
opList.waitFor();
opList.prune();
lock();
}
}
void Observable::dispatchEvents()
{
lock();
{
while(!mEventQueue.empty())
{
// dispatch the next event
Event e = mEventQueue.front();
mEventQueue.pop_front();
dispatchEvent(e);
}
// turn off dispatching
mDispatch = false;
}
unlock();
}
void Observable::registerObserver(Observer* observer, EventId id)
{
lock();
{
// add tap to self if EventId doesn't exist yet
EventIdMap::iterator i = mTaps.find(id);
if(i == mTaps.end())
{
mTaps.insert(make_pair(id, id));
}
// add observer
mObservers.insert(make_pair(id, observer));
}
unlock();
}
void Observable::unregisterObserver(Observer* observer, EventId id)
{
lock();
{
ObserverMap::iterator i = mObservers.find(id);
if(i != mObservers.end())
{
ObserverMap::iterator end = mObservers.upper_bound(id);
for(; i != end; i++)
{
if(i->second == observer)
{
// remove observer and break
mObservers.erase(i);
break;
}
}
}
}
unlock();
}
void Observable::addTap(EventId id, EventId tap)
{
lock();
{
// add tap to id-self if EventId doesn't exist yet
EventIdMap::iterator i = mTaps.find(id);
if(i == mTaps.end())
{
mTaps.insert(make_pair(id, id));
}
// insert tap for id
mTaps.insert(make_pair(id, tap));
// add tap to tap-self if EventId doesn't exist yet
i = mTaps.find(tap);
if(i == mTaps.end())
{
mTaps.insert(make_pair(tap, tap));
}
}
unlock();
}
void Observable::removeTap(EventId id, EventId tap)
{
lock();
{
// look for tap in the range of taps
EventIdMap::iterator i = mTaps.find(id);
if(i != mTaps.end())
{
EventIdMap::iterator end = mTaps.upper_bound(id);
for(; i != end; i++)
{
if(i->second == tap)
{
// remove tap and break
mTaps.erase(i);
break;
}
}
}
}
unlock();
}
void Observable::schedule(Event e, EventId id, bool async)
{
lock();
{
// set the event's ID
e["id"] = id;
if(async)
{
// lock to set dispatch condition
mDispatchLock.lock();
mDispatch = true;
// add event to event queue
mEventQueue.push_back(e);
// notify on dispatch lock and release
mDispatchLock.notifyAll();
mDispatchLock.unlock();
}
else
{
// dispatch the event immediately
dispatchEvent(e);
}
}
unlock();
}
void Observable::start(OperationRunner* opRunner)
{
lock();
{
if(mOperation.isNull())
{
// store operation runner, create and run operation
mOpRunner = opRunner;
mOperation = *this;
opRunner->runOperation(mOperation);
}
}
unlock();
}
void Observable::stop()
{
lock();
{
if(!mOperation.isNull())
{
// interrupt and clean up operation
mOperation->interrupt();
mOperation->waitFor();
mOperation = NULL;
}
}
unlock();
}
void Observable::run()
{
// keep dispatching until interrupted
while(!mOperation->isInterrupted())
{
// lock dispatch lock and check to see if we can dispatch
mDispatchLock.lock();
if(mDispatch)
{
mDispatchLock.unlock();
dispatchEvents();
}
else
{
// wait until dispatch condition is marked true and we are notified
mDispatchLock.wait();
mDispatchLock.unlock();
}
}
}
<commit_msg>Fixed deadlock bug in Observable and cleaned up a couple of other superfluous calls.<commit_after>/*
* Copyright (c) 2007 Digital Bazaar, Inc. All rights reserved.
*/
#include "db/event/Observable.h"
using namespace std;
using namespace db::event;
using namespace db::modest;
using namespace db::rt;
Observable::Observable()
{
// no events to dispatch yet
mDispatch = false;
}
Observable::~Observable()
{
// ensure event dispatching is stopped
stop();
}
void Observable::dispatchEvent(
Event& e, EventId id, OperationList& opList)
{
// go through the list of EventId taps
EventIdMap::iterator ti = mTaps.find(id);
if(ti != mTaps.end())
{
EventIdMap::iterator end = mTaps.upper_bound(id);
for(; ti != end; ti++)
{
// dispatch event if the tap is the EventId itself
if(ti->second == id)
{
// go through the list of observers for the EventId tap
ObserverMap::iterator oi = mObservers.find(id);
if(oi != mObservers.end())
{
ObserverMap::iterator oend = mObservers.upper_bound(id);
for(; oi != oend; oi++)
{
// create and run event dispatcher for each observable
CollectableRunnable ed = new EventDispatcher(oi->second, &e);
Operation op(ed);
mOpRunner->runOperation(op);
opList.add(op);
}
}
}
else
{
// dispatch event to tap
dispatchEvent(e, ti->second, opList);
}
}
}
}
void Observable::dispatchEvent(Event& e)
{
// create an operation list
OperationList opList;
// get the EventId for the event and dispatch it
EventId id = e["id"]->getUInt64();
dispatchEvent(e, id, opList);
if(!opList.isEmpty())
{
// unlock, wait for dispatch operations to complete, relock
unlock();
if(!opList.waitFor())
{
// dispatch thread interrupted, so interrupt all
// event dispatches and wait for them to complete
opList.interrupt();
opList.waitFor(false);
}
lock();
}
}
void Observable::dispatchEvents()
{
// lock while dispatching
lock();
{
// dispatch
while(!mEventQueue.empty() && !mOperation->isInterrupted())
{
// dispatch the next event
Event e = mEventQueue.front();
mEventQueue.pop_front();
dispatchEvent(e);
}
// turn off dispatching
mDispatch = false;
}
unlock();
}
void Observable::registerObserver(Observer* observer, EventId id)
{
lock();
{
// add tap to self if EventId doesn't exist yet
EventIdMap::iterator i = mTaps.find(id);
if(i == mTaps.end())
{
mTaps.insert(make_pair(id, id));
}
// add observer
mObservers.insert(make_pair(id, observer));
}
unlock();
}
void Observable::unregisterObserver(Observer* observer, EventId id)
{
lock();
{
ObserverMap::iterator i = mObservers.find(id);
if(i != mObservers.end())
{
ObserverMap::iterator end = mObservers.upper_bound(id);
for(; i != end; i++)
{
if(i->second == observer)
{
// remove observer and break
mObservers.erase(i);
break;
}
}
}
}
unlock();
}
void Observable::addTap(EventId id, EventId tap)
{
lock();
{
// add tap to id-self if EventId doesn't exist yet
EventIdMap::iterator i = mTaps.find(id);
if(i == mTaps.end())
{
mTaps.insert(make_pair(id, id));
}
// insert tap for id
mTaps.insert(make_pair(id, tap));
// add tap to tap-self if EventId doesn't exist yet
i = mTaps.find(tap);
if(i == mTaps.end())
{
mTaps.insert(make_pair(tap, tap));
}
}
unlock();
}
void Observable::removeTap(EventId id, EventId tap)
{
lock();
{
// look for tap in the range of taps
EventIdMap::iterator i = mTaps.find(id);
if(i != mTaps.end())
{
EventIdMap::iterator end = mTaps.upper_bound(id);
for(; i != end; i++)
{
if(i->second == tap)
{
// remove tap and break
mTaps.erase(i);
break;
}
}
}
}
unlock();
}
void Observable::schedule(Event e, EventId id, bool async)
{
lock();
{
// set the event's ID
e["id"] = id;
if(async)
{
// lock to set dispatch condition
mDispatchLock.lock();
mDispatch = true;
// add event to event queue
mEventQueue.push_back(e);
// notify on dispatch lock and release
mDispatchLock.notifyAll();
mDispatchLock.unlock();
}
else
{
// dispatch the event immediately
dispatchEvent(e);
}
}
unlock();
}
void Observable::start(OperationRunner* opRunner)
{
lock();
{
if(mOperation.isNull())
{
// store operation runner, activate dispatching,
// create and run operation
mOpRunner = opRunner;
mDispatch = true;
mOperation = *this;
opRunner->runOperation(mOperation);
}
}
unlock();
}
void Observable::stop()
{
lock();
{
if(!mOperation.isNull())
{
// interrupt dispatch operation
mOperation->interrupt();
// Note: We only care about locking in this method to prevent
// start() from running while we are shutting down -- we don't
// care if more events are scheduled because that won't cause
// any conflicts. Since this is the case, and start() will
// check mOperation.isNull() before starting anything, then
// we don't need to worry about it starting here since mOperation
// can't be NULL until we relock and clear it below.
//
// We need to unlock() while we wait for the dispatch operation
// to complete because it needs to lock after dispatching each
// event and won't finish if we are holding the lock here waiting
// for it to finish.
// unlock, wait for dispatch operation to finish, relock
unlock();
mOperation->waitFor();
lock();
// clean up operation
mOperation.setNull();
}
}
unlock();
}
void Observable::run()
{
// keep dispatching until interrupted
while(!mOperation->isInterrupted())
{
// lock dispatch lock and check to see if we can dispatch
mDispatchLock.lock();
if(mDispatch)
{
mDispatchLock.unlock();
dispatchEvents();
}
else
{
// wait until dispatch condition is marked true and we are notified
mDispatchLock.wait();
mDispatchLock.unlock();
}
}
}
<|endoftext|>
|
<commit_before>#ifndef CPPMATH_AABB_INL
#define CPPMATH_AABB_INL
#include "AABB.hpp"
namespace math
{
template <typename T>
AABB<T>::AABB() :
pos(),
size()
{};
template <typename T>
AABB<T>::AABB(T x, T y, T w, T h) :
AABB(Point2<T>(x, y), Vec2<T>(w, h))
{};
template <typename T>
AABB<T>::AABB(const Point2<T>& pos_, const Vec2<T>& size_) :
pos(pos_.asVector()),
size(size_)
{};
template <typename T>
AABB<T>::AABB(const AABB<T>& a, const AABB<T>& b) :
AABB(a)
{
combine(b);
}
template <typename T>
AABB<T> fromPoints(const Point2<T>& a, const Point2<T>& b)
{
return AABB<T>(
std::min(a.x, b.x),
std::min(a.y, b.y),
std::abs(a.x - b.x),
std::abs(a.y - b.y)
);
}
template <typename T>
void AABB<T>::combine(const AABB<T>& other)
{
if (isEmpty())
{
*this = other;
return;
}
else if (other.isEmpty())
return;
Vec2<T> newpos = mins(pos, other.pos);
size = maxs(pos + size, other.pos + other.size) - newpos;
pos = newpos;
}
template <typename T>
void AABB<T>::extend(const AABB<T>& other, bool center)
{
extend(other.size, center);
}
template <typename T>
void AABB<T>::extend(const Vec2<T>& othersize, bool center)
{
if (center)
pos -= othersize / 2.f;
size += othersize;
}
template <typename T>
bool AABB<T>::isEmpty() const
{
return size.x == 0 && size.y == 0;
}
template <typename T>
void AABB<T>::center(T x, T y)
{
pos.fill(x, y);
pos -= size / 2;
}
template <typename T>
void AABB<T>::center(const Point2<T>& p)
{
center(p.x, p.y);
}
template <typename T>
Point2<T> AABB<T>::getCenter() const
{
return pos.asPoint() + size / 2;
}
template <typename T>
bool AABB<T>::operator!=(const AABB<T>& r) const
{
return pos != r.pos || size != r.size;
}
template <typename T>
bool AABB<T>::operator==(const AABB<T>& r) const
{
return pos == r.pos && size == r.size;
}
template <typename T>
template <typename T2>
AABB<T>::operator AABB<T2>() const
{
return AABB<T2>(pos, size);
}
}
#endif
<commit_msg>Fix wrong function signature<commit_after>#ifndef CPPMATH_AABB_INL
#define CPPMATH_AABB_INL
#include "AABB.hpp"
namespace math
{
template <typename T>
AABB<T>::AABB() :
pos(),
size()
{};
template <typename T>
AABB<T>::AABB(T x, T y, T w, T h) :
AABB(Point2<T>(x, y), Vec2<T>(w, h))
{};
template <typename T>
AABB<T>::AABB(const Point2<T>& pos_, const Vec2<T>& size_) :
pos(pos_.asVector()),
size(size_)
{};
template <typename T>
AABB<T>::AABB(const AABB<T>& a, const AABB<T>& b) :
AABB(a)
{
combine(b);
}
template <typename T>
AABB<T> AABB<T>::fromPoints(const Point2<T>& a, const Point2<T>& b)
{
return AABB<T>(
std::min(a.x, b.x),
std::min(a.y, b.y),
std::abs(a.x - b.x),
std::abs(a.y - b.y)
);
}
template <typename T>
void AABB<T>::combine(const AABB<T>& other)
{
if (isEmpty())
{
*this = other;
return;
}
else if (other.isEmpty())
return;
Vec2<T> newpos = mins(pos, other.pos);
size = maxs(pos + size, other.pos + other.size) - newpos;
pos = newpos;
}
template <typename T>
void AABB<T>::extend(const AABB<T>& other, bool center)
{
extend(other.size, center);
}
template <typename T>
void AABB<T>::extend(const Vec2<T>& othersize, bool center)
{
if (center)
pos -= othersize / 2.f;
size += othersize;
}
template <typename T>
bool AABB<T>::isEmpty() const
{
return size.x == 0 && size.y == 0;
}
template <typename T>
void AABB<T>::center(T x, T y)
{
pos.fill(x, y);
pos -= size / 2;
}
template <typename T>
void AABB<T>::center(const Point2<T>& p)
{
center(p.x, p.y);
}
template <typename T>
Point2<T> AABB<T>::getCenter() const
{
return pos.asPoint() + size / 2;
}
template <typename T>
bool AABB<T>::operator!=(const AABB<T>& r) const
{
return pos != r.pos || size != r.size;
}
template <typename T>
bool AABB<T>::operator==(const AABB<T>& r) const
{
return pos == r.pos && size == r.size;
}
template <typename T>
template <typename T2>
AABB<T>::operator AABB<T2>() const
{
return AABB<T2>(pos, size);
}
}
#endif
<|endoftext|>
|
<commit_before>/**********************************************************************
*
* GEOS - Geometry Engine Open Source
* http://geos.osgeo.org
*
* Copyright (C) 2012 Sandro Santilli <strk@kbt.io>
*
* This is free software; you can redistribute and/or modify it under
* the terms of the GNU Lesser General Public Licence as published
* by the Free Software Foundation.
* See the COPYING file for more information.
*
**********************************************************************
*
* NOTE: this is not in JTS. JTS has a snapround/GeometryNoder though
*
**********************************************************************/
#include <geos/noding/GeometryNoder.h>
#include <geos/noding/SegmentString.h>
#include <geos/noding/NodedSegmentString.h>
#include <geos/noding/OrientedCoordinateArray.h>
#include <geos/noding/Noder.h>
#include <geos/geom/Geometry.h>
#include <geos/geom/PrecisionModel.h>
#include <geos/geom/CoordinateSequence.h>
#include <geos/geom/GeometryFactory.h>
#include <geos/geom/LineString.h>
#include <geos/noding/IteratedNoder.h>
#include <geos/algorithm/LineIntersector.h>
#include <geos/noding/IntersectionAdder.h>
#include <geos/noding/MCIndexNoder.h>
#include <geos/noding/snapround/SimpleSnapRounder.h>
#include <geos/noding/snapround/MCIndexSnapRounder.h>
#include <memory> // for unique_ptr
#include <iostream>
namespace geos {
namespace noding { // geos.noding
namespace {
/**
* Add every linear element in a geometry into SegmentString vector
*/
class SegmentStringExtractor: public geom::GeometryComponentFilter {
public:
SegmentStringExtractor(SegmentString::NonConstVect& to)
: _to(to)
{}
void filter_ro(const geom::Geometry * g) override {
const geom::LineString *ls = dynamic_cast<const geom::LineString *>(g);
if ( ls ) {
geom::CoordinateSequence* coord = ls->getCoordinates();
// coord ownership transferred to SegmentString
SegmentString *ss = new NodedSegmentString(coord, nullptr);
_to.push_back(ss);
}
}
private:
SegmentString::NonConstVect& _to;
SegmentStringExtractor(SegmentStringExtractor const&); /*= delete*/
SegmentStringExtractor& operator=(SegmentStringExtractor const&); /*= delete*/
};
}
/* public static */
std::unique_ptr<geom::Geometry>
GeometryNoder::node(const geom::Geometry& geom)
{
GeometryNoder noder(geom);
return noder.getNoded();
}
/* public */
GeometryNoder::GeometryNoder(const geom::Geometry& g)
:
argGeom(g)
{
}
/* private */
std::unique_ptr<geom::Geometry>
GeometryNoder::toGeometry(SegmentString::NonConstVect& nodedEdges)
{
const geom::GeometryFactory *geomFact = argGeom.getFactory();
std::set< OrientedCoordinateArray > ocas;
// Create a geometry out of the noded substrings.
std::vector< geom::Geometry* >* lines = new std::vector< geom::Geometry * >();
lines->reserve(nodedEdges.size());
for (auto &ss : nodedEdges)
{
const geom::CoordinateSequence* coords = ss->getCoordinates();
// Check if an equivalent edge is known
OrientedCoordinateArray oca1( *coords );
if ( ocas.insert(oca1).second ) {
geom::Geometry* tmp = geomFact->createLineString( coords->clone() );
lines->push_back( tmp );
}
}
std::unique_ptr<geom::Geometry> noded ( geomFact->createMultiLineString( lines ) );
return noded;
}
/* public */
std::unique_ptr<geom::Geometry>
GeometryNoder::getNoded()
{
SegmentString::NonConstVect p_lineList;
extractSegmentStrings(argGeom, p_lineList);
Noder& p_noder = getNoder();
SegmentString::NonConstVect* nodedEdges = nullptr;
try {
p_noder.computeNodes( &p_lineList );
nodedEdges = p_noder.getNodedSubstrings();
}
catch (const std::exception& ex)
{
for (size_t i=0, n=p_lineList.size(); i<n; ++i)
delete p_lineList[i];
throw;
}
std::unique_ptr<geom::Geometry> noded = toGeometry(*nodedEdges);
for (auto &elem : (*nodedEdges))
delete elem;
delete nodedEdges;
for (auto &elem : lineList)
delete elem;
return noded;
}
/* private static */
void
GeometryNoder::extractSegmentStrings(const geom::Geometry& g,
SegmentString::NonConstVect& to)
{
SegmentStringExtractor ex(to);
g.apply_ro(&ex);
}
/* private */
Noder&
GeometryNoder::getNoder()
{
if ( ! noder.get() )
{
const geom::PrecisionModel *pm = argGeom.getFactory()->getPrecisionModel();
#if 0
using algorithm::LineIntersector;
LineIntersector li;
IntersectionAdder intersectionAdder(li);
noder.reset( new MCIndexNoder(&intersectionAdder) );
#else
IteratedNoder* in = new IteratedNoder(pm);
//in->setMaximumIterations(0);
noder.reset( in );
//using snapround::SimpleSnapRounder;
//noder.reset( new SimpleSnapRounder(*pm) );
//using snapround::MCIndexSnapRounder;
//noder.reset( new MCIndexSnapRounder(*pm) );
#endif
}
return *noder;
}
} // namespace geos.noding
} // namespace geos
<commit_msg>Fix memory leak in getNoded<commit_after>/**********************************************************************
*
* GEOS - Geometry Engine Open Source
* http://geos.osgeo.org
*
* Copyright (C) 2012 Sandro Santilli <strk@kbt.io>
*
* This is free software; you can redistribute and/or modify it under
* the terms of the GNU Lesser General Public Licence as published
* by the Free Software Foundation.
* See the COPYING file for more information.
*
**********************************************************************
*
* NOTE: this is not in JTS. JTS has a snapround/GeometryNoder though
*
**********************************************************************/
#include <geos/noding/GeometryNoder.h>
#include <geos/noding/SegmentString.h>
#include <geos/noding/NodedSegmentString.h>
#include <geos/noding/OrientedCoordinateArray.h>
#include <geos/noding/Noder.h>
#include <geos/geom/Geometry.h>
#include <geos/geom/PrecisionModel.h>
#include <geos/geom/CoordinateSequence.h>
#include <geos/geom/GeometryFactory.h>
#include <geos/geom/LineString.h>
#include <geos/noding/IteratedNoder.h>
#include <geos/algorithm/LineIntersector.h>
#include <geos/noding/IntersectionAdder.h>
#include <geos/noding/MCIndexNoder.h>
#include <geos/noding/snapround/SimpleSnapRounder.h>
#include <geos/noding/snapround/MCIndexSnapRounder.h>
#include <memory> // for unique_ptr
#include <iostream>
namespace geos {
namespace noding { // geos.noding
namespace {
/**
* Add every linear element in a geometry into SegmentString vector
*/
class SegmentStringExtractor: public geom::GeometryComponentFilter {
public:
SegmentStringExtractor(SegmentString::NonConstVect& to)
: _to(to)
{}
void filter_ro(const geom::Geometry * g) override {
const geom::LineString *ls = dynamic_cast<const geom::LineString *>(g);
if ( ls ) {
geom::CoordinateSequence* coord = ls->getCoordinates();
// coord ownership transferred to SegmentString
SegmentString *ss = new NodedSegmentString(coord, nullptr);
_to.push_back(ss);
}
}
private:
SegmentString::NonConstVect& _to;
SegmentStringExtractor(SegmentStringExtractor const&); /*= delete*/
SegmentStringExtractor& operator=(SegmentStringExtractor const&); /*= delete*/
};
}
/* public static */
std::unique_ptr<geom::Geometry>
GeometryNoder::node(const geom::Geometry& geom)
{
GeometryNoder noder(geom);
return noder.getNoded();
}
/* public */
GeometryNoder::GeometryNoder(const geom::Geometry& g)
:
argGeom(g)
{
}
/* private */
std::unique_ptr<geom::Geometry>
GeometryNoder::toGeometry(SegmentString::NonConstVect& nodedEdges)
{
const geom::GeometryFactory *geomFact = argGeom.getFactory();
std::set< OrientedCoordinateArray > ocas;
// Create a geometry out of the noded substrings.
std::vector< geom::Geometry* >* lines = new std::vector< geom::Geometry * >();
lines->reserve(nodedEdges.size());
for (auto &ss : nodedEdges)
{
const geom::CoordinateSequence* coords = ss->getCoordinates();
// Check if an equivalent edge is known
OrientedCoordinateArray oca1( *coords );
if ( ocas.insert(oca1).second ) {
geom::Geometry* tmp = geomFact->createLineString( coords->clone() );
lines->push_back( tmp );
}
}
std::unique_ptr<geom::Geometry> noded ( geomFact->createMultiLineString( lines ) );
return noded;
}
/* public */
std::unique_ptr<geom::Geometry>
GeometryNoder::getNoded()
{
SegmentString::NonConstVect p_lineList;
extractSegmentStrings(argGeom, p_lineList);
Noder& p_noder = getNoder();
SegmentString::NonConstVect* nodedEdges = nullptr;
try {
p_noder.computeNodes( &p_lineList );
nodedEdges = p_noder.getNodedSubstrings();
}
catch (const std::exception& ex)
{
for (size_t i=0, n=p_lineList.size(); i<n; ++i)
delete p_lineList[i];
throw;
}
std::unique_ptr<geom::Geometry> noded = toGeometry(*nodedEdges);
for (auto &elem : (*nodedEdges))
delete elem;
delete nodedEdges;
for (auto &elem : p_lineList)
delete elem;
return noded;
}
/* private static */
void
GeometryNoder::extractSegmentStrings(const geom::Geometry& g,
SegmentString::NonConstVect& to)
{
SegmentStringExtractor ex(to);
g.apply_ro(&ex);
}
/* private */
Noder&
GeometryNoder::getNoder()
{
if ( ! noder.get() )
{
const geom::PrecisionModel *pm = argGeom.getFactory()->getPrecisionModel();
#if 0
using algorithm::LineIntersector;
LineIntersector li;
IntersectionAdder intersectionAdder(li);
noder.reset( new MCIndexNoder(&intersectionAdder) );
#else
IteratedNoder* in = new IteratedNoder(pm);
//in->setMaximumIterations(0);
noder.reset( in );
//using snapround::SimpleSnapRounder;
//noder.reset( new SimpleSnapRounder(*pm) );
//using snapround::MCIndexSnapRounder;
//noder.reset( new MCIndexSnapRounder(*pm) );
#endif
}
return *noder;
}
} // namespace geos.noding
} // namespace geos
<|endoftext|>
|
<commit_before><commit_msg>better extract page type<commit_after><|endoftext|>
|
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/download/download_shelf.h"
#include "app/l10n_util.h"
#include "base/file_util.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/dom_ui/downloads_ui.h"
#include "chrome/browser/download/download_item_model.h"
#include "chrome/browser/download/download_manager.h"
#include "chrome/browser/download/download_util.h"
#include "chrome/browser/metrics/user_metrics.h"
#include "chrome/common/url_constants.h"
#include "grit/generated_resources.h"
// DownloadShelfContextMenu ----------------------------------------------------
DownloadShelfContextMenu::DownloadShelfContextMenu(
BaseDownloadItemModel* download_model)
: download_(download_model->download()),
model_(download_model) {
}
DownloadShelfContextMenu::~DownloadShelfContextMenu() {
}
bool DownloadShelfContextMenu::ItemIsChecked(int id) const {
switch (id) {
case OPEN_WHEN_COMPLETE:
return download_->open_when_complete();
case ALWAYS_OPEN_TYPE: {
const FilePath::StringType extension =
file_util::GetFileExtensionFromPath(download_->full_path());
return download_->manager()->ShouldOpenFileExtension(extension);
}
}
return false;
}
bool DownloadShelfContextMenu::ItemIsDefault(int id) const {
return id == OPEN_WHEN_COMPLETE;
}
std::wstring DownloadShelfContextMenu::GetItemLabel(int id) const {
switch (id) {
case SHOW_IN_FOLDER:
return l10n_util::GetString(IDS_DOWNLOAD_LINK_SHOW);
case OPEN_WHEN_COMPLETE:
if (download_->state() == DownloadItem::IN_PROGRESS)
return l10n_util::GetString(IDS_DOWNLOAD_MENU_OPEN_WHEN_COMPLETE);
return l10n_util::GetString(IDS_DOWNLOAD_MENU_OPEN);
case ALWAYS_OPEN_TYPE:
return l10n_util::GetString(IDS_DOWNLOAD_MENU_ALWAYS_OPEN_TYPE);
case CANCEL:
return l10n_util::GetString(IDS_DOWNLOAD_MENU_CANCEL);
case REMOVE_ITEM:
return l10n_util::GetString(IDS_DOWNLOAD_MENU_REMOVE_ITEM);
default:
NOTREACHED();
}
return std::wstring();
}
bool DownloadShelfContextMenu::IsItemCommandEnabled(int id) const {
switch (id) {
case SHOW_IN_FOLDER:
case OPEN_WHEN_COMPLETE:
return download_->state() != DownloadItem::CANCELLED;
case ALWAYS_OPEN_TYPE:
return download_util::CanOpenDownload(download_);
case CANCEL:
return download_->state() == DownloadItem::IN_PROGRESS;
case REMOVE_ITEM:
return download_->state() == DownloadItem::COMPLETE;
default:
return id > 0 && id < MENU_LAST;
}
}
void DownloadShelfContextMenu::ExecuteItemCommand(int id) {
switch (id) {
case SHOW_IN_FOLDER:
download_->manager()->ShowDownloadInShell(download_);
break;
case OPEN_WHEN_COMPLETE:
download_util::OpenDownload(download_);
break;
case ALWAYS_OPEN_TYPE: {
const FilePath::StringType extension =
file_util::GetFileExtensionFromPath(download_->full_path());
download_->manager()->OpenFilesOfExtension(
extension, !ItemIsChecked(ALWAYS_OPEN_TYPE));
break;
}
case CANCEL:
model_->CancelTask();
break;
case REMOVE_ITEM:
download_->Remove(false);
break;
default:
NOTREACHED();
}
}
<commit_msg>Allow cancellable download items to be removable from download shelf.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/download/download_shelf.h"
#include "app/l10n_util.h"
#include "base/file_util.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/dom_ui/downloads_ui.h"
#include "chrome/browser/download/download_item_model.h"
#include "chrome/browser/download/download_manager.h"
#include "chrome/browser/download/download_util.h"
#include "chrome/browser/metrics/user_metrics.h"
#include "chrome/common/url_constants.h"
#include "grit/generated_resources.h"
// DownloadShelfContextMenu ----------------------------------------------------
DownloadShelfContextMenu::DownloadShelfContextMenu(
BaseDownloadItemModel* download_model)
: download_(download_model->download()),
model_(download_model) {
}
DownloadShelfContextMenu::~DownloadShelfContextMenu() {
}
bool DownloadShelfContextMenu::ItemIsChecked(int id) const {
switch (id) {
case OPEN_WHEN_COMPLETE:
return download_->open_when_complete();
case ALWAYS_OPEN_TYPE: {
const FilePath::StringType extension =
file_util::GetFileExtensionFromPath(download_->full_path());
return download_->manager()->ShouldOpenFileExtension(extension);
}
}
return false;
}
bool DownloadShelfContextMenu::ItemIsDefault(int id) const {
return id == OPEN_WHEN_COMPLETE;
}
std::wstring DownloadShelfContextMenu::GetItemLabel(int id) const {
switch (id) {
case SHOW_IN_FOLDER:
return l10n_util::GetString(IDS_DOWNLOAD_LINK_SHOW);
case OPEN_WHEN_COMPLETE:
if (download_->state() == DownloadItem::IN_PROGRESS)
return l10n_util::GetString(IDS_DOWNLOAD_MENU_OPEN_WHEN_COMPLETE);
return l10n_util::GetString(IDS_DOWNLOAD_MENU_OPEN);
case ALWAYS_OPEN_TYPE:
return l10n_util::GetString(IDS_DOWNLOAD_MENU_ALWAYS_OPEN_TYPE);
case CANCEL:
return l10n_util::GetString(IDS_DOWNLOAD_MENU_CANCEL);
case REMOVE_ITEM:
return l10n_util::GetString(IDS_DOWNLOAD_MENU_REMOVE_ITEM);
default:
NOTREACHED();
}
return std::wstring();
}
bool DownloadShelfContextMenu::IsItemCommandEnabled(int id) const {
switch (id) {
case SHOW_IN_FOLDER:
case OPEN_WHEN_COMPLETE:
return download_->state() != DownloadItem::CANCELLED;
case ALWAYS_OPEN_TYPE:
return download_util::CanOpenDownload(download_);
case CANCEL:
return download_->state() == DownloadItem::IN_PROGRESS;
case REMOVE_ITEM:
return download_->state() == DownloadItem::COMPLETE ||
download_->state() == DownloadItem::CANCELLED;
default:
return id > 0 && id < MENU_LAST;
}
}
void DownloadShelfContextMenu::ExecuteItemCommand(int id) {
switch (id) {
case SHOW_IN_FOLDER:
download_->manager()->ShowDownloadInShell(download_);
break;
case OPEN_WHEN_COMPLETE:
download_util::OpenDownload(download_);
break;
case ALWAYS_OPEN_TYPE: {
const FilePath::StringType extension =
file_util::GetFileExtensionFromPath(download_->full_path());
download_->manager()->OpenFilesOfExtension(
extension, !ItemIsChecked(ALWAYS_OPEN_TYPE));
break;
}
case CANCEL:
model_->CancelTask();
break;
case REMOVE_ITEM:
download_->Remove(false);
break;
default:
NOTREACHED();
}
}
<|endoftext|>
|
<commit_before>/**
* File : D.cpp
* Author : Kazune Takahashi
* Created : 2/9/2019, 9:16:48 PM
* Powered by Visual Studio Code
*/
#include <iostream>
#include <iomanip> // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <functional>
#include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(19920725));
#include <chrono> // std::chrono::system_clock::time_point start_time, end_time;
// start = std::chrono::system_clock::now();
// double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
#define DEBUG 0 // change 0 -> 1 if we need debug.
typedef long long ll;
// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};
// const int C = 1e6+10;
// const ll M = 1000000007;
int L;
ll A[200010];
ll B[200010]; // even
ll C[200010]; // odd
ll sum[3][200010];
ll calc(int a, int b, int c, int d)
{
ll ans = 0;
ans += sum[0][a] - sum[0][0];
ans += sum[1][b] - sum[1][a];
ans += sum[2][c] - sum[2][b];
ans += sum[1][d] - sum[1][c];
ans += sum[0][L] - sum[0][d];
return ans;
}
int main()
{
cin >> L;
ll mini = 0;
for (auto i = 0; i < L; i++)
{
cin >> A[i];
mini += A[i];
}
bool zero = true;
for (auto i = 0; i < L; i++)
{
if (A[i] > 0)
{
zero = false;
break;
}
}
if (zero)
{
cout << 0 << endl;
return 0;
}
for (auto i = 0; i < L; i++)
{
if (A[i] == 0)
{
B[i] = 2;
}
else if (A[i] % 2 == 0)
{
B[i] = 0;
}
else
{
B[i] = 1;
}
}
for (auto i = 0; i < L; i++)
{
if (A[i] % 2 == 1)
{
C[i] = 0;
}
else
{
C[i] = 1;
}
}
sum[0][0] = sum[0][1] = sum[0][2] = 0;
for (auto i = 0; i < L; i++)
{
sum[0][i + 1] = sum[0][i] + A[i];
sum[1][i + 1] = sum[1][i] + B[i];
sum[2][i + 1] = sum[2][i] + C[i];
}
for (auto a = 0; a <= L; a++)
{
for (auto b = a; b <= L; b++)
{
for (auto c = b; c <= L; c++)
{
for (auto d = c; d <= L; d++)
{
ll t = calc(a, b, c, d);
mini = min(mini, t);
cerr << "calc(" << a << ", " << b << ", " << c << ", " << d << ") = " << t << endl;
}
}
}
}
cerr << mini << endl;
}<commit_msg>submit D.cpp to 'D - Ears' (yahoo-procon2019-qual) [C++14 (GCC 5.4.1)]<commit_after>/**
* File : D.cpp
* Author : Kazune Takahashi
* Created : 2/9/2019, 9:16:48 PM
* Powered by Visual Studio Code
*/
#include <iostream>
#include <iomanip> // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <functional>
#include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(19920725));
#include <chrono> // std::chrono::system_clock::time_point start_time, end_time;
// start = std::chrono::system_clock::now();
// double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
#define DEBUG 0 // change 0 -> 1 if we need debug.
typedef long long ll;
// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};
// const int C = 1e6+10;
// const ll M = 1000000007;
int L;
ll A[200010];
ll B[200010]; // even
ll C[200010]; // odd
ll sum[3][200010];
// TLE
ll calc(int a, int b, int c, int d)
{
ll ans = 0;
ans += sum[0][a] - sum[0][0];
ans += sum[1][b] - sum[1][a];
ans += sum[2][c] - sum[2][b];
ans += sum[1][d] - sum[1][c];
ans += sum[0][L] - sum[0][d];
return ans;
}
int main()
{
cin >> L;
ll mini = 0;
for (auto i = 0; i < L; i++)
{
cin >> A[i];
mini += A[i];
}
bool zero = true;
for (auto i = 0; i < L; i++)
{
if (A[i] > 0)
{
zero = false;
break;
}
}
if (zero)
{
cout << 0 << endl;
return 0;
}
for (auto i = 0; i < L; i++)
{
if (A[i] == 0)
{
B[i] = 2;
}
else if (A[i] % 2 == 0)
{
B[i] = 0;
}
else
{
B[i] = 1;
}
}
for (auto i = 0; i < L; i++)
{
if (A[i] % 2 == 1)
{
C[i] = 0;
}
else
{
C[i] = 1;
}
}
sum[0][0] = sum[0][1] = sum[0][2] = 0;
for (auto i = 0; i < L; i++)
{
sum[0][i + 1] = sum[0][i] + A[i];
sum[1][i + 1] = sum[1][i] + B[i];
sum[2][i + 1] = sum[2][i] + C[i];
}
for (auto a = 0; a <= L; a++)
{
for (auto b = a; b <= L; b++)
{
for (auto c = b; c <= L; c++)
{
for (auto d = c; d <= L; d++)
{
ll t = calc(a, b, c, d);
mini = min(mini, t);
// cerr << "calc(" << a << ", " << b << ", " << c << ", " << d << ") = " << t << endl;
}
}
}
}
cout << mini << endl;
}<|endoftext|>
|
<commit_before>#ifndef XML11_HPP
#define XML11_HPP
#include <string>
#include <memory>
#include <vector>
#include <iostream>
#include <algorithm>
namespace xml11 {
namespace detail {
using mp_true = std::integral_constant<bool, true>;
using mp_false = std::integral_constant<bool, false>;
template<class... T> struct mp_list {};
template<class T>
struct mp_empty_impl;
template<template<class...> class L>
struct mp_empty_impl<L<>> : mp_true {};
template<template<class...> class L, class T1, class... T>
struct mp_empty_impl<L<T1, T...>> : mp_false {};
template<class ... T> using mp_empty = typename mp_empty_impl<mp_list<T...>>::type;
template<class T, class = typename std::enable_if<decltype(*std::declval<T&>(), true)(true), void>::type>
struct mp_like_pointer_impl {
static const bool value = true;
};
template<class T, class = typename std::enable_if<decltype(std::to_string(std::declval<T&>()), true)(true), void>::type>
struct mp_can_be_string_impl {
static const bool value = true;
};
template<class T, class = typename std::enable_if<decltype(std::to_string(*std::declval<T&>()), true)(true), void>::type>
struct mp_can_be_string_from_opt_impl {
static const bool value = true;
};
} // namespace detail
template<class ... T> using mp_empty = std::is_same<detail::mp_empty<T...>, detail::mp_true>;
template<class T, class U> using mp_same = std::is_same<typename std::decay<T>::type, U>;
template<class T, class U> using mp_same_from_opt = std::is_same<typename std::decay<decltype(*std::declval<T&>())>::type, U>;
template<class T> using mp_integral = std::is_integral<typename std::decay<T>::type>;
template<class T> using mp_like_pointer = detail::mp_like_pointer_impl<T>;
template<class T> using mp_can_be_string = detail::mp_can_be_string_impl<T>;
template<class T> using mp_can_be_string_from_opt = detail::mp_can_be_string_from_opt_impl<T>;
using NodeList = std::vector<class Node>;
using ValueFilter = std::function<std::string (const std::string& value)>;
class Node {
public:
enum class Type : char {
ELEMENT = 0,
ATTRIBUTE = 1,
OPTIONAL = 2,
};
class Xml11Exception final : public std::runtime_error {
public:
using std::runtime_error::runtime_error;
};
public:
static Node fromString(const std::string& text, const bool isCaseInsensitive=true, ValueFilter valueFilter_ = nullptr);
std::string toString(const bool indent = true, ValueFilter valueFilter_ = nullptr) const;
public:
static void AddNode(Node&) noexcept
{
}
static void AddNode_(Node&) noexcept
{
}
template<
class Head,
class = typename std::enable_if<
mp_like_pointer<Head>::value,
void
>::type,
class = void
>
static void AddNode_(Node& node, Head&& head)
{
if (head) {
AddNode_(node, *std::forward<Head>(head));
}
}
template<
class T,
class = typename std::enable_if<
mp_same<T, std::string>::value,
void
>::type,
class = void,
class = void
>
static void AddNode_(Node& node, T&& value)
{
node.addNode(std::forward<T>(value));
}
template<
class T,
class = typename std::enable_if<
!mp_same<T, Node>::value &&
!mp_same<T, NodeList>::value &&
!mp_same<T, std::string>::value &&
!mp_same<T, char*>::value &&
mp_can_be_string<T>::value,
void
>::type
>
static void AddNode_(Node& node, T&& value)
{
node.text(std::to_string(std::forward<T>(value)));
}
template<std::size_t N>
static void AddNode_(Node& node, const char(&value)[N])
{
node.text(value);
}
static void AddNode_(Node& node, const Node::Type type)
{
node.type(type);
}
template<
class T,
class ... Args,
class = typename std::enable_if<
mp_same<T, Node>::value,
void
>::type
>
static void AddNode_(Node& node, T&& head)
{
node.addNode(std::forward<T>(head));
}
template<
class T,
class ... Args,
class = typename std::enable_if<
mp_same<T, NodeList>::value,
void
>::type,
class = void
>
static void AddNode_(Node& node, T&& head)
{
node.addNodes(std::forward<T>(head));
}
template<
class T,
class ... Args,
class = typename std::enable_if<
mp_like_pointer<T>::value,
void
>::type
>
static void AddNode_(Node& node, std::initializer_list<T>&& list)
{
for (auto&& item : list) {
AddNode_(node, std::move<T>(item));
}
}
template<
class T,
class = typename std::enable_if<
mp_same<T, Node>::value,
void
>::type
>
static void AddNode_(Node& node, std::initializer_list<T>&& list)
{
AddNode_(node, NodeList(std::move<T>(list)));
}
template<
class T,
class = typename std::enable_if<
mp_same<T, NodeList>::value,
void
>::type,
class = void
>
static void AddNode_(Node& node, std::initializer_list<T>&& list)
{
for (const auto& item : list) {
AddNode_(node, std::move<T>(item));
}
}
template<class Head, class... Tail>
static void AddNode_(Node& node, Head&& head, Tail&& ...tail)
{
AddNode_(node, std::forward<Head>(head));
AddNode_(node, std::forward<Tail>(tail)...);
}
template<class Head, class... Tail>
static void AddNode(Node& node, Head&& head, Tail&& ...tail)
{
AddNode_(node, std::forward<Head>(head));
AddNode_(node, std::forward<Tail>(tail)...);
}
public:
~Node() noexcept;
Node(const std::shared_ptr<class NodeImpl>& node) noexcept;
Node(const Node& node) noexcept;
Node(Node&& node) noexcept;
Node(std::string name);
Node(std::string name, const Node& node);
Node(std::string name, Node&& node);
Node(std::string name, std::string value);
Node(std::string name, std::string value, const Type type);
Node(std::string name, const NodeList& nodes);
Node(std::string name, NodeList&& nodes);
Node(std::string name, std::initializer_list<Node>&& list)
: Node(std::move(name), NodeList(std::move(list)))
{
}
template<
class ... Args,
class = typename std::enable_if<
!mp_empty<Args...>::value,
void
>::type
>
Node(std::string name, std::initializer_list<Node>&& list, Args&& ... args)
: Node(std::move(name), NodeList(std::move(list)))
{
AddNode(*const_cast<Node*>(this), std::forward<Args>(args)...);
}
template<
class T,
class ... Args,
class = typename std::enable_if<
mp_like_pointer<T>::value &&
mp_empty<Args...>::value,
void
>::type
>
Node(std::string name, std::initializer_list<T>&& list)
: Node(std::move(name))
{
for (const auto& item : list) {
AddNode(*const_cast<Node*>(this), std::forward<decltype(item)>(item));
}
}
template<
class T,
class ... Args,
class = typename std::enable_if<
mp_like_pointer<T>::value &&
!mp_empty<Args...>::value,
void
>::type
>
Node(std::string name, std::initializer_list<T>&& list, Args&& ... args)
: Node(std::move(name), std::move(list))
{
AddNode(*const_cast<Node*>(this), std::forward<Args>(args)...);
}
template<
class ... Args,
class = typename std::enable_if<
!mp_empty<Args...>::value,
void
>::type
>
Node(std::string name, std::string value, Args&& ... args)
: Node(std::move(name), std::move(value))
{
AddNode(*const_cast<Node*>(this), std::forward<Args>(args)...);
}
template<
class ... Args,
class = typename std::enable_if<
!mp_empty<Args...>::value,
void
>::type
>
Node(std::string name, std::string value, const Type type, Args&& ... args)
: Node(std::move(name), std::move(value), type)
{
AddNode(*const_cast<Node*>(this), std::forward<Args>(args)...);
}
template<
class T,
class ... Args,
class = typename std::enable_if<
(mp_same<T, Node>::value || mp_same<T, NodeList>::value) &&
!mp_empty<Args...>::value,
void
>::type,
class = void
>
Node(std::string name, T&& value, Args&& ... args)
: Node(std::move(name), std::forward<T>(value))
{
AddNode(*const_cast<Node*>(this), std::forward<Args>(args)...);
}
template<
class T,
class ... Args,
class = typename std::enable_if<
mp_integral<T>::value &&
mp_empty<Args...>::value,
void
>::type
>
Node(std::string name, T&& value)
: Node(std::move(name), std::to_string(std::forward<T>(value)))
{
}
template<
class T,
class ... Args,
class = typename std::enable_if<
mp_integral<T>::value &&
!mp_empty<Args...>::value,
void
>::type
>
Node(std::string name, T&& value, Args&& ... args)
: Node(std::move(name), std::to_string(std::forward<T>(value)))
{
AddNode(*const_cast<Node*>(this), std::forward<Args>(args)...);
}
template<
class T,
class=typename std::enable_if<
!mp_same<T, std::string>::value &&
!mp_same<T, char*>::value &&
!mp_same_from_opt<T, std::string>::value &&
mp_can_be_string_from_opt<T>::value,
T
>::type,
class=void
>
Node(std::string name, const T& param)
: Node(std::move(name))
{
if (param) {
this->value(std::to_string(*param));
}
else {
this->pimpl = nullptr;
}
}
template<
class T,
class=typename std::enable_if<
!mp_same<T, std::string>::value &&
!mp_same<T, char*>::value &&
mp_same_from_opt<T, std::string>::value,
T
>::type,
class=void,
class=void
>
Node(std::string name, const T& param)
: Node(std::move(name))
{
if (param) {
this->value(*param);
}
else {
this->pimpl = nullptr;
}
}
Node& operator = (const Node& node) noexcept;
Node& operator = (Node&& node) noexcept;
bool operator == (const Node& node) const noexcept;
bool operator != (const Node& node) const noexcept;
operator bool() const noexcept;
NodeList operator [] (const std::string& name);
NodeList operator [] (const char* name);
NodeList operator [] (const Type& type);
const NodeList operator [] (const std::string& name) const;
const NodeList operator [] (const char* name) const;
const NodeList operator [] (const Type& type) const;
NodeList findNodes(const std::string& name);
NodeList findNodes(const Type& type);
const NodeList findNodes(const std::string& name) const;
const NodeList findNodes(const Type& type) const;
NodeList findNodesXPath(const std::string& name);
const NodeList findNodesXPath(const std::string& name) const;
Node operator () (const std::string& name);
Node operator () (const Type& type);
const Node operator () (const std::string& name) const;
const Node operator () (const Type& type) const;
Node findNode(const std::string& name);
Node findNode(const Type& type);
const Node findNode(const std::string& name) const;
const Node findNode(const Type& type) const;
Node findNodeXPath(const std::string& name);
const Node findNodeXPath(const std::string& name) const;
Node& operator -= (const Node& root);
Node& operator -= (Node&& root);
Node& operator -= (const NodeList& nodes);
Node& operator -= (NodeList&& nodes);
Node& operator += (const Node& root);
Node& operator += (Node&& root);
Node& operator += (const NodeList& nodes);
Node& operator += (NodeList&& nodes);
Node& addNode(const Node& node);
Node& addNode(Node&& node);
Node& addNode(std::string name);
Node& addNode(std::string name, std::string value);
Node& addNode(std::string name, std::string value, const Node::Type type);
template<
class T,
class=typename std::enable_if<
mp_can_be_string<T>::value,
T
>::type
>
Node& addNode(std::string name, T&& value)
{
return addNode(std::move(name), std::to_string(std::forward<T>(value)));
}
Node& addAttribute(std::string name);
Node& addAttribute(std::string name, std::string value);
Node& addNodes(const NodeList& node);
Node& addNodes(NodeList&& node);
Node& eraseNode(const Node& node);
Node& eraseNode(Node&& node);
Node& eraseNodes(const NodeList& node);
Node& eraseNodes(NodeList&& nodes);
NodeList nodes();
const NodeList nodes() const;
Node::Type type() const;
void type(const Node::Type type);
std::string& name() const;
void name(std::string name);
std::string& text() const;
void text(std::string value);
void value(std::string text);
void value(const Node& node);
void value(Node&& node);
void isCaseInsensitive(const bool isCaseInsensitive);
bool isCaseInsensitive() const;
void valueFilter(ValueFilter valueFilter);
ValueFilter valueFilter() const;
Node clone(ValueFilter valueFilter_ = nullptr) const;
private:
std::shared_ptr<class NodeImpl> pimpl {nullptr};
};
namespace literals {
Node operator "" _xml(const char* value, size_t size);
} /* literals */
} /* namespace xml11 */
#endif // XML11_HPP
<commit_msg>Remove iostream and add functional header<commit_after>#ifndef XML11_HPP
#define XML11_HPP
#include <string>
#include <memory>
#include <vector>
#include <functional>
namespace xml11 {
namespace detail {
using mp_true = std::integral_constant<bool, true>;
using mp_false = std::integral_constant<bool, false>;
template<class... T> struct mp_list {};
template<class T>
struct mp_empty_impl;
template<template<class...> class L>
struct mp_empty_impl<L<>> : mp_true {};
template<template<class...> class L, class T1, class... T>
struct mp_empty_impl<L<T1, T...>> : mp_false {};
template<class ... T> using mp_empty = typename mp_empty_impl<mp_list<T...>>::type;
template<class T, class = typename std::enable_if<decltype(*std::declval<T&>(), true)(true), void>::type>
struct mp_like_pointer_impl {
static const bool value = true;
};
template<class T, class = typename std::enable_if<decltype(std::to_string(std::declval<T&>()), true)(true), void>::type>
struct mp_can_be_string_impl {
static const bool value = true;
};
template<class T, class = typename std::enable_if<decltype(std::to_string(*std::declval<T&>()), true)(true), void>::type>
struct mp_can_be_string_from_opt_impl {
static const bool value = true;
};
} // namespace detail
template<class ... T> using mp_empty = std::is_same<detail::mp_empty<T...>, detail::mp_true>;
template<class T, class U> using mp_same = std::is_same<typename std::decay<T>::type, U>;
template<class T, class U> using mp_same_from_opt = std::is_same<typename std::decay<decltype(*std::declval<T&>())>::type, U>;
template<class T> using mp_integral = std::is_integral<typename std::decay<T>::type>;
template<class T> using mp_like_pointer = detail::mp_like_pointer_impl<T>;
template<class T> using mp_can_be_string = detail::mp_can_be_string_impl<T>;
template<class T> using mp_can_be_string_from_opt = detail::mp_can_be_string_from_opt_impl<T>;
using NodeList = std::vector<class Node>;
using ValueFilter = std::function<std::string (const std::string& value)>;
class Node {
public:
enum class Type : char {
ELEMENT = 0,
ATTRIBUTE = 1,
OPTIONAL = 2,
};
class Xml11Exception final : public std::runtime_error {
public:
using std::runtime_error::runtime_error;
};
public:
static Node fromString(const std::string& text, const bool isCaseInsensitive=true, ValueFilter valueFilter_ = nullptr);
std::string toString(const bool indent = true, ValueFilter valueFilter_ = nullptr) const;
public:
static void AddNode(Node&) noexcept
{
}
static void AddNode_(Node&) noexcept
{
}
template<
class Head,
class = typename std::enable_if<
mp_like_pointer<Head>::value,
void
>::type,
class = void
>
static void AddNode_(Node& node, Head&& head)
{
if (head) {
AddNode_(node, *std::forward<Head>(head));
}
}
template<
class T,
class = typename std::enable_if<
mp_same<T, std::string>::value,
void
>::type,
class = void,
class = void
>
static void AddNode_(Node& node, T&& value)
{
node.addNode(std::forward<T>(value));
}
template<
class T,
class = typename std::enable_if<
!mp_same<T, Node>::value &&
!mp_same<T, NodeList>::value &&
!mp_same<T, std::string>::value &&
!mp_same<T, char*>::value &&
mp_can_be_string<T>::value,
void
>::type
>
static void AddNode_(Node& node, T&& value)
{
node.text(std::to_string(std::forward<T>(value)));
}
template<std::size_t N>
static void AddNode_(Node& node, const char(&value)[N])
{
node.text(value);
}
static void AddNode_(Node& node, const Node::Type type)
{
node.type(type);
}
template<
class T,
class ... Args,
class = typename std::enable_if<
mp_same<T, Node>::value,
void
>::type
>
static void AddNode_(Node& node, T&& head)
{
node.addNode(std::forward<T>(head));
}
template<
class T,
class ... Args,
class = typename std::enable_if<
mp_same<T, NodeList>::value,
void
>::type,
class = void
>
static void AddNode_(Node& node, T&& head)
{
node.addNodes(std::forward<T>(head));
}
template<
class T,
class ... Args,
class = typename std::enable_if<
mp_like_pointer<T>::value,
void
>::type
>
static void AddNode_(Node& node, std::initializer_list<T>&& list)
{
for (auto&& item : list) {
AddNode_(node, std::move<T>(item));
}
}
template<
class T,
class = typename std::enable_if<
mp_same<T, Node>::value,
void
>::type
>
static void AddNode_(Node& node, std::initializer_list<T>&& list)
{
AddNode_(node, NodeList(std::move<T>(list)));
}
template<
class T,
class = typename std::enable_if<
mp_same<T, NodeList>::value,
void
>::type,
class = void
>
static void AddNode_(Node& node, std::initializer_list<T>&& list)
{
for (const auto& item : list) {
AddNode_(node, std::move<T>(item));
}
}
template<class Head, class... Tail>
static void AddNode_(Node& node, Head&& head, Tail&& ...tail)
{
AddNode_(node, std::forward<Head>(head));
AddNode_(node, std::forward<Tail>(tail)...);
}
template<class Head, class... Tail>
static void AddNode(Node& node, Head&& head, Tail&& ...tail)
{
AddNode_(node, std::forward<Head>(head));
AddNode_(node, std::forward<Tail>(tail)...);
}
public:
~Node() noexcept;
Node(const std::shared_ptr<class NodeImpl>& node) noexcept;
Node(const Node& node) noexcept;
Node(Node&& node) noexcept;
Node(std::string name);
Node(std::string name, const Node& node);
Node(std::string name, Node&& node);
Node(std::string name, std::string value);
Node(std::string name, std::string value, const Type type);
Node(std::string name, const NodeList& nodes);
Node(std::string name, NodeList&& nodes);
Node(std::string name, std::initializer_list<Node>&& list)
: Node(std::move(name), NodeList(std::move(list)))
{
}
template<
class ... Args,
class = typename std::enable_if<
!mp_empty<Args...>::value,
void
>::type
>
Node(std::string name, std::initializer_list<Node>&& list, Args&& ... args)
: Node(std::move(name), NodeList(std::move(list)))
{
AddNode(*const_cast<Node*>(this), std::forward<Args>(args)...);
}
template<
class T,
class ... Args,
class = typename std::enable_if<
mp_like_pointer<T>::value &&
mp_empty<Args...>::value,
void
>::type
>
Node(std::string name, std::initializer_list<T>&& list)
: Node(std::move(name))
{
for (const auto& item : list) {
AddNode(*const_cast<Node*>(this), std::forward<decltype(item)>(item));
}
}
template<
class T,
class ... Args,
class = typename std::enable_if<
mp_like_pointer<T>::value &&
!mp_empty<Args...>::value,
void
>::type
>
Node(std::string name, std::initializer_list<T>&& list, Args&& ... args)
: Node(std::move(name), std::move(list))
{
AddNode(*const_cast<Node*>(this), std::forward<Args>(args)...);
}
template<
class ... Args,
class = typename std::enable_if<
!mp_empty<Args...>::value,
void
>::type
>
Node(std::string name, std::string value, Args&& ... args)
: Node(std::move(name), std::move(value))
{
AddNode(*const_cast<Node*>(this), std::forward<Args>(args)...);
}
template<
class ... Args,
class = typename std::enable_if<
!mp_empty<Args...>::value,
void
>::type
>
Node(std::string name, std::string value, const Type type, Args&& ... args)
: Node(std::move(name), std::move(value), type)
{
AddNode(*const_cast<Node*>(this), std::forward<Args>(args)...);
}
template<
class T,
class ... Args,
class = typename std::enable_if<
(mp_same<T, Node>::value || mp_same<T, NodeList>::value) &&
!mp_empty<Args...>::value,
void
>::type,
class = void
>
Node(std::string name, T&& value, Args&& ... args)
: Node(std::move(name), std::forward<T>(value))
{
AddNode(*const_cast<Node*>(this), std::forward<Args>(args)...);
}
template<
class T,
class ... Args,
class = typename std::enable_if<
mp_integral<T>::value &&
mp_empty<Args...>::value,
void
>::type
>
Node(std::string name, T&& value)
: Node(std::move(name), std::to_string(std::forward<T>(value)))
{
}
template<
class T,
class ... Args,
class = typename std::enable_if<
mp_integral<T>::value &&
!mp_empty<Args...>::value,
void
>::type
>
Node(std::string name, T&& value, Args&& ... args)
: Node(std::move(name), std::to_string(std::forward<T>(value)))
{
AddNode(*const_cast<Node*>(this), std::forward<Args>(args)...);
}
template<
class T,
class=typename std::enable_if<
!mp_same<T, std::string>::value &&
!mp_same<T, char*>::value &&
!mp_same_from_opt<T, std::string>::value &&
mp_can_be_string_from_opt<T>::value,
T
>::type,
class=void
>
Node(std::string name, const T& param)
: Node(std::move(name))
{
if (param) {
this->value(std::to_string(*param));
}
else {
this->pimpl = nullptr;
}
}
template<
class T,
class=typename std::enable_if<
!mp_same<T, std::string>::value &&
!mp_same<T, char*>::value &&
mp_same_from_opt<T, std::string>::value,
T
>::type,
class=void,
class=void
>
Node(std::string name, const T& param)
: Node(std::move(name))
{
if (param) {
this->value(*param);
}
else {
this->pimpl = nullptr;
}
}
Node& operator = (const Node& node) noexcept;
Node& operator = (Node&& node) noexcept;
bool operator == (const Node& node) const noexcept;
bool operator != (const Node& node) const noexcept;
operator bool() const noexcept;
NodeList operator [] (const std::string& name);
NodeList operator [] (const char* name);
NodeList operator [] (const Type& type);
const NodeList operator [] (const std::string& name) const;
const NodeList operator [] (const char* name) const;
const NodeList operator [] (const Type& type) const;
NodeList findNodes(const std::string& name);
NodeList findNodes(const Type& type);
const NodeList findNodes(const std::string& name) const;
const NodeList findNodes(const Type& type) const;
NodeList findNodesXPath(const std::string& name);
const NodeList findNodesXPath(const std::string& name) const;
Node operator () (const std::string& name);
Node operator () (const Type& type);
const Node operator () (const std::string& name) const;
const Node operator () (const Type& type) const;
Node findNode(const std::string& name);
Node findNode(const Type& type);
const Node findNode(const std::string& name) const;
const Node findNode(const Type& type) const;
Node findNodeXPath(const std::string& name);
const Node findNodeXPath(const std::string& name) const;
Node& operator -= (const Node& root);
Node& operator -= (Node&& root);
Node& operator -= (const NodeList& nodes);
Node& operator -= (NodeList&& nodes);
Node& operator += (const Node& root);
Node& operator += (Node&& root);
Node& operator += (const NodeList& nodes);
Node& operator += (NodeList&& nodes);
Node& addNode(const Node& node);
Node& addNode(Node&& node);
Node& addNode(std::string name);
Node& addNode(std::string name, std::string value);
Node& addNode(std::string name, std::string value, const Node::Type type);
template<
class T,
class=typename std::enable_if<
mp_can_be_string<T>::value,
T
>::type
>
Node& addNode(std::string name, T&& value)
{
return addNode(std::move(name), std::to_string(std::forward<T>(value)));
}
Node& addAttribute(std::string name);
Node& addAttribute(std::string name, std::string value);
Node& addNodes(const NodeList& node);
Node& addNodes(NodeList&& node);
Node& eraseNode(const Node& node);
Node& eraseNode(Node&& node);
Node& eraseNodes(const NodeList& node);
Node& eraseNodes(NodeList&& nodes);
NodeList nodes();
const NodeList nodes() const;
Node::Type type() const;
void type(const Node::Type type);
std::string& name() const;
void name(std::string name);
std::string& text() const;
void text(std::string value);
void value(std::string text);
void value(const Node& node);
void value(Node&& node);
void isCaseInsensitive(const bool isCaseInsensitive);
bool isCaseInsensitive() const;
void valueFilter(ValueFilter valueFilter);
ValueFilter valueFilter() const;
Node clone(ValueFilter valueFilter_ = nullptr) const;
private:
std::shared_ptr<class NodeImpl> pimpl {nullptr};
};
namespace literals {
Node operator "" _xml(const char* value, size_t size);
} /* literals */
} /* namespace xml11 */
#endif // XML11_HPP
<|endoftext|>
|
<commit_before>#include "CoreAudio.h"
#include "Functiondiscoverykeys_devpkey.h"
#include "../../Logger.h"
// {EC9CB649-7E84-4B42-B367-7FC39BE17806}
static const GUID G3RVXCoreAudioEvent = { 0xec9cb649, 0x7e84, 0x4b42,
{ 0xb3, 0x67, 0x7f, 0xc3, 0x9b, 0xe1, 0x78, 0x6 } };
HRESULT CoreAudio::Init() {
HRESULT hr;
hr = CoCreateInstance(
__uuidof(MMDeviceEnumerator),
NULL,
CLSCTX_INPROC_SERVER,
IID_PPV_ARGS(&_devEnumerator));
if (SUCCEEDED(hr)) {
hr = _devEnumerator->RegisterEndpointNotificationCallback(this);
if (SUCCEEDED(hr)) {
hr = AttachDevice();
}
}
return hr;
}
HRESULT CoreAudio::Init(std::wstring deviceId) {
_devId = deviceId;
return Init();
}
void CoreAudio::Dispose() {
DetachDevice();
_devEnumerator->UnregisterEndpointNotificationCallback(this);
}
HRESULT CoreAudio::AttachDevice() {
HRESULT hr;
if (_devId.empty()) {
/* Use default device */
hr = _devEnumerator->GetDefaultAudioEndpoint(eRender,
eMultimedia, &_device);
if (SUCCEEDED(hr)) {
LPWSTR id = NULL;
_device->GetId(&id);
if (id) {
_devId = std::wstring(id);
CoTaskMemFree(id);
}
}
} else {
hr = _devEnumerator->GetDevice(_devId.c_str(), &_device);
}
if (SUCCEEDED(hr)) {
hr = _device->Activate(__uuidof(_volumeControl),
CLSCTX_INPROC_SERVER, NULL, (void **) &_volumeControl);
CLOG(L"Attached to audio device: [%s]", DeviceName().c_str());
if (SUCCEEDED(hr)) {
hr = _volumeControl->RegisterControlChangeNotify(this);
_registeredNotifications = SUCCEEDED(hr);
}
} else {
CLOG(L"Failed to find audio device!");
}
return hr;
}
void CoreAudio::DetachDevice() {
if (_volumeControl != NULL) {
if (_registeredNotifications) {
_volumeControl->UnregisterControlChangeNotify(this);
_registeredNotifications = false;
}
_volumeControl->Release();
}
if (_device != NULL) {
_device->Release();
}
}
HRESULT CoreAudio::OnNotify(PAUDIO_VOLUME_NOTIFICATION_DATA pNotify) {
if (pNotify->guidEventContext == G3RVXCoreAudioEvent) {
PostMessage(_notifyHwnd, MSG_VOL_CHNG, (WPARAM) 1, NULL);
} else {
PostMessage(_notifyHwnd, MSG_VOL_CHNG, NULL, NULL);
}
return S_OK;
}
HRESULT CoreAudio::OnDefaultDeviceChanged(
EDataFlow flow, ERole role, LPCWSTR pwstrDefaultDeviceId) {
if (flow == eRender) {
PostMessage(_notifyHwnd, MSG_VOL_DEVCHNG, 0, 0);
}
return S_OK;
}
HRESULT CoreAudio::SelectDevice(std::wstring deviceId) {
HRESULT hr;
_devId = deviceId;
DetachDevice();
hr = AttachDevice();
return hr;
}
HRESULT CoreAudio::SelectDefaultDevice() {
HRESULT hr;
_devId = L"";
DetachDevice();
hr = AttachDevice();
return hr;
}
std::list<VolumeController::DeviceInfo> CoreAudio::ListDevices() {
std::list<VolumeController::DeviceInfo> devList;
IMMDeviceCollection *devices = NULL;
HRESULT hr = _devEnumerator->EnumAudioEndpoints(
eRender,
DEVICE_STATE_ACTIVE | DEVICE_STATE_UNPLUGGED,
&devices);
if (FAILED(hr)) {
if (devices) {
devices->Release();
}
return devList;
}
UINT numDevices = 0;
devices->GetCount(&numDevices);
LPWSTR devId;
for (unsigned int i = 0; i < numDevices; ++i) {
IMMDevice *device = NULL;
HRESULT hr = devices->Item(i, &device);
if (FAILED(hr)) {
if (device) {
device->Release();
}
continue;
}
device->GetId(&devId);
std::wstring idStr;
if (devId) {
idStr = std::wstring(devId);
CoTaskMemFree(devId);
} else {
continue;
}
VolumeController::DeviceInfo devInfo = {};
devInfo.id = idStr;
devInfo.name = DeviceName(idStr);
devList.push_back(devInfo);
device->Release();
}
devices->Release();
return devList;
}
std::wstring CoreAudio::DeviceId() {
return _devId;
}
std::wstring CoreAudio::DeviceName() {
return DeviceName(_device);
}
std::wstring CoreAudio::DeviceDesc() {
return DeviceDesc(_device);
}
std::wstring CoreAudio::DeviceName(std::wstring deviceId) {
IMMDevice *device;
HRESULT hr = _devEnumerator->GetDevice(deviceId.c_str(), &device);
if (FAILED(hr)) {
return L"";
}
std::wstring name = DeviceName(device);
device->Release();
return name;
}
std::wstring CoreAudio::DeviceDesc(std::wstring deviceId) {
IMMDevice *device;
HRESULT hr = _devEnumerator->GetDevice(deviceId.c_str(), &device);
if (FAILED(hr)) {
return L"";
}
std::wstring name = DeviceName(device);
device->Release();
return name;
}
std::wstring CoreAudio::DeviceName(IMMDevice *device) {
if (device == NULL) {
return L"";
}
IPropertyStore *props = NULL;
HRESULT hr = device->OpenPropertyStore(STGM_READ, &props);
if (FAILED(hr)) {
return L"";
}
PROPVARIANT pvName;
PropVariantInit(&pvName);
props->GetValue(PKEY_Device_FriendlyName, &pvName);
std::wstring str(pvName.pwszVal);
PropVariantClear(&pvName);
props->Release();
return str;
}
std::wstring CoreAudio::DeviceDesc(IMMDevice *device) {
if (device == NULL) {
return L"";
}
IPropertyStore *props = NULL;
HRESULT hr = device->OpenPropertyStore(STGM_READ, &props);
if (FAILED(hr)) {
return L"";
}
PROPVARIANT pvDesc;
PropVariantInit(&pvDesc);
props->GetValue(PKEY_Device_DeviceDesc, &pvDesc);
std::wstring str(pvDesc.pwszVal);
PropVariantClear(&pvDesc);
props->Release();
return str;
}
float CoreAudio::Volume() {
float vol = 0.0f;
if (_volumeControl) {
_volumeControl->GetMasterVolumeLevelScalar(&vol);
}
return vol;
}
void CoreAudio::Volume(float vol) {
if (vol > 1.0f) {
vol = 1.0f;
}
if (vol < 0.0f) {
vol = 0.0f;
}
if (_volumeControl) {
_volumeControl->SetMasterVolumeLevelScalar(vol, &G3RVXCoreAudioEvent);
}
}
bool CoreAudio::Muted() {
if (_volumeControl == NULL) {
return true;
}
BOOL muted = FALSE;
_volumeControl->GetMute(&muted);
return (muted == TRUE) ? true : false;
}
void CoreAudio::Muted(bool muted) {
if (_volumeControl) {
_volumeControl->SetMute(muted, &G3RVXCoreAudioEvent);
}
}
ULONG CoreAudio::AddRef() {
return InterlockedIncrement(&_refCount);
}
ULONG CoreAudio::Release() {
long lRef = InterlockedDecrement(&_refCount);
if (lRef == 0) {
delete this;
}
return lRef;
}
HRESULT CoreAudio::QueryInterface(REFIID iid, void **ppUnk) {
if ((iid == __uuidof(IUnknown)) ||
(iid == __uuidof(IMMNotificationClient))) {
*ppUnk = static_cast<IMMNotificationClient*>(this);
} else if (iid == __uuidof(IAudioEndpointVolumeCallback)) {
*ppUnk = static_cast<IAudioEndpointVolumeCallback*>(this);
} else {
*ppUnk = NULL;
return E_NOINTERFACE;
}
AddRef();
return S_OK;
}<commit_msg>Add missing checks for function results<commit_after>#include "CoreAudio.h"
#include "Functiondiscoverykeys_devpkey.h"
#include "../../Logger.h"
// {EC9CB649-7E84-4B42-B367-7FC39BE17806}
static const GUID G3RVXCoreAudioEvent = { 0xec9cb649, 0x7e84, 0x4b42,
{ 0xb3, 0x67, 0x7f, 0xc3, 0x9b, 0xe1, 0x78, 0x6 } };
HRESULT CoreAudio::Init() {
HRESULT hr;
hr = CoCreateInstance(
__uuidof(MMDeviceEnumerator),
NULL,
CLSCTX_INPROC_SERVER,
IID_PPV_ARGS(&_devEnumerator));
if (SUCCEEDED(hr)) {
hr = _devEnumerator->RegisterEndpointNotificationCallback(this);
if (SUCCEEDED(hr)) {
hr = AttachDevice();
}
}
return hr;
}
HRESULT CoreAudio::Init(std::wstring deviceId) {
_devId = deviceId;
return Init();
}
void CoreAudio::Dispose() {
DetachDevice();
_devEnumerator->UnregisterEndpointNotificationCallback(this);
}
HRESULT CoreAudio::AttachDevice() {
HRESULT hr;
if (_devId.empty()) {
/* Use default device */
hr = _devEnumerator->GetDefaultAudioEndpoint(eRender,
eMultimedia, &_device);
if (SUCCEEDED(hr)) {
LPWSTR id = NULL;
hr = _device->GetId(&id);
if (SUCCEEDED(hr) && id) {
_devId = std::wstring(id);
CoTaskMemFree(id);
}
}
} else {
hr = _devEnumerator->GetDevice(_devId.c_str(), &_device);
}
if (SUCCEEDED(hr)) {
hr = _device->Activate(__uuidof(_volumeControl),
CLSCTX_INPROC_SERVER, NULL, (void **) &_volumeControl);
CLOG(L"Attached to audio device: [%s]", DeviceName().c_str());
if (SUCCEEDED(hr)) {
hr = _volumeControl->RegisterControlChangeNotify(this);
_registeredNotifications = SUCCEEDED(hr);
}
} else {
CLOG(L"Failed to find audio device!");
}
return hr;
}
void CoreAudio::DetachDevice() {
if (_volumeControl != NULL) {
if (_registeredNotifications) {
_volumeControl->UnregisterControlChangeNotify(this);
_registeredNotifications = false;
}
_volumeControl->Release();
}
if (_device != NULL) {
_device->Release();
}
}
HRESULT CoreAudio::OnNotify(PAUDIO_VOLUME_NOTIFICATION_DATA pNotify) {
if (pNotify->guidEventContext == G3RVXCoreAudioEvent) {
PostMessage(_notifyHwnd, MSG_VOL_CHNG, (WPARAM) 1, NULL);
} else {
PostMessage(_notifyHwnd, MSG_VOL_CHNG, NULL, NULL);
}
return S_OK;
}
HRESULT CoreAudio::OnDefaultDeviceChanged(
EDataFlow flow, ERole role, LPCWSTR pwstrDefaultDeviceId) {
if (flow == eRender) {
PostMessage(_notifyHwnd, MSG_VOL_DEVCHNG, 0, 0);
}
return S_OK;
}
HRESULT CoreAudio::SelectDevice(std::wstring deviceId) {
HRESULT hr;
_devId = deviceId;
DetachDevice();
hr = AttachDevice();
return hr;
}
HRESULT CoreAudio::SelectDefaultDevice() {
HRESULT hr;
_devId = L"";
DetachDevice();
hr = AttachDevice();
return hr;
}
std::list<VolumeController::DeviceInfo> CoreAudio::ListDevices() {
std::list<VolumeController::DeviceInfo> devList;
IMMDeviceCollection *devices = NULL;
HRESULT hr = _devEnumerator->EnumAudioEndpoints(
eRender,
DEVICE_STATE_ACTIVE | DEVICE_STATE_UNPLUGGED,
&devices);
if (FAILED(hr)) {
return devList;
}
UINT numDevices = 0;
hr = devices->GetCount(&numDevices);
if (FAILED(hr)) {
return devList;
}
LPWSTR devId;
for (unsigned int i = 0; i < numDevices; ++i) {
IMMDevice *device = NULL;
HRESULT hr = devices->Item(i, &device);
if (FAILED(hr)) {
continue;
}
hr = device->GetId(&devId);
if (FAILED(hr)) {
device->Release();
continue;
}
std::wstring idStr;
if (devId) {
idStr = std::wstring(devId);
CoTaskMemFree(devId);
} else {
continue;
}
VolumeController::DeviceInfo devInfo = {};
devInfo.id = idStr;
devInfo.name = DeviceName(idStr);
devList.push_back(devInfo);
device->Release();
}
devices->Release();
return devList;
}
std::wstring CoreAudio::DeviceId() {
return _devId;
}
std::wstring CoreAudio::DeviceName() {
return DeviceName(_device);
}
std::wstring CoreAudio::DeviceDesc() {
return DeviceDesc(_device);
}
std::wstring CoreAudio::DeviceName(std::wstring deviceId) {
IMMDevice *device;
HRESULT hr = _devEnumerator->GetDevice(deviceId.c_str(), &device);
if (FAILED(hr)) {
return L"";
}
std::wstring name = DeviceName(device);
device->Release();
return name;
}
std::wstring CoreAudio::DeviceDesc(std::wstring deviceId) {
IMMDevice *device;
HRESULT hr = _devEnumerator->GetDevice(deviceId.c_str(), &device);
if (FAILED(hr)) {
return L"";
}
std::wstring name = DeviceName(device);
device->Release();
return name;
}
std::wstring CoreAudio::DeviceName(IMMDevice *device) {
if (device == NULL) {
return L"";
}
IPropertyStore *props = NULL;
HRESULT hr = device->OpenPropertyStore(STGM_READ, &props);
if (FAILED(hr)) {
return L"";
}
PROPVARIANT pvName;
PropVariantInit(&pvName);
hr = props->GetValue(PKEY_Device_FriendlyName, &pvName);
if (FAILED(hr)) {
props->Release();
return L"";
}
std::wstring str(pvName.pwszVal);
PropVariantClear(&pvName);
props->Release();
return str;
}
std::wstring CoreAudio::DeviceDesc(IMMDevice *device) {
HRESULT hr;
if (device == NULL) {
return L"";
}
IPropertyStore *props = NULL;
hr = device->OpenPropertyStore(STGM_READ, &props);
if (FAILED(hr)) {
return L"";
}
PROPVARIANT pvDesc;
PropVariantInit(&pvDesc);
hr = props->GetValue(PKEY_Device_DeviceDesc, &pvDesc);
if (FAILED(hr)) {
props->Release();
return L"";
}
std::wstring str(pvDesc.pwszVal);
PropVariantClear(&pvDesc);
props->Release();
return str;
}
float CoreAudio::Volume() {
float vol = 0.0f;
if (_volumeControl) {
HRESULT hr = _volumeControl->GetMasterVolumeLevelScalar(&vol);
if (FAILED(hr)) {
return 0;
}
}
return vol;
}
void CoreAudio::Volume(float vol) {
if (vol > 1.0f) {
vol = 1.0f;
}
if (vol < 0.0f) {
vol = 0.0f;
}
if (_volumeControl) {
_volumeControl->SetMasterVolumeLevelScalar(vol, &G3RVXCoreAudioEvent);
}
}
bool CoreAudio::Muted() {
if (_volumeControl == NULL) {
return true;
}
BOOL muted = FALSE;
HRESULT hr = _volumeControl->GetMute(&muted);
if (FAILED(hr)) {
return false;
}
return (muted == TRUE) ? true : false;
}
void CoreAudio::Muted(bool muted) {
if (_volumeControl) {
_volumeControl->SetMute(muted, &G3RVXCoreAudioEvent);
}
}
ULONG CoreAudio::AddRef() {
return InterlockedIncrement(&_refCount);
}
ULONG CoreAudio::Release() {
long lRef = InterlockedDecrement(&_refCount);
if (lRef == 0) {
delete this;
}
return lRef;
}
HRESULT CoreAudio::QueryInterface(REFIID iid, void **ppUnk) {
if ((iid == __uuidof(IUnknown)) ||
(iid == __uuidof(IMMNotificationClient))) {
*ppUnk = static_cast<IMMNotificationClient*>(this);
} else if (iid == __uuidof(IAudioEndpointVolumeCallback)) {
*ppUnk = static_cast<IAudioEndpointVolumeCallback*>(this);
} else {
*ppUnk = NULL;
return E_NOINTERFACE;
}
AddRef();
return S_OK;
}<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2012, 2014 ARM Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Copyright (c) 2002-2005 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Nathan Binkert
* Steve Reinhardt
* Andreas Hansson
*/
#ifndef __BASE_ADDR_RANGE_HH__
#define __BASE_ADDR_RANGE_HH__
#include <list>
#include <vector>
#include "base/bitfield.hh"
#include "base/cprintf.hh"
#include "base/misc.hh"
#include "base/types.hh"
/**
* The AddrRange class encapsulates an address range, and supports a
* number of tests to check if two ranges intersect, if a range
* contains a specific address etc. Besides a basic range, the
* AddrRange also support interleaved ranges, to stripe across cache
* banks, or memory controllers. The interleaving is implemented by
* allowing a number of bits of the address, at an arbitrary bit
* position, to be used as interleaving bits with an associated
* matching value. In addition, to prevent uniformly strided address
* patterns from a very biased interleaving, we also allow basic
* XOR-based hashing by specifying an additional set of bits to XOR
* with before matching.
*
* The AddrRange is also able to coalesce a number of interleaved
* ranges to a contiguous range.
*/
class AddrRange
{
private:
/// Private fields for the start and end of the range
/// Both _start and _end are part of the range.
Addr _start;
Addr _end;
/// The high bit of the slice that is used for interleaving
uint8_t intlvHighBit;
/// The high bit of the slice used to XOR hash the value we match
/// against, set to 0 to disable.
uint8_t xorHighBit;
/// The number of bits used for interleaving, set to 0 to disable
uint8_t intlvBits;
/// The value to compare the slice addr[high:(high - bits + 1)]
/// with.
uint8_t intlvMatch;
public:
AddrRange()
: _start(1), _end(0), intlvHighBit(0), xorHighBit(0), intlvBits(0),
intlvMatch(0)
{}
AddrRange(Addr _start, Addr _end, uint8_t _intlv_high_bit,
uint8_t _xor_high_bit, uint8_t _intlv_bits,
uint8_t _intlv_match)
: _start(_start), _end(_end), intlvHighBit(_intlv_high_bit),
xorHighBit(_xor_high_bit), intlvBits(_intlv_bits),
intlvMatch(_intlv_match)
{
// sanity checks
fatal_if(intlvBits && intlvMatch >= ULL(1) << intlvBits,
"Match value %d does not fit in %d interleaving bits\n",
intlvMatch, intlvBits);
// ignore the XOR bits if not interleaving
if (intlvBits && xorHighBit) {
if (xorHighBit == intlvHighBit) {
fatal("XOR and interleave high bit must be different\n");
} else if (xorHighBit > intlvHighBit) {
if ((xorHighBit - intlvHighBit) < intlvBits)
fatal("XOR and interleave high bit must be at least "
"%d bits apart\n", intlvBits);
} else {
if ((intlvHighBit - xorHighBit) < intlvBits) {
fatal("Interleave and XOR high bit must be at least "
"%d bits apart\n", intlvBits);
}
}
}
}
AddrRange(Addr _start, Addr _end)
: _start(_start), _end(_end), intlvHighBit(0), xorHighBit(0),
intlvBits(0), intlvMatch(0)
{}
/**
* Create an address range by merging a collection of interleaved
* ranges.
*
* @param ranges Interleaved ranges to be merged
*/
AddrRange(const std::vector<AddrRange>& ranges)
: _start(1), _end(0), intlvHighBit(0), xorHighBit(0), intlvBits(0),
intlvMatch(0)
{
if (!ranges.empty()) {
// get the values from the first one and check the others
_start = ranges.front()._start;
_end = ranges.front()._end;
intlvHighBit = ranges.front().intlvHighBit;
xorHighBit = ranges.front().xorHighBit;
intlvBits = ranges.front().intlvBits;
if (ranges.size() != (ULL(1) << intlvBits))
fatal("Got %d ranges spanning %d interleaving bits\n",
ranges.size(), intlvBits);
uint8_t match = 0;
for (const auto& r : ranges) {
if (!mergesWith(r))
fatal("Can only merge ranges with the same start, end "
"and interleaving bits\n");
if (r.intlvMatch != match)
fatal("Expected interleave match %d but got %d when "
"merging\n", match, r.intlvMatch);
++match;
}
// our range is complete and we can turn this into a
// non-interleaved range
intlvHighBit = 0;
xorHighBit = 0;
intlvBits = 0;
}
}
/**
* Determine if the range is interleaved or not.
*
* @return true if interleaved
*/
bool interleaved() const { return intlvBits != 0; }
/**
* Determine if the range interleaving is hashed or not.
*/
bool hashed() const { return interleaved() && xorHighBit != 0; }
/**
* Determing the interleaving granularity of the range.
*
* @return The size of the regions created by the interleaving bits
*/
uint64_t granularity() const
{
return ULL(1) << (intlvHighBit - intlvBits + 1);
}
/**
* Determine the number of interleaved address stripes this range
* is part of.
*
* @return The number of stripes spanned by the interleaving bits
*/
uint32_t stripes() const { return ULL(1) << intlvBits; }
/**
* Get the size of the address range. For a case where
* interleaving is used we make the simplifying assumption that
* the size is a divisible by the size of the interleaving slice.
*/
Addr size() const
{
return (_end - _start + 1) >> intlvBits;
}
/**
* Determine if the range is valid.
*/
bool valid() const { return _start <= _end; }
/**
* Get the start address of the range.
*/
Addr start() const { return _start; }
/**
* Get a string representation of the range. This could
* alternatively be implemented as a operator<<, but at the moment
* that seems like overkill.
*/
std::string to_string() const
{
if (interleaved()) {
if (hashed()) {
return csprintf("[%#llx : %#llx], [%d : %d] XOR [%d : %d] = %d",
_start, _end,
intlvHighBit, intlvHighBit - intlvBits + 1,
xorHighBit, xorHighBit - intlvBits + 1,
intlvMatch);
} else {
return csprintf("[%#llx : %#llx], [%d : %d] = %d",
_start, _end,
intlvHighBit, intlvHighBit - intlvBits + 1,
intlvMatch);
}
} else {
return csprintf("[%#llx : %#llx]", _start, _end);
}
}
/**
* Determine if another range merges with the current one, i.e. if
* they are part of the same contigous range and have the same
* interleaving bits.
*
* @param r Range to evaluate merging with
* @return true if the two ranges would merge
*/
bool mergesWith(const AddrRange& r) const
{
return r._start == _start && r._end == _end &&
r.intlvHighBit == intlvHighBit &&
r.xorHighBit == xorHighBit &&
r.intlvBits == intlvBits;
}
/**
* Determine if another range intersects this one, i.e. if there
* is an address that is both in this range and the other
* range. No check is made to ensure either range is valid.
*
* @param r Range to intersect with
* @return true if the intersection of the two ranges is not empty
*/
bool intersects(const AddrRange& r) const
{
if (!interleaved()) {
return _start <= r._end && _end >= r._start;
}
// the current range is interleaved, split the check up in
// three cases
if (r.size() == 1)
// keep it simple and check if the address is within
// this range
return contains(r.start());
else if (!r.interleaved())
// be conservative and ignore the interleaving
return _start <= r._end && _end >= r._start;
else if (mergesWith(r))
// restrict the check to ranges that belong to the
// same chunk
return intlvMatch == r.intlvMatch;
else
panic("Cannot test intersection of interleaved range %s\n",
to_string());
}
/**
* Determine if this range is a subset of another range, i.e. if
* every address in this range is also in the other range. No
* check is made to ensure either range is valid.
*
* @param r Range to compare with
* @return true if the this range is a subset of the other one
*/
bool isSubset(const AddrRange& r) const
{
if (interleaved())
panic("Cannot test subset of interleaved range %s\n", to_string());
return _start >= r._start && _end <= r._end;
}
/**
* Determine if the range contains an address.
*
* @param a Address to compare with
* @return true if the address is in the range
*/
bool contains(const Addr& a) const
{
// check if the address is in the range and if there is either
// no interleaving, or with interleaving also if the selected
// bits from the address match the interleaving value
bool in_range = a >= _start && a <= _end;
if (!interleaved()) {
return in_range;
} else if (in_range) {
if (!hashed()) {
return bits(a, intlvHighBit, intlvHighBit - intlvBits + 1) ==
intlvMatch;
} else {
return (bits(a, intlvHighBit, intlvHighBit - intlvBits + 1) ^
bits(a, xorHighBit, xorHighBit - intlvBits + 1)) ==
intlvMatch;
}
}
return false;
}
/**
* Keep the operators away from SWIG.
*/
#ifndef SWIG
/**
* Less-than operator used to turn an STL map into a binary search
* tree of non-overlapping address ranges.
*
* @param r Range to compare with
* @return true if the start address is less than that of the other range
*/
bool operator<(const AddrRange& r) const
{
if (_start != r._start)
return _start < r._start;
else
// for now assume that the end is also the same, and that
// we are looking at the same interleaving bits
return intlvMatch < r.intlvMatch;
}
#endif // SWIG
};
/**
* Convenience typedef for a collection of address ranges
*/
typedef std::list<AddrRange> AddrRangeList;
inline AddrRange
RangeEx(Addr start, Addr end)
{ return AddrRange(start, end - 1); }
inline AddrRange
RangeIn(Addr start, Addr end)
{ return AddrRange(start, end); }
inline AddrRange
RangeSize(Addr start, Addr size)
{ return AddrRange(start, start + size - 1); }
#endif // __BASE_ADDR_RANGE_HH__
<commit_msg>base: add an accessor and operators ==,!= to address ranges<commit_after>/*
* Copyright (c) 2012, 2014 ARM Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Copyright (c) 2002-2005 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Nathan Binkert
* Steve Reinhardt
* Andreas Hansson
*/
#ifndef __BASE_ADDR_RANGE_HH__
#define __BASE_ADDR_RANGE_HH__
#include <list>
#include <vector>
#include "base/bitfield.hh"
#include "base/cprintf.hh"
#include "base/misc.hh"
#include "base/types.hh"
/**
* The AddrRange class encapsulates an address range, and supports a
* number of tests to check if two ranges intersect, if a range
* contains a specific address etc. Besides a basic range, the
* AddrRange also support interleaved ranges, to stripe across cache
* banks, or memory controllers. The interleaving is implemented by
* allowing a number of bits of the address, at an arbitrary bit
* position, to be used as interleaving bits with an associated
* matching value. In addition, to prevent uniformly strided address
* patterns from a very biased interleaving, we also allow basic
* XOR-based hashing by specifying an additional set of bits to XOR
* with before matching.
*
* The AddrRange is also able to coalesce a number of interleaved
* ranges to a contiguous range.
*/
class AddrRange
{
private:
/// Private fields for the start and end of the range
/// Both _start and _end are part of the range.
Addr _start;
Addr _end;
/// The high bit of the slice that is used for interleaving
uint8_t intlvHighBit;
/// The high bit of the slice used to XOR hash the value we match
/// against, set to 0 to disable.
uint8_t xorHighBit;
/// The number of bits used for interleaving, set to 0 to disable
uint8_t intlvBits;
/// The value to compare the slice addr[high:(high - bits + 1)]
/// with.
uint8_t intlvMatch;
public:
AddrRange()
: _start(1), _end(0), intlvHighBit(0), xorHighBit(0), intlvBits(0),
intlvMatch(0)
{}
AddrRange(Addr _start, Addr _end, uint8_t _intlv_high_bit,
uint8_t _xor_high_bit, uint8_t _intlv_bits,
uint8_t _intlv_match)
: _start(_start), _end(_end), intlvHighBit(_intlv_high_bit),
xorHighBit(_xor_high_bit), intlvBits(_intlv_bits),
intlvMatch(_intlv_match)
{
// sanity checks
fatal_if(intlvBits && intlvMatch >= ULL(1) << intlvBits,
"Match value %d does not fit in %d interleaving bits\n",
intlvMatch, intlvBits);
// ignore the XOR bits if not interleaving
if (intlvBits && xorHighBit) {
if (xorHighBit == intlvHighBit) {
fatal("XOR and interleave high bit must be different\n");
} else if (xorHighBit > intlvHighBit) {
if ((xorHighBit - intlvHighBit) < intlvBits)
fatal("XOR and interleave high bit must be at least "
"%d bits apart\n", intlvBits);
} else {
if ((intlvHighBit - xorHighBit) < intlvBits) {
fatal("Interleave and XOR high bit must be at least "
"%d bits apart\n", intlvBits);
}
}
}
}
AddrRange(Addr _start, Addr _end)
: _start(_start), _end(_end), intlvHighBit(0), xorHighBit(0),
intlvBits(0), intlvMatch(0)
{}
/**
* Create an address range by merging a collection of interleaved
* ranges.
*
* @param ranges Interleaved ranges to be merged
*/
AddrRange(const std::vector<AddrRange>& ranges)
: _start(1), _end(0), intlvHighBit(0), xorHighBit(0), intlvBits(0),
intlvMatch(0)
{
if (!ranges.empty()) {
// get the values from the first one and check the others
_start = ranges.front()._start;
_end = ranges.front()._end;
intlvHighBit = ranges.front().intlvHighBit;
xorHighBit = ranges.front().xorHighBit;
intlvBits = ranges.front().intlvBits;
if (ranges.size() != (ULL(1) << intlvBits))
fatal("Got %d ranges spanning %d interleaving bits\n",
ranges.size(), intlvBits);
uint8_t match = 0;
for (const auto& r : ranges) {
if (!mergesWith(r))
fatal("Can only merge ranges with the same start, end "
"and interleaving bits\n");
if (r.intlvMatch != match)
fatal("Expected interleave match %d but got %d when "
"merging\n", match, r.intlvMatch);
++match;
}
// our range is complete and we can turn this into a
// non-interleaved range
intlvHighBit = 0;
xorHighBit = 0;
intlvBits = 0;
}
}
/**
* Determine if the range is interleaved or not.
*
* @return true if interleaved
*/
bool interleaved() const { return intlvBits != 0; }
/**
* Determine if the range interleaving is hashed or not.
*/
bool hashed() const { return interleaved() && xorHighBit != 0; }
/**
* Determing the interleaving granularity of the range.
*
* @return The size of the regions created by the interleaving bits
*/
uint64_t granularity() const
{
return ULL(1) << (intlvHighBit - intlvBits + 1);
}
/**
* Determine the number of interleaved address stripes this range
* is part of.
*
* @return The number of stripes spanned by the interleaving bits
*/
uint32_t stripes() const { return ULL(1) << intlvBits; }
/**
* Get the size of the address range. For a case where
* interleaving is used we make the simplifying assumption that
* the size is a divisible by the size of the interleaving slice.
*/
Addr size() const
{
return (_end - _start + 1) >> intlvBits;
}
/**
* Determine if the range is valid.
*/
bool valid() const { return _start <= _end; }
/**
* Get the start address of the range.
*/
Addr start() const { return _start; }
/**
* Get the end address of the range.
*/
Addr end() const { return _end; }
/**
* Get a string representation of the range. This could
* alternatively be implemented as a operator<<, but at the moment
* that seems like overkill.
*/
std::string to_string() const
{
if (interleaved()) {
if (hashed()) {
return csprintf("[%#llx : %#llx], [%d : %d] XOR [%d : %d] = %d",
_start, _end,
intlvHighBit, intlvHighBit - intlvBits + 1,
xorHighBit, xorHighBit - intlvBits + 1,
intlvMatch);
} else {
return csprintf("[%#llx : %#llx], [%d : %d] = %d",
_start, _end,
intlvHighBit, intlvHighBit - intlvBits + 1,
intlvMatch);
}
} else {
return csprintf("[%#llx : %#llx]", _start, _end);
}
}
/**
* Determine if another range merges with the current one, i.e. if
* they are part of the same contigous range and have the same
* interleaving bits.
*
* @param r Range to evaluate merging with
* @return true if the two ranges would merge
*/
bool mergesWith(const AddrRange& r) const
{
return r._start == _start && r._end == _end &&
r.intlvHighBit == intlvHighBit &&
r.xorHighBit == xorHighBit &&
r.intlvBits == intlvBits;
}
/**
* Determine if another range intersects this one, i.e. if there
* is an address that is both in this range and the other
* range. No check is made to ensure either range is valid.
*
* @param r Range to intersect with
* @return true if the intersection of the two ranges is not empty
*/
bool intersects(const AddrRange& r) const
{
if (!interleaved()) {
return _start <= r._end && _end >= r._start;
}
// the current range is interleaved, split the check up in
// three cases
if (r.size() == 1)
// keep it simple and check if the address is within
// this range
return contains(r.start());
else if (!r.interleaved())
// be conservative and ignore the interleaving
return _start <= r._end && _end >= r._start;
else if (mergesWith(r))
// restrict the check to ranges that belong to the
// same chunk
return intlvMatch == r.intlvMatch;
else
panic("Cannot test intersection of interleaved range %s\n",
to_string());
}
/**
* Determine if this range is a subset of another range, i.e. if
* every address in this range is also in the other range. No
* check is made to ensure either range is valid.
*
* @param r Range to compare with
* @return true if the this range is a subset of the other one
*/
bool isSubset(const AddrRange& r) const
{
if (interleaved())
panic("Cannot test subset of interleaved range %s\n", to_string());
return _start >= r._start && _end <= r._end;
}
/**
* Determine if the range contains an address.
*
* @param a Address to compare with
* @return true if the address is in the range
*/
bool contains(const Addr& a) const
{
// check if the address is in the range and if there is either
// no interleaving, or with interleaving also if the selected
// bits from the address match the interleaving value
bool in_range = a >= _start && a <= _end;
if (!interleaved()) {
return in_range;
} else if (in_range) {
if (!hashed()) {
return bits(a, intlvHighBit, intlvHighBit - intlvBits + 1) ==
intlvMatch;
} else {
return (bits(a, intlvHighBit, intlvHighBit - intlvBits + 1) ^
bits(a, xorHighBit, xorHighBit - intlvBits + 1)) ==
intlvMatch;
}
}
return false;
}
/**
* Keep the operators away from SWIG.
*/
#ifndef SWIG
/**
* Less-than operator used to turn an STL map into a binary search
* tree of non-overlapping address ranges.
*
* @param r Range to compare with
* @return true if the start address is less than that of the other range
*/
bool operator<(const AddrRange& r) const
{
if (_start != r._start)
return _start < r._start;
else
// for now assume that the end is also the same, and that
// we are looking at the same interleaving bits
return intlvMatch < r.intlvMatch;
}
bool operator==(const AddrRange& r) const
{
if (_start != r._start) return false;
if (_end != r._end) return false;
if (intlvBits != r.intlvBits) return false;
if (intlvBits != 0) {
if (intlvHighBit != r.intlvHighBit) return false;
if (intlvMatch != r.intlvMatch) return false;
}
return true;
}
bool operator!=(const AddrRange& r) const
{
return !(*this == r);
}
#endif // SWIG
};
/**
* Convenience typedef for a collection of address ranges
*/
typedef std::list<AddrRange> AddrRangeList;
inline AddrRange
RangeEx(Addr start, Addr end)
{ return AddrRange(start, end - 1); }
inline AddrRange
RangeIn(Addr start, Addr end)
{ return AddrRange(start, end); }
inline AddrRange
RangeSize(Addr start, Addr size)
{ return AddrRange(start, start + size - 1); }
#endif // __BASE_ADDR_RANGE_HH__
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2000-2005 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Steve Reinhardt
*/
/*
* This code was originally written by Steve Reinhardt as part of
* the Wisconsin Wind Tunnel simulator. Relicensed as part of M5
* by permission.
*/
#ifndef NO_FAST_ALLOC
#ifdef __GNUC__
#pragma implementation
#endif
#include <assert.h>
#include "base/fast_alloc.hh"
void *FastAlloc::freeLists[Num_Buckets];
#ifdef FAST_ALLOC_STATS
unsigned FastAlloc::newCount[Num_Buckets];
unsigned FastAlloc::deleteCount[Num_Buckets];
unsigned FastAlloc::allocCount[Num_Buckets];
#endif
void *FastAlloc::moreStructs(int bucket)
{
assert(bucket > 0 && bucket < Num_Buckets);
int sz = bucket * Alloc_Quantum;
const int nstructs = Num_Structs_Per_New; // how many to allocate?
char *p = ::new char[nstructs * sz];
#ifdef FAST_ALLOC_STATS
++allocCount[bucket];
#endif
freeLists[bucket] = p;
for (int i = 0; i < (nstructs-2); ++i, p += sz)
*(void **)p = p + sz;
*(void **)p = 0;
return (p + sz);
}
#ifdef FAST_ALLOC_DEBUG
#include <typeinfo>
#include <iostream>
#include <iomanip>
#include <map>
#include <string>
using namespace std;
// count of in-use FastAlloc objects
int FastAlloc::numInUse;
// dummy head & tail object for doubly linked list of in-use FastAlloc
// objects
FastAlloc FastAlloc::inUseHead(&FastAlloc::inUseHead, &FastAlloc::inUseHead);
// special constructor for dummy head: make inUsePrev & inUseNext
// point to self
FastAlloc::FastAlloc(FastAlloc *prev, FastAlloc *next)
{
inUsePrev = prev;
inUseNext = next;
}
// constructor: marks as in use, add to in-use list
FastAlloc::FastAlloc()
{
// mark this object in use
inUse = true;
// update count
++numInUse;
// add to tail of list of in-use objects ("before" dummy head)
FastAlloc *myNext = &inUseHead;
FastAlloc *myPrev = inUseHead.inUsePrev;
inUsePrev = myPrev;
inUseNext = myNext;
myPrev->inUseNext = this;
myNext->inUsePrev = this;
}
// destructor: mark not in use, remove from in-use list
FastAlloc::~FastAlloc()
{
assert(inUse);
inUse = false;
--numInUse;
assert(numInUse >= 0);
// remove me from in-use list
inUsePrev->inUseNext = inUseNext;
inUseNext->inUsePrev = inUsePrev;
}
// summarize in-use list
void
FastAlloc::dump_summary()
{
map<string, int> typemap;
for (FastAlloc *p = inUseHead.inUseNext; p != &inUseHead; p = p->inUseNext)
{
++typemap[typeid(*p).name()];
}
map<string, int>::const_iterator mapiter;
cout << " count type\n"
<< " ----- ----\n";
for (mapiter = typemap.begin(); mapiter != typemap.end(); ++mapiter)
{
cout << setw(6) << mapiter->second << " " << mapiter->first << endl;
}
}
// show oldest n items on in-use list
void
FastAlloc::dump_oldest(int n)
{
// sanity check: don't want to crash the debugger if you forget to
// pass in a parameter
if (n < 0 || n > numInUse)
{
cout << "FastAlloc::dump_oldest: bad arg " << n
<< " (" << numInUse << " objects in use" << endl;
return;
}
for (FastAlloc *p = inUseHead.inUsePrev;
p != &inUseHead && n > 0;
p = p->inUsePrev, --n)
{
cout << p << " " << typeid(*p).name() << endl;
}
}
//
// C interfaces to FastAlloc::dump_summary() and FastAlloc::dump_oldest().
// gdb seems to have trouble with calling C++ functions directly.
//
fast_alloc_summary()
{
FastAlloc::dump_summary();
}
fast_alloc_oldest(int n)
{
FastAlloc::dump_oldest(n);
}
#endif
#endif // NO_FAST_ALLOC
<commit_msg>Make NO_FAST_ALLOC compile.<commit_after>/*
* Copyright (c) 2000-2005 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Steve Reinhardt
*/
/*
* This code was originally written by Steve Reinhardt as part of
* the Wisconsin Wind Tunnel simulator. Relicensed as part of M5
* by permission.
*/
#include <assert.h>
#include "base/fast_alloc.hh"
#if !NO_FAST_ALLOC
#ifdef __GNUC__
#pragma implementation
#endif
void *FastAlloc::freeLists[Num_Buckets];
#ifdef FAST_ALLOC_STATS
unsigned FastAlloc::newCount[Num_Buckets];
unsigned FastAlloc::deleteCount[Num_Buckets];
unsigned FastAlloc::allocCount[Num_Buckets];
#endif
void *FastAlloc::moreStructs(int bucket)
{
assert(bucket > 0 && bucket < Num_Buckets);
int sz = bucket * Alloc_Quantum;
const int nstructs = Num_Structs_Per_New; // how many to allocate?
char *p = ::new char[nstructs * sz];
#ifdef FAST_ALLOC_STATS
++allocCount[bucket];
#endif
freeLists[bucket] = p;
for (int i = 0; i < (nstructs-2); ++i, p += sz)
*(void **)p = p + sz;
*(void **)p = 0;
return (p + sz);
}
#ifdef FAST_ALLOC_DEBUG
#include <typeinfo>
#include <iostream>
#include <iomanip>
#include <map>
#include <string>
using namespace std;
// count of in-use FastAlloc objects
int FastAlloc::numInUse;
// dummy head & tail object for doubly linked list of in-use FastAlloc
// objects
FastAlloc FastAlloc::inUseHead(&FastAlloc::inUseHead, &FastAlloc::inUseHead);
// special constructor for dummy head: make inUsePrev & inUseNext
// point to self
FastAlloc::FastAlloc(FastAlloc *prev, FastAlloc *next)
{
inUsePrev = prev;
inUseNext = next;
}
// constructor: marks as in use, add to in-use list
FastAlloc::FastAlloc()
{
// mark this object in use
inUse = true;
// update count
++numInUse;
// add to tail of list of in-use objects ("before" dummy head)
FastAlloc *myNext = &inUseHead;
FastAlloc *myPrev = inUseHead.inUsePrev;
inUsePrev = myPrev;
inUseNext = myNext;
myPrev->inUseNext = this;
myNext->inUsePrev = this;
}
// destructor: mark not in use, remove from in-use list
FastAlloc::~FastAlloc()
{
assert(inUse);
inUse = false;
--numInUse;
assert(numInUse >= 0);
// remove me from in-use list
inUsePrev->inUseNext = inUseNext;
inUseNext->inUsePrev = inUsePrev;
}
// summarize in-use list
void
FastAlloc::dump_summary()
{
map<string, int> typemap;
for (FastAlloc *p = inUseHead.inUseNext; p != &inUseHead; p = p->inUseNext)
{
++typemap[typeid(*p).name()];
}
map<string, int>::const_iterator mapiter;
cout << " count type\n"
<< " ----- ----\n";
for (mapiter = typemap.begin(); mapiter != typemap.end(); ++mapiter)
{
cout << setw(6) << mapiter->second << " " << mapiter->first << endl;
}
}
// show oldest n items on in-use list
void
FastAlloc::dump_oldest(int n)
{
// sanity check: don't want to crash the debugger if you forget to
// pass in a parameter
if (n < 0 || n > numInUse)
{
cout << "FastAlloc::dump_oldest: bad arg " << n
<< " (" << numInUse << " objects in use" << endl;
return;
}
for (FastAlloc *p = inUseHead.inUsePrev;
p != &inUseHead && n > 0;
p = p->inUsePrev, --n)
{
cout << p << " " << typeid(*p).name() << endl;
}
}
//
// C interfaces to FastAlloc::dump_summary() and FastAlloc::dump_oldest().
// gdb seems to have trouble with calling C++ functions directly.
//
fast_alloc_summary()
{
FastAlloc::dump_summary();
}
fast_alloc_oldest(int n)
{
FastAlloc::dump_oldest(n);
}
#endif
#endif // NO_FAST_ALLOC
<|endoftext|>
|
<commit_before>/*
* Copyright 2016 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
enum class repair_checksum : uint8_t {
legacy = 0,
streamed = 1,
};
class partition_checksum {
std::array<uint8_t, 32> digest();
};
class repair_hash {
uint64_t hash;
};
enum class bound_weight : int8_t {
before_all_prefixed = -1,
equal = 0,
after_all_prefixed = 1,
};
enum class partition_region : uint8_t {
partition_start,
static_row,
clustered,
partition_end,
};
class position_in_partition {
partition_region get_type();
bound_weight get_bound_weight();
std::optional<clustering_key_prefix> get_clustering_key_prefix();
};
struct partition_key_and_mutation_fragments {
partition_key get_key();
std::list<frozen_mutation_fragment> get_mutation_fragments();
};
class repair_sync_boundary {
dht::decorated_key pk;
position_in_partition position;
};
struct get_sync_boundary_response {
std::optional<repair_sync_boundary> boundary;
repair_hash row_buf_combined_csum;
uint64_t row_buf_size;
uint64_t new_rows_size;
uint64_t new_rows_nr;
};
<commit_msg>idl: Add row_level_diff_detect_algorithm<commit_after>/*
* Copyright 2016 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
enum class repair_checksum : uint8_t {
legacy = 0,
streamed = 1,
};
class partition_checksum {
std::array<uint8_t, 32> digest();
};
class repair_hash {
uint64_t hash;
};
enum class bound_weight : int8_t {
before_all_prefixed = -1,
equal = 0,
after_all_prefixed = 1,
};
enum class partition_region : uint8_t {
partition_start,
static_row,
clustered,
partition_end,
};
class position_in_partition {
partition_region get_type();
bound_weight get_bound_weight();
std::optional<clustering_key_prefix> get_clustering_key_prefix();
};
struct partition_key_and_mutation_fragments {
partition_key get_key();
std::list<frozen_mutation_fragment> get_mutation_fragments();
};
class repair_sync_boundary {
dht::decorated_key pk;
position_in_partition position;
};
struct get_sync_boundary_response {
std::optional<repair_sync_boundary> boundary;
repair_hash row_buf_combined_csum;
uint64_t row_buf_size;
uint64_t new_rows_size;
uint64_t new_rows_nr;
};
enum class row_level_diff_detect_algorithm : uint8_t {
send_full_set,
};
<|endoftext|>
|
<commit_before>#include "ofxLineSegmentObject.h"
ofxLineSegmentObject::ofxLineSegmentObject(int iNumVerts)
{
lineWidth = 1.0;
for(int i=0; i < iNumVerts; i++){
addVertex(0,0,0);
}
}
ofxLineSegmentObject::~ofxLineSegmentObject(){}
void ofxLineSegmentObject::render()
{
glLineWidth(lineWidth);
glBegin(GL_LINE_STRIP);
for(int i=0; i < vertices.size(); i++){
glVertex3f(vertices[i].x, vertices[i].y, vertices[i].z);
}
glEnd();
}
void ofxLineSegmentObject::setLineWidth(float iWidth)
{
lineWidth = iWidth;
}
void ofxLineSegmentObject::setVertexPos(int iVertNum, float iX, float iY, float iZ)
{
if(ofInRange(iVertNum, 0, vertices.size()-1)){
vertices[iVertNum].set(iX, iY, iZ);
}
}
void ofxLineSegmentObject::addVertex(float iX, float iY, float iZ)
{
vertices.push_back(ofVec3f(iX, iY, iZ));
}<commit_msg>ofxLineSegment render type<commit_after>#include "ofxLineSegmentObject.h"
ofxLineSegmentObject::ofxLineSegmentObject(int iNumVerts)
{
lineWidth = 1.0;
for(int i=0; i < iNumVerts; i++){
addVertex(0,0,0);
}
}
ofxLineSegmentObject::~ofxLineSegmentObject(){}
void ofxLineSegmentObject::render()
{
glLineWidth(lineWidth);
glBegin(GL_LINES);
for(int i=0; i < vertices.size(); i++){
glVertex3f(vertices[i].x, vertices[i].y, vertices[i].z);
}
glEnd();
}
void ofxLineSegmentObject::setLineWidth(float iWidth)
{
lineWidth = iWidth;
}
void ofxLineSegmentObject::setVertexPos(int iVertNum, float iX, float iY, float iZ)
{
if(ofInRange(iVertNum, 0, vertices.size()-1)){
vertices[iVertNum].set(iX, iY, iZ);
}
}
void ofxLineSegmentObject::addVertex(float iX, float iY, float iZ)
{
vertices.push_back(ofVec3f(iX, iY, iZ));
}<|endoftext|>
|
<commit_before>#include <iostream>
#include <sstream>
#include <string>
#include "pegmatite.hh"
// This is very bad style, but it's okay for a short example...
using namespace std;
using namespace pegmatite;
/**
* The AST namespace contains the abstract syntax tree for this grammar.
*/
namespace AST
{
/**
* The base class for expressions in our language.
*/
class Expression : public ASTContainer
{
public:
/**
* Evaluate this expression. Returns a `double` representing the result of
* the evaluation.
*/
virtual double eval() const = 0;
/**
* Print the node, at the specified indent depth.
*/
virtual void print(int depth = 0) const = 0;
PEGMATITE_RTTI(Expression, ASTContainer);
};
/**
* AST node representing a number.
*/
class Number : public Expression
{
public:
/**
* Construct the numerical value from the text in the input range.
*/
virtual void construct(const pegmatite::InputRange &r, pegmatite::ASTStack &st)
{
stringstream stream;
for (char c : r)
{
stream << c;
}
stream >> value;
}
virtual double eval() const
{
return value;
}
virtual void print(int depth) const
{
cout << string(depth, '\t') << value << endl;
}
private:
double value;
};
/**
* Superclass for all of the binary expressions. Contains pointers to the left
* and right children. Subclasses encode the operation type.
*/
template<class func, char op>
class BinaryExpression : public Expression
{
protected:
/**
* The pointers to the left and right nodes. The `ASTPtr` class will
* automatically fill these in when this node is constructed, popping the
* two top values from the AST stack.
*/
ASTPtr<Expression> left, right;
public:
double eval() const override
{
func f;
return f(left->eval(), right->eval());
}
void print(int depth) const override
{
cout << string(depth, '\t') << op << endl;
left->print(depth+1);
right->print(depth+1);
}
};
}
namespace Parser
{
/**
* The (singleton) calculator grammar.
*/
struct CalculatorGrammar
{
/**
* Only spaces are recognised as whitespace in this toy example.
*/
Rule ws = " \t\n"_E;
/**
* Digits are things in the range 0-9.
*/
Rule digits = "[0-9]+"_R;
/**
* Numbers are one or more digits, optionally followed by a decimal point,
* and one or more digits, optionally followed by an exponent (which may
* also be negative.
*/
Rule num = digits >> -('.'_E >> digits >> -("eE"_S >> -("+-"_S) >> digits));
/**
* Values are either numbers or expressions in brackets (highest precedence).
*/
Rule val = num | '(' >> expr >> ')';
/**
* Multiply operations are values or multiply, or divide operations,
* followed by a multiply symbol, followed by a values, or multiply or
* divide operations. The sides can never be add or subtract operations,
* because they have lower precedence and so can only be parents of
* multiply or divide operations (or children via parenthetical
* expressions), not direct children.
*/
Rule mul_op = mul >> '*' >> mul;
/**
* Divide operations follow the same syntax as multiply.
*/
Rule div_op = mul >> '/' >> mul;
/**
* Multiply-precedence operations are either multiply or divide operations,
* or simple values (numbers of parenthetical expressions).
*/
Rule mul = mul_op | div_op | val;
/**
* Add operations can have any expression on the left (including other add
* expressions), but only higher-precedence operations on the right.
*/
Rule add_op = expr >> '+' >> expr;
/**
* Subtract operations follow the same structure as add.
*/
Rule sub_op = expr >> '-' >> expr;
/**
* Expressions can be any of the other types.
*/
Rule expr = add_op | sub_op | mul;
/**
* Returns a singleton instance of this grammar.
*/
static const CalculatorGrammar& get()
{
static CalculatorGrammar g;
return g;
}
private:
/**
* Private constructor. This class is immutable, and so only the `get()`
* method should be used to return the singleton instance.
*/
CalculatorGrammar() {};
};
/**
* CalculatorParser, constructs an AST from an input string.
*/
class CalculatorParser : public ASTParserDelegate
{
BindAST<AST::Number> num = CalculatorGrammar::get().num;
BindAST<AST::BinaryExpression<std::plus<double>,'+'>> add = CalculatorGrammar::get().add_op;
BindAST<AST::BinaryExpression<std::minus<double>,'-'>> sub = CalculatorGrammar::get().sub_op;
BindAST<AST::BinaryExpression<std::multiplies<double>,'*'>> mul = CalculatorGrammar::get().mul_op;
BindAST<AST::BinaryExpression<std::divides<double>,'/'>> div = CalculatorGrammar::get().div_op;
public:
const CalculatorGrammar &g = CalculatorGrammar::get();
};
}
int main()
{
Parser::CalculatorParser p;
for (;;)
{
string s;
cout << "enter a math expression (+ - * /, floats, parentheses) or enter to exit:\n";
getline(cin, s);
if (s.empty()) break;
//convert the string to input
StringInput i(std::move(s));
//parse
ErrorReporter er = [](const InputRange &ir, const std::string &s)
{
cout << "line " << ir.start.line << ", col " << ir.finish.col << ": " << s;
};
unique_ptr<AST::Expression> root = 0;
p.parse(i, p.g.expr, p.g.ws, er, root);
//on success
if (root)
{
double v = root->eval();
cout << "success\n";
cout << "result = " << v << endl;
cout << "parse tree:\n";
root->print(0);
}
//next input
cout << endl;
}
return 0;
}
<commit_msg>We’re `using namespace std`, so delete a load of `std::`<commit_after>#include <iostream>
#include <sstream>
#include <string>
#include "pegmatite.hh"
// This is very bad style, but it's okay for a short example...
using namespace std;
using namespace pegmatite;
/**
* The AST namespace contains the abstract syntax tree for this grammar.
*/
namespace AST
{
/**
* The base class for expressions in our language.
*/
class Expression : public ASTContainer
{
public:
/**
* Evaluate this expression. Returns a `double` representing the result of
* the evaluation.
*/
virtual double eval() const = 0;
/**
* Print the node, at the specified indent depth.
*/
virtual void print(int depth = 0) const = 0;
PEGMATITE_RTTI(Expression, ASTContainer);
};
/**
* AST node representing a number.
*/
class Number : public Expression
{
public:
/**
* Construct the numerical value from the text in the input range.
*/
virtual void construct(const pegmatite::InputRange &r, pegmatite::ASTStack &st)
{
stringstream stream;
for (char c : r)
{
stream << c;
}
stream >> value;
}
virtual double eval() const
{
return value;
}
virtual void print(int depth) const
{
cout << string(depth, '\t') << value << endl;
}
private:
double value;
};
/**
* Superclass for all of the binary expressions. Contains pointers to the left
* and right children. Subclasses encode the operation type.
*/
template<class func, char op>
class BinaryExpression : public Expression
{
protected:
/**
* The pointers to the left and right nodes. The `ASTPtr` class will
* automatically fill these in when this node is constructed, popping the
* two top values from the AST stack.
*/
ASTPtr<Expression> left, right;
public:
double eval() const override
{
func f;
return f(left->eval(), right->eval());
}
void print(int depth) const override
{
cout << string(depth, '\t') << op << endl;
left->print(depth+1);
right->print(depth+1);
}
};
}
namespace Parser
{
/**
* The (singleton) calculator grammar.
*/
struct CalculatorGrammar
{
/**
* Only spaces are recognised as whitespace in this toy example.
*/
Rule ws = " \t\n"_E;
/**
* Digits are things in the range 0-9.
*/
Rule digits = "[0-9]+"_R;
/**
* Numbers are one or more digits, optionally followed by a decimal point,
* and one or more digits, optionally followed by an exponent (which may
* also be negative.
*/
Rule num = digits >> -('.'_E >> digits >> -("eE"_S >> -("+-"_S) >> digits));
/**
* Values are either numbers or expressions in brackets (highest precedence).
*/
Rule val = num | '(' >> expr >> ')';
/**
* Multiply operations are values or multiply, or divide operations,
* followed by a multiply symbol, followed by a values, or multiply or
* divide operations. The sides can never be add or subtract operations,
* because they have lower precedence and so can only be parents of
* multiply or divide operations (or children via parenthetical
* expressions), not direct children.
*/
Rule mul_op = mul >> '*' >> mul;
/**
* Divide operations follow the same syntax as multiply.
*/
Rule div_op = mul >> '/' >> mul;
/**
* Multiply-precedence operations are either multiply or divide operations,
* or simple values (numbers of parenthetical expressions).
*/
Rule mul = mul_op | div_op | val;
/**
* Add operations can have any expression on the left (including other add
* expressions), but only higher-precedence operations on the right.
*/
Rule add_op = expr >> '+' >> expr;
/**
* Subtract operations follow the same structure as add.
*/
Rule sub_op = expr >> '-' >> expr;
/**
* Expressions can be any of the other types.
*/
Rule expr = add_op | sub_op | mul;
/**
* Returns a singleton instance of this grammar.
*/
static const CalculatorGrammar& get()
{
static CalculatorGrammar g;
return g;
}
private:
/**
* Private constructor. This class is immutable, and so only the `get()`
* method should be used to return the singleton instance.
*/
CalculatorGrammar() {};
};
/**
* CalculatorParser, constructs an AST from an input string.
*/
class CalculatorParser : public ASTParserDelegate
{
BindAST<AST::Number> num = CalculatorGrammar::get().num;
BindAST<AST::BinaryExpression<plus<double>,'+'>> add = CalculatorGrammar::get().add_op;
BindAST<AST::BinaryExpression<minus<double>,'-'>> sub = CalculatorGrammar::get().sub_op;
BindAST<AST::BinaryExpression<multiplies<double>,'*'>> mul = CalculatorGrammar::get().mul_op;
BindAST<AST::BinaryExpression<divides<double>,'/'>> div = CalculatorGrammar::get().div_op;
public:
const CalculatorGrammar &g = CalculatorGrammar::get();
};
}
int main()
{
Parser::CalculatorParser p;
for (;;)
{
string s;
cout << "enter a math expression (+ - * /, floats, parentheses) or enter to exit:\n";
getline(cin, s);
if (s.empty()) break;
//convert the string to input
StringInput i(move(s));
//parse
ErrorReporter er = [](const InputRange &ir, const string &s)
{
cout << "line " << ir.start.line << ", col " << ir.finish.col << ": " << s;
};
unique_ptr<AST::Expression> root = 0;
p.parse(i, p.g.expr, p.g.ws, er, root);
//on success
if (root)
{
double v = root->eval();
cout << "success\n";
cout << "result = " << v << endl;
cout << "parse tree:\n";
root->print(0);
}
//next input
cout << endl;
}
return 0;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2014-2022 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/
#ifndef TAO_PEGTL_DEMANGLE_HPP
#define TAO_PEGTL_DEMANGLE_HPP
#include <ciso646>
#include <string_view>
#include "config.hpp"
// ensure a consistent interface
namespace TAO_PEGTL_NAMESPACE
{
#if !defined( __clang__ ) && defined( __GNUC__ ) && ( __GNUC__ == 7 )
template< typename T >
[[nodiscard]] std::string_view demangle() noexcept;
#else
template< typename T >
[[nodiscard]] constexpr std::string_view demangle() noexcept;
#endif
} // namespace TAO_PEGTL_NAMESPACE
#if defined( __clang__ )
#if defined( _LIBCPP_VERSION )
template< typename T >
[[nodiscard]] constexpr std::string_view TAO_PEGTL_NAMESPACE::demangle() noexcept
{
constexpr std::string_view sv = __PRETTY_FUNCTION__;
constexpr auto begin = sv.find( '=' );
static_assert( begin != std::string_view::npos );
return sv.substr( begin + 2, sv.size() - begin - 3 );
}
#else
namespace TAO_PEGTL_NAMESPACE::internal
{
// When using libstdc++ with clang, std::string_view::find is not constexpr :(
template< char C >
constexpr const char* string_view_find( const char* p, std::size_t n ) noexcept
{
while( n ) {
if( *p == C ) {
return p;
}
++p;
--n;
}
return nullptr;
}
} // namespace TAO_PEGTL_NAMESPACE::internal
template< typename T >
[[nodiscard]] constexpr std::string_view TAO_PEGTL_NAMESPACE::demangle() noexcept
{
constexpr std::string_view sv = __PRETTY_FUNCTION__;
constexpr auto begin = internal::string_view_find< '=' >( sv.data(), sv.size() );
static_assert( begin != nullptr );
return { begin + 2, sv.data() + sv.size() - begin - 3 };
}
#endif
#elif defined( __GNUC__ )
#if( __GNUC__ == 7 )
// GCC 7 wrongly sometimes disallows __PRETTY_FUNCTION__ in constexpr functions,
// therefore we drop the 'constexpr' and hope for the best.
template< typename T >
[[nodiscard]] std::string_view TAO_PEGTL_NAMESPACE::demangle() noexcept
{
const std::string_view sv = __PRETTY_FUNCTION__;
const auto begin = sv.find( '=' );
const auto tmp = sv.substr( begin + 2 );
const auto end = tmp.rfind( ';' );
return tmp.substr( 0, end );
}
#elif( __GNUC__ == 9 ) && ( __GNUC_MINOR__ < 3 )
#if !defined( __cpp_rtti )
#error "RTTI support required for GCC 9.1/9.2"
#else
#include <typeinfo>
// GCC 9.1 and 9.2 have a bug that leads to truncated __PRETTY_FUNCTION__ names,
// see https://gcc.gnu.org/bugzilla/show_bug.cgi?id=91155
template< typename T >
[[nodiscard]] constexpr std::string_view TAO_PEGTL_NAMESPACE::demangle() noexcept
{
// fallback: requires RTTI, no demangling
return typeid( T ).name();
}
#endif
#else
namespace TAO_PEGTL_NAMESPACE::special
{
template< typename T >
[[nodiscard]] constexpr std::string_view demangle() noexcept
{
constexpr std::string_view sv = __PRETTY_FUNCTION__;
constexpr auto begin = sv.find( '=' );
static_assert( begin != std::string_view::npos );
constexpr auto tmp = sv.substr( begin + 2 );
constexpr auto end = tmp.rfind( ';' );
static_assert( end != std::string_view::npos );
return tmp.substr( 0, end );
}
} // namespace TAO_PEGTL_NAMESPACE::special
template< typename T >
[[nodiscard]] constexpr std::string_view TAO_PEGTL_NAMESPACE::demangle() noexcept
{
return TAO_PEGTL_NAMESPACE::special::demangle< T >();
}
#endif
#elif defined( _MSC_VER )
#if( _MSC_VER < 1920 )
template< typename T >
[[nodiscard]] constexpr std::string_view TAO_PEGTL_NAMESPACE::demangle() noexcept
{
const std::string_view sv = __FUNCSIG__;
const auto begin = sv.find( "demangle<" );
const auto tmp = sv.substr( begin + 9 );
const auto end = tmp.rfind( '>' );
return tmp.substr( 0, end );
}
#else
template< typename T >
[[nodiscard]] constexpr std::string_view TAO_PEGTL_NAMESPACE::demangle() noexcept
{
// we can not add static_assert for additional safety,
// see issues #296, #301 and #308
constexpr std::string_view sv = __FUNCSIG__;
constexpr auto begin = sv.find( "demangle<" );
constexpr auto tmp = sv.substr( begin + 9 );
constexpr auto end = tmp.rfind( '>' );
return tmp.substr( 0, end );
}
#endif
#else
#if !defined( __cpp_rtti )
#error "RTTI support required for unknown compilers"
#else
#include <typeinfo>
template< typename T >
[[nodiscard]] constexpr std::string_view TAO_PEGTL_NAMESPACE::demangle() noexcept
{
// fallback: requires RTTI, no demangling
return typeid( T ).name();
}
#endif
#endif
#endif
<commit_msg>Simplify<commit_after>// Copyright (c) 2014-2022 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/
#ifndef TAO_PEGTL_DEMANGLE_HPP
#define TAO_PEGTL_DEMANGLE_HPP
#include <ciso646>
#include <string_view>
#include "config.hpp"
// ensure a consistent interface
namespace TAO_PEGTL_NAMESPACE
{
#if !defined( __clang__ ) && defined( __GNUC__ ) && ( __GNUC__ == 7 )
template< typename T >
[[nodiscard]] std::string_view demangle() noexcept;
#else
template< typename T >
[[nodiscard]] constexpr std::string_view demangle() noexcept;
#endif
} // namespace TAO_PEGTL_NAMESPACE
#if defined( __clang__ )
#if defined( _LIBCPP_VERSION )
template< typename T >
[[nodiscard]] constexpr std::string_view TAO_PEGTL_NAMESPACE::demangle() noexcept
{
constexpr std::string_view sv = __PRETTY_FUNCTION__;
constexpr auto begin = sv.find( '=' );
static_assert( begin != std::string_view::npos );
return sv.substr( begin + 2, sv.size() - begin - 3 );
}
#else
namespace TAO_PEGTL_NAMESPACE::internal
{
// When using libstdc++ with clang, std::string_view::find is not constexpr :(
template< char C >
constexpr const char* string_view_find( const char* p, std::size_t n ) noexcept
{
while( n ) {
if( *p == C ) {
return p;
}
++p;
--n;
}
return nullptr;
}
} // namespace TAO_PEGTL_NAMESPACE::internal
template< typename T >
[[nodiscard]] constexpr std::string_view TAO_PEGTL_NAMESPACE::demangle() noexcept
{
constexpr std::string_view sv = __PRETTY_FUNCTION__;
constexpr auto begin = internal::string_view_find< '=' >( sv.data(), sv.size() );
static_assert( begin != nullptr );
return { begin + 2, sv.data() + sv.size() - begin - 3 };
}
#endif
#elif defined( __GNUC__ )
#if( __GNUC__ == 7 )
// GCC 7 wrongly sometimes disallows __PRETTY_FUNCTION__ in constexpr functions,
// therefore we drop the 'constexpr' and hope for the best.
template< typename T >
[[nodiscard]] std::string_view TAO_PEGTL_NAMESPACE::demangle() noexcept
{
const std::string_view sv = __PRETTY_FUNCTION__;
const auto begin = sv.find( '=' );
const auto tmp = sv.substr( begin + 2 );
const auto end = tmp.rfind( ';' );
return tmp.substr( 0, end );
}
#elif( __GNUC__ == 9 ) && ( __GNUC_MINOR__ < 3 )
#if !defined( __cpp_rtti )
#error "RTTI support required for GCC 9.1/9.2"
#else
#include <typeinfo>
// GCC 9.1 and 9.2 have a bug that leads to truncated __PRETTY_FUNCTION__ names,
// see https://gcc.gnu.org/bugzilla/show_bug.cgi?id=91155
template< typename T >
[[nodiscard]] constexpr std::string_view TAO_PEGTL_NAMESPACE::demangle() noexcept
{
// fallback: requires RTTI, no demangling
return typeid( T ).name();
}
#endif
#else
namespace TAO_PEGTL_NAMESPACE::special
{
template< typename T >
[[nodiscard]] constexpr std::string_view demangle() noexcept
{
constexpr std::string_view sv = __PRETTY_FUNCTION__;
constexpr auto begin = sv.find( '=' );
static_assert( begin != std::string_view::npos );
constexpr auto tmp = sv.substr( begin + 2 );
constexpr auto end = tmp.rfind( ';' );
static_assert( end != std::string_view::npos );
return tmp.substr( 0, end );
}
} // namespace TAO_PEGTL_NAMESPACE::special
template< typename T >
[[nodiscard]] constexpr std::string_view TAO_PEGTL_NAMESPACE::demangle() noexcept
{
return special::demangle< T >();
}
#endif
#elif defined( _MSC_VER )
#if( _MSC_VER < 1920 )
template< typename T >
[[nodiscard]] constexpr std::string_view TAO_PEGTL_NAMESPACE::demangle() noexcept
{
const std::string_view sv = __FUNCSIG__;
const auto begin = sv.find( "demangle<" );
const auto tmp = sv.substr( begin + 9 );
const auto end = tmp.rfind( '>' );
return tmp.substr( 0, end );
}
#else
template< typename T >
[[nodiscard]] constexpr std::string_view TAO_PEGTL_NAMESPACE::demangle() noexcept
{
// we can not add static_assert for additional safety,
// see issues #296, #301 and #308
constexpr std::string_view sv = __FUNCSIG__;
constexpr auto begin = sv.find( "demangle<" );
constexpr auto tmp = sv.substr( begin + 9 );
constexpr auto end = tmp.rfind( '>' );
return tmp.substr( 0, end );
}
#endif
#else
#if !defined( __cpp_rtti )
#error "RTTI support required for unknown compilers"
#else
#include <typeinfo>
template< typename T >
[[nodiscard]] constexpr std::string_view TAO_PEGTL_NAMESPACE::demangle() noexcept
{
// fallback: requires RTTI, no demangling
return typeid( T ).name();
}
#endif
#endif
#endif
<|endoftext|>
|
<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015 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 <os>
#include <net/inet4>
#include <net/dhcp/dh4client.hpp>
#include <math.h> // rand()
#include <sstream>
// An IP-stack object
std::unique_ptr<net::Inet4<VirtioNet> > inet;
using namespace std::chrono;
std::string HTML_RESPONSE() {
int color = rand();
std::stringstream stream;
/* HTML Fonts */
std::string ubuntu_medium = "font-family: \'Ubuntu\', sans-serif; font-weight: 500; ";
std::string ubuntu_normal = "font-family: \'Ubuntu\', sans-serif; font-weight: 400; ";
std::string ubuntu_light = "font-family: \'Ubuntu\', sans-serif; font-weight: 300; ";
/* HTML */
stream << "<html><head>"
<< "<link href='https://fonts.googleapis.com/css?family=Ubuntu:500,300' rel='stylesheet' type='text/css'>"
<< "</head><body>"
<< "<h1 style= \"color: " << "#" << std::hex << (color >> 8) << "\">"
<< "<span style=\""+ubuntu_medium+"\">Include</span><span style=\""+ubuntu_light+"\">OS</span> </h1>"
<< "<h2>Now speaks TCP!</h2>"
// .... generate more dynamic content
<< "<p> ...and can improvise http. With limitations of course, but it's been easier than expected so far </p>"
<< "<footer><hr /> © 2015, Oslo and Akershus University College of Applied Sciences </footer>"
<< "</body></html>\n";
std::string html = stream.str();
std::string header="HTTP/1.1 200 OK \n " \
"Date: Mon, 01 Jan 1970 00:00:01 GMT \n" \
"Server: IncludeOS prototype 4.0 \n" \
"Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT \n" \
"Content-Type: text/html; charset=UTF-8 \n" \
"Content-Length: "+std::to_string(html.size())+"\n" \
"Accept-Ranges: bytes\n" \
"Connection: close\n\n";
return header + html;
}
void Service::start() {
// Assign a driver (VirtioNet) to a network interface (eth0)
// @note: We could determine the appropirate driver dynamically, but then we'd
// have to include all the drivers into the image, which we want to avoid.
hw::Nic<VirtioNet>& eth0 = hw::Dev::eth<0,VirtioNet>();
// Bring up a network stack, attached to the nic
// @note : No parameters after 'nic' means we'll use DHCP for IP config.
inet = std::make_unique<net::Inet4<VirtioNet> >(eth0);
// Static IP configuration, until we (possibly) get DHCP
// @note : Mostly to get a robust demo service that it works with and without DHCP
inet->network_config( { 10,0,0,42 }, // IP
{ 255,255,255,0 }, // Netmask
{ 10,0,0,1 }, // Gateway
{ 8,8,8,8 } ); // DNS
srand(OS::cycles_since_boot());
// Set up a TCP server on port 80
auto& server = inet->tcp().bind(80);
hw::PIT::instance().onRepeatedTimeout(30s, []{
printf("<Service> TCP STATUS:\n%s \n", inet->tcp().status().c_str());
});
// Add a TCP connection handler - here a hardcoded HTTP-service
server.onAccept([](auto conn) -> bool {
printf("<Service> @onAccept - Connection attempt from: %s \n",
conn->to_string().c_str());
return true; // allow all connections
}).onConnect([](auto conn) {
printf("<Service> @onConnect - Connection successfully established.\n");
// read async with a buffer size of 1024 bytes
// define what to do when data is read
conn->read(1024, [conn](net::TCP::buffer_t buf, size_t n) {
// create string from buffer
std::string data { (char*)buf.get(), n };
printf("<Service> @read:\n%s\n", data.c_str());
// create response
std::string response = HTML_RESPONSE();
// write the data from the string with the strings size
conn->write(response.data(), response.size(), [](size_t n) {
printf("<Service> @write: %u bytes written\n", n);
});
});
}).onDisconnect([](auto, auto reason) {
printf("<Service> @onDisconnect - Reason: %s \n", reason.to_string().c_str());
});
printf("*** TEST SERVICE STARTED *** \n");
}
<commit_msg>example: made the demo a tiny bit smarter<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015 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 <os>
#include <net/inet4>
#include <net/dhcp/dh4client.hpp>
#include <math.h> // rand()
#include <sstream>
// An IP-stack object
std::unique_ptr<net::Inet4<VirtioNet> > inet;
using namespace std::chrono;
std::string HTML_RESPONSE() {
int color = rand();
std::stringstream stream;
/* HTML Fonts */
std::string ubuntu_medium = "font-family: \'Ubuntu\', sans-serif; font-weight: 500; ";
std::string ubuntu_normal = "font-family: \'Ubuntu\', sans-serif; font-weight: 400; ";
std::string ubuntu_light = "font-family: \'Ubuntu\', sans-serif; font-weight: 300; ";
/* HTML */
stream << "<html><head>"
<< "<link href='https://fonts.googleapis.com/css?family=Ubuntu:500,300' rel='stylesheet' type='text/css'>"
<< "</head><body>"
<< "<h1 style= \"color: " << "#" << std::hex << (color >> 8) << "\">"
<< "<span style=\""+ubuntu_medium+"\">Include</span><span style=\""+ubuntu_light+"\">OS</span> </h1>"
<< "<h2>Now speaks TCP!</h2>"
// .... generate more dynamic content
<< "<p> ...and can improvise http. With limitations of course, but it's been easier than expected so far </p>"
<< "<footer><hr /> © 2015, Oslo and Akershus University College of Applied Sciences </footer>"
<< "</body></html>\n";
std::string html = stream.str();
std::string header="HTTP/1.1 200 OK \n " \
"Date: Mon, 01 Jan 1970 00:00:01 GMT \n" \
"Server: IncludeOS prototype 4.0 \n" \
"Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT \n" \
"Content-Type: text/html; charset=UTF-8 \n" \
"Content-Length: "+std::to_string(html.size())+"\n" \
"Accept-Ranges: bytes\n" \
"Connection: close\n\n";
return header + html;
}
const std::string NOT_FOUND = "HTTP/1.1 404 Not Found \n Connection: close\n\n";
void Service::start() {
// Assign a driver (VirtioNet) to a network interface (eth0)
// @note: We could determine the appropirate driver dynamically, but then we'd
// have to include all the drivers into the image, which we want to avoid.
hw::Nic<VirtioNet>& eth0 = hw::Dev::eth<0,VirtioNet>();
// Bring up a network stack, attached to the nic
// @note : No parameters after 'nic' means we'll use DHCP for IP config.
inet = std::make_unique<net::Inet4<VirtioNet> >(eth0);
// Static IP configuration, until we (possibly) get DHCP
// @note : Mostly to get a robust demo service that it works with and without DHCP
inet->network_config( { 10,0,0,42 }, // IP
{ 255,255,255,0 }, // Netmask
{ 10,0,0,1 }, // Gateway
{ 8,8,8,8 } ); // DNS
srand(OS::cycles_since_boot());
// Set up a TCP server on port 80
auto& server = inet->tcp().bind(80);
hw::PIT::instance().onRepeatedTimeout(30s, []{
printf("<Service> TCP STATUS:\n%s \n", inet->tcp().status().c_str());
});
// Add a TCP connection handler - here a hardcoded HTTP-service
server.onAccept([](auto conn) -> bool {
printf("<Service> @onAccept - Connection attempt from: %s \n",
conn->to_string().c_str());
return true; // allow all connections
}).onConnect([](auto conn) {
printf("<Service> @onConnect - Connection successfully established.\n");
// read async with a buffer size of 1024 bytes
// define what to do when data is read
conn->read(1024, [conn](net::TCP::buffer_t buf, size_t n) {
// create string from buffer
std::string data { (char*)buf.get(), n };
printf("<Service> @read:\n%s\n", data.c_str());
if(data.find("GET / ") != std::string::npos) {
// create response
std::string response = HTML_RESPONSE();
// write the data from the string with the strings size
conn->write(response.data(), response.size(), [](size_t n) {
printf("<Service> @write: %u bytes written\n", n);
});
}
else {
conn->write(NOT_FOUND.data(), NOT_FOUND.size());
}
});
}).onDisconnect([](auto conn, auto reason) {
printf("<Service> @onDisconnect - Reason: %s \n", reason.to_string().c_str());
conn->close();
}).onPacketReceived([](auto, auto packet) {
printf("@Packet: %s\n", packet->to_string().c_str());
});
printf("*** TEST SERVICE STARTED *** \n");
}
<|endoftext|>
|
<commit_before>#ifndef ORIGEN_HPP_INCLUDED
#define ORIGEN_HPP_INCLUDED
#define ORIGEN_VERSION "0.11.0"
#ifndef debugger
#define debugger __asm__("int $3");
#endif
#include "origen/helpers.hpp"
#include "origen/site.hpp"
#include "origen/utils.hpp"
namespace Origen {
extern vector<Site> Sites;
Utils::Version version();
Site& site();
Site& site(int site);
extern bool invertFunctionalResults;
}
#endif
<commit_msg>Wrote new version in C++ code<commit_after>#ifndef ORIGEN_HPP_INCLUDED
#define ORIGEN_HPP_INCLUDED
#define ORIGEN_VERSION "0.12.0"
#ifndef debugger
#define debugger __asm__("int $3");
#endif
#include "origen/helpers.hpp"
#include "origen/site.hpp"
#include "origen/utils.hpp"
namespace Origen {
extern vector<Site> Sites;
Utils::Version version();
Site& site();
Site& site(int site);
extern bool invertFunctionalResults;
}
#endif
<|endoftext|>
|
<commit_before>// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "lexer.h"
#include "eval_env.h"
bool Lexer::Error(const string& message, string* err) {
// Compute line/column.
int line = 1;
const char* context = input_.str_;
for (const char* p = input_.str_; p < last_token_; ++p) {
if (*p == '\n') {
++line;
context = p + 1;
}
}
int col = last_token_ ? last_token_ - context : 0;
char buf[1024];
snprintf(buf, sizeof(buf), "%s:%d: ", filename_.AsString().c_str(), line);
*err = buf;
*err += message + "\n";
// Add some context to the message.
const int kTruncateColumn = 72;
if (col > 0 && col < kTruncateColumn) {
int len;
bool truncated = true;
for (len = 0; len < kTruncateColumn; ++len) {
if (context[len] == 0 || context[len] == '\n') {
truncated = false;
break;
}
}
*err += string(context, len);
if (truncated)
*err += "...";
*err += "\n";
*err += string(col, ' ');
*err += "^ near here\n";
}
return false;
}
Lexer::Lexer(const char* input) {
Start("input", input);
}
void Lexer::Start(StringPiece filename, StringPiece input) {
filename_ = filename;
input_ = input;
ofs_ = input_.str_;
last_token_ = NULL;
}
const char* Lexer::TokenName(Token t) {
switch (t) {
case ERROR: return "lexing error";
case BUILD: return "'build'";
case COLON: return "':'";
case DEFAULT: return "'default'";
case EQUALS: return "'='";
case IDENT: return "identifier";
case INCLUDE: return "'include'";
case INDENT: return "indent";
case NEWLINE: return "newline";
case PIPE2: return "'||'";
case PIPE: return "'|'";
case RULE: return "'rule'";
case SUBNINJA: return "'subninja'";
case TEOF: return "eof";
}
return NULL; // not reached
}
void Lexer::UnreadToken() {
ofs_ = last_token_;
}
Lexer::Token Lexer::ReadToken() {
const char* p = ofs_;
const char* q;
const char* start;
Lexer::Token token;
for (;;) {
start = p;
/*!re2c
re2c:define:YYCTYPE = "char";
re2c:define:YYCURSOR = p;
re2c:define:YYMARKER = q;
re2c:yyfill:enable = 0;
nul = "\000";
simple_varname = [a-zA-Z0-9_]+;
varname = [a-zA-Z0-9_.]+;
"#"[^\000\n]*"\n" { continue; }
[\n] { token = NEWLINE; break; }
[ ]+ { token = INDENT; break; }
"build" { token = BUILD; break; }
"rule" { token = RULE; break; }
"default" { token = DEFAULT; break; }
"=" { token = EQUALS; break; }
":" { token = COLON; break; }
"||" { token = PIPE2; break; }
"|" { token = PIPE; break; }
"include" { token = INCLUDE; break; }
"subninja" { token = SUBNINJA; break; }
varname { token = IDENT; break; }
nul { token = TEOF; break; }
[^] { token = ERROR; break; }
*/
}
last_token_ = start;
ofs_ = p;
if (token != NEWLINE && token != TEOF)
EatWhitespace();
return token;
}
bool Lexer::PeekToken(Token token) {
Token t = ReadToken();
if (t == token)
return true;
UnreadToken();
return false;
}
void Lexer::EatWhitespace() {
const char* p = ofs_;
for (;;) {
ofs_ = p;
/*!re2c
[ ]+ { continue; }
"$\n" { continue; }
nul { break; }
[^] { break; }
*/
}
}
bool Lexer::ReadIdent(string* out) {
const char* p = ofs_;
for (;;) {
const char* start = p;
/*!re2c
varname {
out->assign(start, p - start);
break;
}
[^] { return false; }
*/
}
ofs_ = p;
EatWhitespace();
return true;
}
bool Lexer::ReadEvalString(EvalString* eval, bool path, string* err) {
const char* p = ofs_;
const char* q;
const char* start;
for (;;) {
start = p;
/*!re2c
[^$ :\n|\000]+ {
eval->Add(EvalString::RAW, StringPiece(start, p - start));
continue;
}
[ :|\n] {
if (path) {
p = start;
break;
} else {
if (*start == '\n')
break;
eval->Add(EvalString::RAW, StringPiece(start, 1));
continue;
}
}
"$$" {
eval->Add(EvalString::RAW, StringPiece("$", 1));
continue;
}
"$ " {
eval->Add(EvalString::RAW, StringPiece(" ", 1));
continue;
}
"$\n"[ ]* {
continue;
}
"${"varname"}" {
eval->Add(EvalString::SPECIAL, StringPiece(start + 2, p - start - 3));
continue;
}
"$"simple_varname {
eval->Add(EvalString::SPECIAL, StringPiece(start + 1, p - start - 1));
continue;
}
"$". {
last_token_ = start;
return Error("bad $-escape (literal $ must be written as $$)", err);
}
nul {
last_token_ = start;
return Error("unexpected EOF", err);
}
[^] {
last_token_ = start;
return Error("lexing error", err);
}
*/
}
last_token_ = start;
ofs_ = p;
if (path)
EatWhitespace();
// Non-path strings end in newlines, so there's no whitespace to eat.
return true;
}
<commit_msg>build fix<commit_after>// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "lexer.h"
#include <stdio.h>
#include "eval_env.h"
bool Lexer::Error(const string& message, string* err) {
// Compute line/column.
int line = 1;
const char* context = input_.str_;
for (const char* p = input_.str_; p < last_token_; ++p) {
if (*p == '\n') {
++line;
context = p + 1;
}
}
int col = last_token_ ? last_token_ - context : 0;
char buf[1024];
snprintf(buf, sizeof(buf), "%s:%d: ", filename_.AsString().c_str(), line);
*err = buf;
*err += message + "\n";
// Add some context to the message.
const int kTruncateColumn = 72;
if (col > 0 && col < kTruncateColumn) {
int len;
bool truncated = true;
for (len = 0; len < kTruncateColumn; ++len) {
if (context[len] == 0 || context[len] == '\n') {
truncated = false;
break;
}
}
*err += string(context, len);
if (truncated)
*err += "...";
*err += "\n";
*err += string(col, ' ');
*err += "^ near here\n";
}
return false;
}
Lexer::Lexer(const char* input) {
Start("input", input);
}
void Lexer::Start(StringPiece filename, StringPiece input) {
filename_ = filename;
input_ = input;
ofs_ = input_.str_;
last_token_ = NULL;
}
const char* Lexer::TokenName(Token t) {
switch (t) {
case ERROR: return "lexing error";
case BUILD: return "'build'";
case COLON: return "':'";
case DEFAULT: return "'default'";
case EQUALS: return "'='";
case IDENT: return "identifier";
case INCLUDE: return "'include'";
case INDENT: return "indent";
case NEWLINE: return "newline";
case PIPE2: return "'||'";
case PIPE: return "'|'";
case RULE: return "'rule'";
case SUBNINJA: return "'subninja'";
case TEOF: return "eof";
}
return NULL; // not reached
}
void Lexer::UnreadToken() {
ofs_ = last_token_;
}
Lexer::Token Lexer::ReadToken() {
const char* p = ofs_;
const char* q;
const char* start;
Lexer::Token token;
for (;;) {
start = p;
/*!re2c
re2c:define:YYCTYPE = "char";
re2c:define:YYCURSOR = p;
re2c:define:YYMARKER = q;
re2c:yyfill:enable = 0;
nul = "\000";
simple_varname = [a-zA-Z0-9_]+;
varname = [a-zA-Z0-9_.]+;
"#"[^\000\n]*"\n" { continue; }
[\n] { token = NEWLINE; break; }
[ ]+ { token = INDENT; break; }
"build" { token = BUILD; break; }
"rule" { token = RULE; break; }
"default" { token = DEFAULT; break; }
"=" { token = EQUALS; break; }
":" { token = COLON; break; }
"||" { token = PIPE2; break; }
"|" { token = PIPE; break; }
"include" { token = INCLUDE; break; }
"subninja" { token = SUBNINJA; break; }
varname { token = IDENT; break; }
nul { token = TEOF; break; }
[^] { token = ERROR; break; }
*/
}
last_token_ = start;
ofs_ = p;
if (token != NEWLINE && token != TEOF)
EatWhitespace();
return token;
}
bool Lexer::PeekToken(Token token) {
Token t = ReadToken();
if (t == token)
return true;
UnreadToken();
return false;
}
void Lexer::EatWhitespace() {
const char* p = ofs_;
for (;;) {
ofs_ = p;
/*!re2c
[ ]+ { continue; }
"$\n" { continue; }
nul { break; }
[^] { break; }
*/
}
}
bool Lexer::ReadIdent(string* out) {
const char* p = ofs_;
for (;;) {
const char* start = p;
/*!re2c
varname {
out->assign(start, p - start);
break;
}
[^] { return false; }
*/
}
ofs_ = p;
EatWhitespace();
return true;
}
bool Lexer::ReadEvalString(EvalString* eval, bool path, string* err) {
const char* p = ofs_;
const char* q;
const char* start;
for (;;) {
start = p;
/*!re2c
[^$ :\n|\000]+ {
eval->Add(EvalString::RAW, StringPiece(start, p - start));
continue;
}
[ :|\n] {
if (path) {
p = start;
break;
} else {
if (*start == '\n')
break;
eval->Add(EvalString::RAW, StringPiece(start, 1));
continue;
}
}
"$$" {
eval->Add(EvalString::RAW, StringPiece("$", 1));
continue;
}
"$ " {
eval->Add(EvalString::RAW, StringPiece(" ", 1));
continue;
}
"$\n"[ ]* {
continue;
}
"${"varname"}" {
eval->Add(EvalString::SPECIAL, StringPiece(start + 2, p - start - 3));
continue;
}
"$"simple_varname {
eval->Add(EvalString::SPECIAL, StringPiece(start + 1, p - start - 1));
continue;
}
"$". {
last_token_ = start;
return Error("bad $-escape (literal $ must be written as $$)", err);
}
nul {
last_token_ = start;
return Error("unexpected EOF", err);
}
[^] {
last_token_ = start;
return Error("lexing error", err);
}
*/
}
last_token_ = start;
ofs_ = p;
if (path)
EatWhitespace();
// Non-path strings end in newlines, so there's no whitespace to eat.
return true;
}
<|endoftext|>
|
<commit_before>#ifndef V_SMC_CORE_PARTICLE_HPP
#define V_SMC_CORE_PARTICLE_HPP
#include <vector>
#include <cmath>
#include <cstddef>
#include <boost/function.hpp>
#include <boost/random/binomial_distribution.hpp>
#include <boost/random/uniform_01.hpp>
#include <Eigen/Dense>
#include <vSMC/internal/rng.hpp>
#include <vSMC/internal/version.hpp>
namespace vSMC {
/// Resample scheme
enum ResampleScheme {
MULTINOMIAL, RESIDUAL, STRATIFIED, SYSTEMATIC, RESIDUAL_STRATIFIED};
/// \brief Particle class
///
/// Particle class store the particle set and arrays of weights and log
/// weights. It provides access to particle values as well as weights. It
/// computes and manages resources for ESS, resampling, etc, tasks unique to
/// each iteration.
template <typename T>
class Particle
{
public :
typedef V_SMC_RNG_TYPE rng_type;
/// \brief Construct a Particle object with given number of particles
///
/// \param N The number of particles
/// \param seed The seed to the parallel RNG system
Particle (std::size_t N, rng_type::seed_type seed = V_SMC_RNG_SEED) :
size_(N), value_(N),
weight_(N), log_weight_(N), inc_weight_(N), replication_(N),
ess_(0), resampled_(false), zconst_(0), prng_(N)
{
rng_type rng(seed);
rng.step_size(size_);
for (std::size_t i = 0; i != size_; ++i) {
rng.advance_ctr(i);
prng_[i] = rng;
}
weight_.setConstant(1.0 / size_);
log_weight_.setConstant(0);
}
/// \brief Size of the particle set
///
/// \return The number of particles
std::size_t size () const
{
return size_;
}
/// \brief Read and write access to particle values
///
/// \return A reference to the particle values, type (T &)
///
/// \note The Particle class guarantee that during the life type of the
/// object, the reference returned by this member will no be a dangle
/// handler.
T &value ()
{
return value_;
}
/// \brief Read only access to particle values
///
/// \return A const reference to the particle values
const T &value () const
{
return value_;
}
/// \brief Read only access to the weights
///
/// \return A const pointer to the weights
///
/// \note The Particle class guarantee that during the life type of the
/// object, the pointer returned by this always valid and point to the
/// same address
const double *weight_ptr () const
{
return weight_.data();
}
/// \brief Read only access to the log weights
///
/// \return A const pointer to the log weights
const double *log_weight_ptr () const
{
return log_weight_.data();
}
const Eigen::VectorXd &weight () const
{
return weight_;
}
const Eigen::VectorXd &log_weight () const
{
return log_weight_;
}
/// \brief Set the log weights
///
/// \param new_weight New log weights
/// \param delta A multiplier appiled to new_weight
void set_log_weight (const double *new_weight, double delta = 1)
{
Eigen::Map<const Eigen::VectorXd> w(new_weight, size_);
log_weight_ = delta * w;
set_weight();
}
/// \brief Add to the log weights
///
/// \param inc_weight Incremental log weights
/// \param delta A multiplier applied to inc_weight
/// \param add_zconst Whether this incremental weights should contribute
/// the esitmates of normalizing constants
void add_log_weight (const double *inc_weight, double delta = 1,
bool add_zconst = true)
{
Eigen::Map<const Eigen::VectorXd> w(inc_weight, size_);
if (add_zconst) {
inc_weight_ = (delta * w).array().exp();
zconst_ += std::log(weight_.dot(inc_weight_));
}
log_weight_ += delta * w;
set_weight();
}
/// \brief The ESS (Effective Sample Size)
///
/// \return The value of ESS for current particle set
double ess () const
{
return ess_;
}
/// \brief Get indicator of resampling
///
/// \return A bool value, \b true if the current iteration was resampled
bool resampled () const
{
return resampled_;
}
/// \brief Set indicator of resampling
///
/// \param resampled \b true if the current iteration was resampled
void resampled (bool resampled)
{
resampled_ = resampled;
}
/// \brief Get the value of SMC normalizing constant
///
/// \return SMC normalizng constant estimate
double zconst () const
{
return zconst_;
}
/// \brief Reset the value of SMC normalizing constant
void reset_zconst ()
{
zconst_ = 0;
}
/// \brief Perform resampling
///
/// \param scheme The resampling scheme, see ResamplingScheme
void resample (ResampleScheme scheme)
{
switch (scheme) {
case MULTINOMIAL :
resample_multinomial();
break;
case RESIDUAL :
resample_residual();
break;
case STRATIFIED :
resample_stratified();
break;
case SYSTEMATIC :
resample_systematic();
break;
case RESIDUAL_STRATIFIED :
resample_residual_stratified ();
break;
default :
throw std::runtime_error(
"ERROR: vSMC::Particle::resample: "
"Unknown Resample Scheme");
}
}
rng_type &prng (std::size_t id)
{
return prng_[id];
}
private :
std::size_t size_;
T value_;
Eigen::VectorXd weight_;
Eigen::VectorXd log_weight_;
Eigen::VectorXd inc_weight_;
Eigen::VectorXi replication_;
double ess_;
bool resampled_;
double zconst_;
std::vector<rng_type> prng_;
typedef boost::random::binomial_distribution<> binom_type;
binom_type binom_;
void set_weight ()
{
double max_weight = log_weight_.maxCoeff();
log_weight_ = log_weight_.array() - max_weight;
weight_ = log_weight_.array().exp();
double sum = weight_.sum();
weight_ *= 1 / sum;
ess_ = 1 / weight_.squaredNorm();
}
void resample_multinomial ()
{
weight2replication(size_);
resample_do();
}
void resample_residual ()
{
// Reuse weight and log_weight. weight: act as the fractional part of
// N * weight. log_weight: act as the integral part of N * weight.
// They all will be reset to equal weights after resampling. So it is
// safe to modify them here.
for (std::size_t i = 0; i != size_; ++i)
weight_[i] = std::modf(size_ * weight_[i], log_weight_.data() + i);
std::size_t size = size_ - log_weight_.sum();
weight2replication(size);
for (std::size_t i = 0; i != size_; ++i)
replication_[i] += log_weight_[i];
resample_do();
}
void resample_stratified ()
{
replication_.setConstant(0);
std::size_t j = 0;
std::size_t k = 0;
boost::random::uniform_01<> unif;
double u = unif(prng_[0]);
double cw = weight_[0];
while (j != size_) {
while (j < cw * size_ - u && j != size_) {
++replication_[k];
u = unif(prng_[j++]);
}
cw += weight_[++k];
}
resample_do();
}
void resample_systematic ()
{
replication_.setConstant(0);
std::size_t j = 0;
std::size_t k = 0;
boost::random::uniform_01<> unif;
double u = unif(prng_[0]);
double cw = weight_[0];
while (j != size_) {
while (j < cw * size_ - u && j != size_) {
++replication_[k];
++j;
}
cw += weight_[++k];
}
resample_do();
}
void resample_residual_stratified ()
{
for (std::size_t i = 0; i != size_; ++i)
weight_[i] = std::modf(size_ * weight_[i], log_weight_.data() + i);
resample_stratified();
for (std::size_t i = 0; i != size_; ++i)
replication_[i] += log_weight_[i];
resample_do();
}
void weight2replication (std::size_t size)
{
double tp = weight_.sum();
double sum_p = 0;
std::size_t sum_n = 0;
replication_.setConstant(0);
for (std::size_t i = 0; i != size_; ++i) {
if (sum_n < size && weight_[i] > 0) {
binom_type::param_type
param(size - sum_n, weight_[i] / (tp - sum_p));
replication_[i] = binom_(prng_[i], param);
}
sum_p += weight_[i];
sum_n += replication_[i];
}
}
void resample_do ()
{
// Some times the nuemrical round error can cause the total childs
// differ from number of particles
std::size_t sum = replication_.sum();
if (sum != size_) {
Eigen::VectorXd::Index id_max;
replication_.maxCoeff(&id_max);
replication_[id_max] += size_ - sum;
}
std::size_t from = 0;
std::size_t time = 0;
for (std::size_t to = 0; to != size_; ++to) {
if (!replication_[to]) {
// replication_[to] has zero child, copy from elsewhere
if (replication_[from] - time <= 1) {
// only 1 child left on replication_[from]
time = 0;
do // move from to some position with at least 2 children
++from;
while (replication_[from] < 2);
}
value_.copy(from, to);
++time;
}
}
ess_ = size_;
weight_.setConstant(1.0 / size_);
log_weight_.setConstant(0);
}
}; // class Particle
} // namespace vSMC
#endif // V_SMC_CORE_PARTICLE_HPP
<commit_msg>implement residual stratified resampling<commit_after>#ifndef V_SMC_CORE_PARTICLE_HPP
#define V_SMC_CORE_PARTICLE_HPP
#include <vector>
#include <cmath>
#include <cstddef>
#include <boost/function.hpp>
#include <boost/random/binomial_distribution.hpp>
#include <boost/random/uniform_01.hpp>
#include <Eigen/Dense>
#include <vSMC/internal/rng.hpp>
#include <vSMC/internal/version.hpp>
namespace vSMC {
/// Resample scheme
enum ResampleScheme {
MULTINOMIAL, RESIDUAL, STRATIFIED, SYSTEMATIC, RESIDUAL_STRATIFIED};
/// \brief Particle class
///
/// Particle class store the particle set and arrays of weights and log
/// weights. It provides access to particle values as well as weights. It
/// computes and manages resources for ESS, resampling, etc, tasks unique to
/// each iteration.
template <typename T>
class Particle
{
public :
typedef V_SMC_RNG_TYPE rng_type;
/// \brief Construct a Particle object with given number of particles
///
/// \param N The number of particles
/// \param seed The seed to the parallel RNG system
Particle (std::size_t N, rng_type::seed_type seed = V_SMC_RNG_SEED) :
size_(N), value_(N),
weight_(N), log_weight_(N), inc_weight_(N), replication_(N),
ess_(0), resampled_(false), zconst_(0), prng_(N)
{
rng_type rng(seed);
rng.step_size(size_);
for (std::size_t i = 0; i != size_; ++i) {
rng.advance_ctr(i);
prng_[i] = rng;
}
weight_.setConstant(1.0 / size_);
log_weight_.setConstant(0);
}
/// \brief Size of the particle set
///
/// \return The number of particles
std::size_t size () const
{
return size_;
}
/// \brief Read and write access to particle values
///
/// \return A reference to the particle values, type (T &)
///
/// \note The Particle class guarantee that during the life type of the
/// object, the reference returned by this member will no be a dangle
/// handler.
T &value ()
{
return value_;
}
/// \brief Read only access to particle values
///
/// \return A const reference to the particle values
const T &value () const
{
return value_;
}
/// \brief Read only access to the weights
///
/// \return A const pointer to the weights
///
/// \note The Particle class guarantee that during the life type of the
/// object, the pointer returned by this always valid and point to the
/// same address
const double *weight_ptr () const
{
return weight_.data();
}
/// \brief Read only access to the log weights
///
/// \return A const pointer to the log weights
const double *log_weight_ptr () const
{
return log_weight_.data();
}
const Eigen::VectorXd &weight () const
{
return weight_;
}
const Eigen::VectorXd &log_weight () const
{
return log_weight_;
}
/// \brief Set the log weights
///
/// \param new_weight New log weights
/// \param delta A multiplier appiled to new_weight
void set_log_weight (const double *new_weight, double delta = 1)
{
Eigen::Map<const Eigen::VectorXd> w(new_weight, size_);
log_weight_ = delta * w;
set_weight();
}
/// \brief Add to the log weights
///
/// \param inc_weight Incremental log weights
/// \param delta A multiplier applied to inc_weight
/// \param add_zconst Whether this incremental weights should contribute
/// the esitmates of normalizing constants
void add_log_weight (const double *inc_weight, double delta = 1,
bool add_zconst = true)
{
Eigen::Map<const Eigen::VectorXd> w(inc_weight, size_);
if (add_zconst) {
inc_weight_ = (delta * w).array().exp();
zconst_ += std::log(weight_.dot(inc_weight_));
}
log_weight_ += delta * w;
set_weight();
}
/// \brief The ESS (Effective Sample Size)
///
/// \return The value of ESS for current particle set
double ess () const
{
return ess_;
}
/// \brief Get indicator of resampling
///
/// \return A bool value, \b true if the current iteration was resampled
bool resampled () const
{
return resampled_;
}
/// \brief Set indicator of resampling
///
/// \param resampled \b true if the current iteration was resampled
void resampled (bool resampled)
{
resampled_ = resampled;
}
/// \brief Get the value of SMC normalizing constant
///
/// \return SMC normalizng constant estimate
double zconst () const
{
return zconst_;
}
/// \brief Reset the value of SMC normalizing constant
void reset_zconst ()
{
zconst_ = 0;
}
/// \brief Perform resampling
///
/// \param scheme The resampling scheme, see ResamplingScheme
void resample (ResampleScheme scheme)
{
switch (scheme) {
case MULTINOMIAL :
resample_multinomial();
break;
case RESIDUAL :
resample_residual();
break;
case STRATIFIED :
resample_stratified();
break;
case SYSTEMATIC :
resample_systematic();
break;
case RESIDUAL_STRATIFIED :
resample_residual_stratified ();
break;
default :
throw std::runtime_error(
"ERROR: vSMC::Particle::resample: "
"Unknown Resample Scheme");
}
}
rng_type &prng (std::size_t id)
{
return prng_[id];
}
private :
std::size_t size_;
T value_;
Eigen::VectorXd weight_;
Eigen::VectorXd log_weight_;
Eigen::VectorXd inc_weight_;
Eigen::VectorXi replication_;
double ess_;
bool resampled_;
double zconst_;
std::vector<rng_type> prng_;
typedef boost::random::binomial_distribution<> binom_type;
binom_type binom_;
void set_weight ()
{
double max_weight = log_weight_.maxCoeff();
log_weight_ = log_weight_.array() - max_weight;
weight_ = log_weight_.array().exp();
double sum = weight_.sum();
weight_ *= 1 / sum;
ess_ = 1 / weight_.squaredNorm();
}
void resample_multinomial ()
{
weight2replication(size_);
resample_do();
}
void resample_residual ()
{
// Reuse weight and log_weight. weight: act as the fractional part of
// N * weight. log_weight: act as the integral part of N * weight.
// They all will be reset to equal weights after resampling. So it is
// safe to modify them here.
for (std::size_t i = 0; i != size_; ++i)
weight_[i] = std::modf(size_ * weight_[i], log_weight_.data() + i);
weight2replication(weight_.sum());
for (std::size_t i = 0; i != size_; ++i)
replication_[i] += log_weight_[i];
resample_do();
}
void resample_stratified ()
{
replication_.setConstant(0);
std::size_t j = 0;
std::size_t k = 0;
boost::random::uniform_01<> unif;
double u = unif(prng_[0]);
double cw = weight_[0];
while (j != size_) {
while (j < cw * size_ - u && j != size_) {
++replication_[k];
u = unif(prng_[j++]);
}
cw += weight_[++k];
}
resample_do();
}
void resample_systematic ()
{
replication_.setConstant(0);
std::size_t j = 0;
std::size_t k = 0;
boost::random::uniform_01<> unif;
double u = unif(prng_[0]);
double cw = weight_[0];
while (j != size_) {
while (j < cw * size_ - u && j != size_) {
++replication_[k];
++j;
}
cw += weight_[++k];
}
resample_do();
}
void resample_residual_stratified ()
{
replication_.setConstant(0);
for (std::size_t i = 0; i != size_; ++i)
weight_[i] = std::modf(size_ * weight_[i], log_weight_.data() + i);
std::size_t size = weight_.sum();
weight_ /= size;
std::size_t j = 0;
std::size_t k = 0;
boost::random::uniform_01<> unif;
double u = unif(prng_[0]);
double cw = weight_[0];
while (j != size) {
while (j < cw * size_ - u && j != size) {
++replication_[k];
++j;
}
cw += weight_[++k];
}
for (std::size_t i = 0; i != size_; ++i)
replication_[i] += log_weight_[i];
resample_do();
}
void weight2replication (std::size_t size)
{
double tp = weight_.sum();
double sum_p = 0;
std::size_t sum_n = 0;
replication_.setConstant(0);
for (std::size_t i = 0; i != size_; ++i) {
if (sum_n < size && weight_[i] > 0) {
binom_type::param_type
param(size - sum_n, weight_[i] / (tp - sum_p));
replication_[i] = binom_(prng_[i], param);
}
sum_p += weight_[i];
sum_n += replication_[i];
}
}
void resample_do ()
{
// Some times the nuemrical round error can cause the total childs
// differ from number of particles
std::size_t sum = replication_.sum();
if (sum != size_) {
Eigen::VectorXd::Index id_max;
replication_.maxCoeff(&id_max);
replication_[id_max] += size_ - sum;
}
std::size_t from = 0;
std::size_t time = 0;
for (std::size_t to = 0; to != size_; ++to) {
if (!replication_[to]) {
// replication_[to] has zero child, copy from elsewhere
if (replication_[from] - time <= 1) {
// only 1 child left on replication_[from]
time = 0;
do // move from to some position with at least 2 children
++from;
while (replication_[from] < 2);
}
value_.copy(from, to);
++time;
}
}
ess_ = size_;
weight_.setConstant(1.0 / size_);
log_weight_.setConstant(0);
}
}; // class Particle
} // namespace vSMC
#endif // V_SMC_CORE_PARTICLE_HPP
<|endoftext|>
|
<commit_before>// Copyright 2018 Google LLC
// Copyright 2018-present Open Networking Foundation
// SPDX-License-Identifier: Apache-2.0
#include "stratum/hal/lib/common/hal.h"
#include <chrono> // NOLINT
#include <utility>
#include "absl/base/macros.h"
#include "absl/memory/memory.h"
#include "absl/strings/str_join.h"
#include "absl/strings/str_split.h"
#include "absl/synchronization/mutex.h"
#include "gflags/gflags.h"
#include "stratum/glue/logging.h"
#include "stratum/lib/constants.h"
#include "stratum/lib/macros.h"
#include "stratum/lib/utils.h"
#include "stratum/procmon/procmon.grpc.pb.h"
// TODO(unknown): Use FLAG_DEFINE for all flags.
DEFINE_string(external_stratum_urls, stratum::kExternalStratumUrls,
"Comma-separated list of URLs for server to listen to for "
"external calls from SDN controller, etc.");
DEFINE_string(local_stratum_url, stratum::kLocalStratumUrl,
"URL for listening to local calls from stratum stub.");
DEFINE_bool(warmboot, false, "Determines whether HAL is in warmboot stage.");
DEFINE_string(procmon_service_addr, ::stratum::kProcmonServiceUrl,
"URL of the procmon service to connect to.");
DEFINE_string(persistent_config_dir, "/etc/stratum/",
"The persistent dir where all the config files will be stored.");
DEFINE_int32(grpc_keepalive_time_ms, 600000, "grpc keep alive time");
DEFINE_int32(grpc_keepalive_timeout_ms, 20000,
"grpc keep alive timeout period");
DEFINE_int32(grpc_keepalive_min_ping_interval, 10000,
"grpc keep alive minimum ping interval");
DEFINE_int32(grpc_keepalive_permit, 1, "grpc keep alive permit");
DEFINE_uint32(grpc_max_recv_msg_size, 256 * 1024 * 1024,
"grpc server max receive message size (0 = gRPC default).");
DEFINE_uint32(grpc_max_send_msg_size, 0,
"grpc server max send message size (0 = gRPC default).");
namespace stratum {
namespace hal {
namespace {
// Signal received callback which is registered as the handler for SIGINT and
// SIGTERM signals using signal() system call.
void SignalRcvCallback(int value) {
Hal* hal = Hal::GetSingleton();
if (hal == nullptr) return;
hal->HandleSignal(value);
}
// Set the channel arguments to match the defualt keep-alive parameters set by
// the google3 side net/grpc clients.
void SetGrpcServerKeepAliveArgs(::grpc::ServerBuilder* builder) {
builder->AddChannelArgument(GRPC_ARG_KEEPALIVE_TIME_MS,
FLAGS_grpc_keepalive_time_ms);
builder->AddChannelArgument(GRPC_ARG_KEEPALIVE_TIMEOUT_MS,
FLAGS_grpc_keepalive_timeout_ms);
builder->AddChannelArgument(
GRPC_ARG_HTTP2_MIN_RECV_PING_INTERVAL_WITHOUT_DATA_MS,
FLAGS_grpc_keepalive_min_ping_interval);
builder->AddChannelArgument(GRPC_ARG_KEEPALIVE_PERMIT_WITHOUT_CALLS,
FLAGS_grpc_keepalive_permit);
}
} // namespace
Hal* Hal::singleton_ = nullptr;
ABSL_CONST_INIT absl::Mutex Hal::init_lock_(absl::kConstInit);
Hal::Hal(OperationMode mode, SwitchInterface* switch_interface,
AuthPolicyChecker* auth_policy_checker,
CredentialsManager* credentials_manager)
: mode_(mode),
switch_interface_(ABSL_DIE_IF_NULL(switch_interface)),
auth_policy_checker_(ABSL_DIE_IF_NULL(auth_policy_checker)),
credentials_manager_(ABSL_DIE_IF_NULL(credentials_manager)),
error_buffer_(ABSL_DIE_IF_NULL(new ErrorBuffer())),
config_monitoring_service_(),
p4_service_(nullptr),
admin_service_(nullptr),
certificate_management_service_(nullptr),
diag_service_(nullptr),
file_service_(nullptr),
external_server_(nullptr),
old_signal_handlers_() {}
Hal::~Hal() {
// TODO(unknown): Handle this error?
UnregisterSignalHandlers().IgnoreError();
}
::util::Status Hal::SanityCheck() {
const std::vector<std::string> external_stratum_urls =
absl::StrSplit(FLAGS_external_stratum_urls, ',', absl::SkipEmpty());
CHECK_RETURN_IF_FALSE(!external_stratum_urls.empty())
<< "No external URL was given. This is invalid.";
auto it =
std::find_if(external_stratum_urls.begin(), external_stratum_urls.end(),
[](const std::string& url) {
return (url == FLAGS_local_stratum_url ||
// FIXME(boc) google only url ==
// FLAGS_cmal_service_url ||
url == FLAGS_procmon_service_addr);
});
CHECK_RETURN_IF_FALSE(it == external_stratum_urls.end())
<< "You used one of these reserved local URLs as your external URLs: "
<< FLAGS_local_stratum_url
<< ", "
/*FIXME(boc) google only << FLAGS_cmal_service_url */
<< ", " << FLAGS_procmon_service_addr << ".";
CHECK_RETURN_IF_FALSE(!FLAGS_persistent_config_dir.empty())
<< "persistent_config_dir flag needs to be explicitly given.";
LOG(INFO) << "HAL sanity checks all passed.";
return ::util::OkStatus();
}
::util::Status Hal::Setup() {
LOG(INFO) << "Setting up HAL in "
<< (FLAGS_warmboot ? "WARMBOOT" : "COLDBOOT") << " mode...";
RETURN_IF_ERROR(RecursivelyCreateDir(FLAGS_persistent_config_dir));
// Setup all the services. In case of coldboot setup, we push the saved
// configs to the switch as part of setup. In case of warmboot, we only
// recover the internal state of the class.
RETURN_IF_ERROR(config_monitoring_service_->Setup(FLAGS_warmboot));
RETURN_IF_ERROR(p4_service_->Setup(FLAGS_warmboot));
RETURN_IF_ERROR(admin_service_->Setup(FLAGS_warmboot));
RETURN_IF_ERROR(certificate_management_service_->Setup(FLAGS_warmboot));
RETURN_IF_ERROR(diag_service_->Setup(FLAGS_warmboot));
RETURN_IF_ERROR(file_service_->Setup(FLAGS_warmboot));
if (FLAGS_warmboot) {
// In case of warmboot, we also call unfreeze the switch interface after
// services are setup. Note that finding the saved configs in case of
// warmboot is critical. We will not perform unfreeze if we dont find those
// files.
LOG(INFO) << "Unfreezing HAL...";
::util::Status status = switch_interface_->Unfreeze();
if (!status.ok()) {
error_buffer_->AddError(status, "Failed to unfreeze HAL: ", GTL_LOC);
return status;
}
}
// Successful warmboot or coldboot will clear out the blocking errors.
error_buffer_->ClearErrors();
return ::util::OkStatus();
}
::util::Status Hal::Teardown() {
// Teardown is called as part of both warmboot and coldboot shutdown. In case
// of warmboot shutdown, the stack is first freezed by calling an RPC in
// AdminService, which itself calls Freeze() method in SwitchInterface class.
LOG(INFO) << "Shutting down HAL...";
::util::Status status = ::util::OkStatus();
APPEND_STATUS_IF_ERROR(status, config_monitoring_service_->Teardown());
APPEND_STATUS_IF_ERROR(status, p4_service_->Teardown());
APPEND_STATUS_IF_ERROR(status, certificate_management_service_->Teardown());
APPEND_STATUS_IF_ERROR(status, diag_service_->Teardown());
APPEND_STATUS_IF_ERROR(status, file_service_->Teardown());
APPEND_STATUS_IF_ERROR(status, switch_interface_->Shutdown());
APPEND_STATUS_IF_ERROR(status, auth_policy_checker_->Shutdown());
APPEND_STATUS_IF_ERROR(status, admin_service_->Teardown());
if (!status.ok()) {
error_buffer_->AddError(status, "Failed to shutdown HAL: ", GTL_LOC);
return status;
}
return ::util::OkStatus();
}
::util::Status Hal::Run() {
// All HAL external facing services listen to a list of secure external URLs
// given by external_stratum_urls flag, as well as a local insecure URLs for
// given by local_stratum_url flag. The insecure URLs is used by any local
// stratum_stub binary running on the switch, since local connections cannot
// support auth.
const std::vector<std::string> external_stratum_urls =
absl::StrSplit(FLAGS_external_stratum_urls, ',');
{
std::shared_ptr<::grpc::ServerCredentials> server_credentials =
credentials_manager_->GenerateExternalFacingServerCredentials();
::grpc::ServerBuilder builder;
SetGrpcServerKeepAliveArgs(&builder);
builder.AddListeningPort(FLAGS_local_stratum_url,
::grpc::InsecureServerCredentials());
for (const auto& url : external_stratum_urls) {
builder.AddListeningPort(url, server_credentials);
}
if (FLAGS_grpc_max_recv_msg_size > 0) {
builder.SetMaxReceiveMessageSize(FLAGS_grpc_max_recv_msg_size);
builder.AddChannelArgument<int>(GRPC_ARG_MAX_METADATA_SIZE,
FLAGS_grpc_max_recv_msg_size);
}
if (FLAGS_grpc_max_send_msg_size > 0) {
builder.SetMaxSendMessageSize(FLAGS_grpc_max_send_msg_size);
}
builder.RegisterService(config_monitoring_service_.get());
builder.RegisterService(p4_service_.get());
builder.RegisterService(admin_service_.get());
builder.RegisterService(certificate_management_service_.get());
builder.RegisterService(diag_service_.get());
builder.RegisterService(file_service_.get());
external_server_ = builder.BuildAndStart();
if (external_server_ == nullptr) {
return MAKE_ERROR(ERR_INTERNAL)
<< "Failed to start Stratum external facing services. This is an "
<< "internal error.";
}
LOG(ERROR) << "Stratum external facing services are listening to "
<< absl::StrJoin(external_stratum_urls, ", ") << ", "
<< FLAGS_local_stratum_url << "...";
}
if (mode_ != OPERATION_MODE_SIM) {
// Try checking in with Procmon if we are not running in sim mode. Continue
// if checkin fails.
::util::Status status = ProcmonCheckin();
if (!status.ok()) {
LOG(ERROR) << "Error when checking in with procmon: "
<< status.error_message() << ".";
}
}
external_server_->Wait(); // blocking until external_server_->Shutdown()
// is called. We dont wait on internal_service.
return Teardown();
}
void Hal::HandleSignal(int value) {
LOG(INFO) << "Received signal: " << strsignal(value);
// Calling Shutdown() so the blocking call to Wait() returns.
// NOTE: Seems like if there is an active stream Read(), calling Shutdown()
// with no deadline will block forever, as it waits for all the active RPCs
// to finish. To fix this, we give a deadline set to "now" so the call returns
// immediately.
external_server_->Shutdown(std::chrono::system_clock::now());
}
Hal* Hal::CreateSingleton(OperationMode mode, SwitchInterface* switch_interface,
AuthPolicyChecker* auth_policy_checker,
CredentialsManager* credentials_manager) {
absl::WriterMutexLock l(&init_lock_);
if (!singleton_) {
singleton_ = new Hal(mode, switch_interface, auth_policy_checker,
credentials_manager);
::util::Status status = singleton_->RegisterSignalHandlers();
if (!status.ok()) {
LOG(ERROR) << "RegisterSignalHandlers() failed: " << status;
delete singleton_;
singleton_ = nullptr;
}
status = singleton_->InitializeServer();
if (!status.ok()) {
LOG(ERROR) << "InitializeServer() failed: " << status;
delete singleton_;
singleton_ = nullptr;
}
}
return singleton_;
}
Hal* Hal::GetSingleton() {
absl::ReaderMutexLock l(&init_lock_);
return singleton_;
}
#define CHECK_IS_NULL(ptr) \
if (ptr != nullptr) { \
return MAKE_ERROR(ERR_INTERNAL) \
<< #ptr << " is not nullptr. InitializeServer() cannot be called " \
<< "multiple times."; \
}
::util::Status Hal::InitializeServer() {
CHECK_IS_NULL(config_monitoring_service_);
CHECK_IS_NULL(p4_service_);
CHECK_IS_NULL(admin_service_);
CHECK_IS_NULL(certificate_management_service_);
CHECK_IS_NULL(diag_service_);
CHECK_IS_NULL(file_service_);
CHECK_IS_NULL(external_server_);
// FIXME(boc) google only
// CHECK_IS_NULL(internal_server_);
// Reset error_buffer_.
error_buffer_->ClearErrors();
// Build the HAL services.
config_monitoring_service_ = absl::make_unique<ConfigMonitoringService>(
mode_, switch_interface_, auth_policy_checker_, error_buffer_.get());
p4_service_ = absl::make_unique<P4Service>(
mode_, switch_interface_, auth_policy_checker_, error_buffer_.get());
admin_service_ = absl::make_unique<AdminService>(
mode_, switch_interface_, auth_policy_checker_, error_buffer_.get(),
SignalRcvCallback);
certificate_management_service_ =
absl::make_unique<CertificateManagementService>(
mode_, switch_interface_, auth_policy_checker_, error_buffer_.get());
diag_service_ = absl::make_unique<DiagService>(
mode_, switch_interface_, auth_policy_checker_, error_buffer_.get());
file_service_ = absl::make_unique<FileService>(
mode_, switch_interface_, auth_policy_checker_, error_buffer_.get());
return ::util::OkStatus();
}
#undef CHECK_IS_NULL // should not be used in any other method.
::util::Status Hal::RegisterSignalHandlers() {
// Register the signal handlers and save the old handlers as well.
std::vector<int> sig = {SIGINT, SIGTERM, SIGUSR2};
for (const int s : sig) {
sighandler_t h = signal(s, SignalRcvCallback);
if (h == SIG_ERR) {
return MAKE_ERROR(ERR_INTERNAL)
<< "Failed to register signal " << strsignal(s);
}
old_signal_handlers_[s] = h;
}
return ::util::OkStatus();
}
::util::Status Hal::UnregisterSignalHandlers() {
// Register the old handlers for all the signals.
for (const auto& e : old_signal_handlers_) {
signal(e.first, e.second);
}
old_signal_handlers_.clear();
return ::util::OkStatus();
}
::util::Status Hal::ProcmonCheckin() {
// FIXME replace Procmon with gNOI
std::unique_ptr<procmon::ProcmonService::Stub> stub =
procmon::ProcmonService::NewStub(::grpc::CreateChannel(
FLAGS_procmon_service_addr, ::grpc::InsecureChannelCredentials()));
if (stub == nullptr) {
return MAKE_ERROR(ERR_INTERNAL)
<< "Could not create stub for procmon gRPC service.";
}
procmon::CheckinRequest req;
procmon::CheckinResponse resp;
::grpc::ClientContext context;
req.set_checkin_key(getpid());
::grpc::Status status = stub->Checkin(&context, req, &resp);
if (!status.ok()) {
return MAKE_ERROR(ERR_INTERNAL)
<< "Failed to check in with procmon: " << status.error_message();
}
return ::util::OkStatus();
}
} // namespace hal
} // namespace stratum
<commit_msg>Replace `<chrono>` with absl time in hal.c (#647)<commit_after>// Copyright 2018 Google LLC
// Copyright 2018-present Open Networking Foundation
// SPDX-License-Identifier: Apache-2.0
#include "stratum/hal/lib/common/hal.h"
#include <utility>
#include "absl/base/macros.h"
#include "absl/memory/memory.h"
#include "absl/strings/str_join.h"
#include "absl/strings/str_split.h"
#include "absl/synchronization/mutex.h"
#include "gflags/gflags.h"
#include "stratum/glue/logging.h"
#include "stratum/lib/constants.h"
#include "stratum/lib/macros.h"
#include "stratum/lib/utils.h"
#include "stratum/procmon/procmon.grpc.pb.h"
// TODO(unknown): Use FLAG_DEFINE for all flags.
DEFINE_string(external_stratum_urls, stratum::kExternalStratumUrls,
"Comma-separated list of URLs for server to listen to for "
"external calls from SDN controller, etc.");
DEFINE_string(local_stratum_url, stratum::kLocalStratumUrl,
"URL for listening to local calls from stratum stub.");
DEFINE_bool(warmboot, false, "Determines whether HAL is in warmboot stage.");
DEFINE_string(procmon_service_addr, ::stratum::kProcmonServiceUrl,
"URL of the procmon service to connect to.");
DEFINE_string(persistent_config_dir, "/etc/stratum/",
"The persistent dir where all the config files will be stored.");
DEFINE_int32(grpc_keepalive_time_ms, 600000, "grpc keep alive time");
DEFINE_int32(grpc_keepalive_timeout_ms, 20000,
"grpc keep alive timeout period");
DEFINE_int32(grpc_keepalive_min_ping_interval, 10000,
"grpc keep alive minimum ping interval");
DEFINE_int32(grpc_keepalive_permit, 1, "grpc keep alive permit");
DEFINE_uint32(grpc_max_recv_msg_size, 256 * 1024 * 1024,
"grpc server max receive message size (0 = gRPC default).");
DEFINE_uint32(grpc_max_send_msg_size, 0,
"grpc server max send message size (0 = gRPC default).");
namespace stratum {
namespace hal {
namespace {
// Signal received callback which is registered as the handler for SIGINT and
// SIGTERM signals using signal() system call.
void SignalRcvCallback(int value) {
Hal* hal = Hal::GetSingleton();
if (hal == nullptr) return;
hal->HandleSignal(value);
}
// Set the channel arguments to match the defualt keep-alive parameters set by
// the google3 side net/grpc clients.
void SetGrpcServerKeepAliveArgs(::grpc::ServerBuilder* builder) {
builder->AddChannelArgument(GRPC_ARG_KEEPALIVE_TIME_MS,
FLAGS_grpc_keepalive_time_ms);
builder->AddChannelArgument(GRPC_ARG_KEEPALIVE_TIMEOUT_MS,
FLAGS_grpc_keepalive_timeout_ms);
builder->AddChannelArgument(
GRPC_ARG_HTTP2_MIN_RECV_PING_INTERVAL_WITHOUT_DATA_MS,
FLAGS_grpc_keepalive_min_ping_interval);
builder->AddChannelArgument(GRPC_ARG_KEEPALIVE_PERMIT_WITHOUT_CALLS,
FLAGS_grpc_keepalive_permit);
}
} // namespace
Hal* Hal::singleton_ = nullptr;
ABSL_CONST_INIT absl::Mutex Hal::init_lock_(absl::kConstInit);
Hal::Hal(OperationMode mode, SwitchInterface* switch_interface,
AuthPolicyChecker* auth_policy_checker,
CredentialsManager* credentials_manager)
: mode_(mode),
switch_interface_(ABSL_DIE_IF_NULL(switch_interface)),
auth_policy_checker_(ABSL_DIE_IF_NULL(auth_policy_checker)),
credentials_manager_(ABSL_DIE_IF_NULL(credentials_manager)),
error_buffer_(ABSL_DIE_IF_NULL(new ErrorBuffer())),
config_monitoring_service_(),
p4_service_(nullptr),
admin_service_(nullptr),
certificate_management_service_(nullptr),
diag_service_(nullptr),
file_service_(nullptr),
external_server_(nullptr),
old_signal_handlers_() {}
Hal::~Hal() {
// TODO(unknown): Handle this error?
UnregisterSignalHandlers().IgnoreError();
}
::util::Status Hal::SanityCheck() {
const std::vector<std::string> external_stratum_urls =
absl::StrSplit(FLAGS_external_stratum_urls, ',', absl::SkipEmpty());
CHECK_RETURN_IF_FALSE(!external_stratum_urls.empty())
<< "No external URL was given. This is invalid.";
auto it =
std::find_if(external_stratum_urls.begin(), external_stratum_urls.end(),
[](const std::string& url) {
return (url == FLAGS_local_stratum_url ||
// FIXME(boc) google only url ==
// FLAGS_cmal_service_url ||
url == FLAGS_procmon_service_addr);
});
CHECK_RETURN_IF_FALSE(it == external_stratum_urls.end())
<< "You used one of these reserved local URLs as your external URLs: "
<< FLAGS_local_stratum_url
<< ", "
/*FIXME(boc) google only << FLAGS_cmal_service_url */
<< ", " << FLAGS_procmon_service_addr << ".";
CHECK_RETURN_IF_FALSE(!FLAGS_persistent_config_dir.empty())
<< "persistent_config_dir flag needs to be explicitly given.";
LOG(INFO) << "HAL sanity checks all passed.";
return ::util::OkStatus();
}
::util::Status Hal::Setup() {
LOG(INFO) << "Setting up HAL in "
<< (FLAGS_warmboot ? "WARMBOOT" : "COLDBOOT") << " mode...";
RETURN_IF_ERROR(RecursivelyCreateDir(FLAGS_persistent_config_dir));
// Setup all the services. In case of coldboot setup, we push the saved
// configs to the switch as part of setup. In case of warmboot, we only
// recover the internal state of the class.
RETURN_IF_ERROR(config_monitoring_service_->Setup(FLAGS_warmboot));
RETURN_IF_ERROR(p4_service_->Setup(FLAGS_warmboot));
RETURN_IF_ERROR(admin_service_->Setup(FLAGS_warmboot));
RETURN_IF_ERROR(certificate_management_service_->Setup(FLAGS_warmboot));
RETURN_IF_ERROR(diag_service_->Setup(FLAGS_warmboot));
RETURN_IF_ERROR(file_service_->Setup(FLAGS_warmboot));
if (FLAGS_warmboot) {
// In case of warmboot, we also call unfreeze the switch interface after
// services are setup. Note that finding the saved configs in case of
// warmboot is critical. We will not perform unfreeze if we dont find those
// files.
LOG(INFO) << "Unfreezing HAL...";
::util::Status status = switch_interface_->Unfreeze();
if (!status.ok()) {
error_buffer_->AddError(status, "Failed to unfreeze HAL: ", GTL_LOC);
return status;
}
}
// Successful warmboot or coldboot will clear out the blocking errors.
error_buffer_->ClearErrors();
return ::util::OkStatus();
}
::util::Status Hal::Teardown() {
// Teardown is called as part of both warmboot and coldboot shutdown. In case
// of warmboot shutdown, the stack is first freezed by calling an RPC in
// AdminService, which itself calls Freeze() method in SwitchInterface class.
LOG(INFO) << "Shutting down HAL...";
::util::Status status = ::util::OkStatus();
APPEND_STATUS_IF_ERROR(status, config_monitoring_service_->Teardown());
APPEND_STATUS_IF_ERROR(status, p4_service_->Teardown());
APPEND_STATUS_IF_ERROR(status, certificate_management_service_->Teardown());
APPEND_STATUS_IF_ERROR(status, diag_service_->Teardown());
APPEND_STATUS_IF_ERROR(status, file_service_->Teardown());
APPEND_STATUS_IF_ERROR(status, switch_interface_->Shutdown());
APPEND_STATUS_IF_ERROR(status, auth_policy_checker_->Shutdown());
APPEND_STATUS_IF_ERROR(status, admin_service_->Teardown());
if (!status.ok()) {
error_buffer_->AddError(status, "Failed to shutdown HAL: ", GTL_LOC);
return status;
}
return ::util::OkStatus();
}
::util::Status Hal::Run() {
// All HAL external facing services listen to a list of secure external URLs
// given by external_stratum_urls flag, as well as a local insecure URLs for
// given by local_stratum_url flag. The insecure URLs is used by any local
// stratum_stub binary running on the switch, since local connections cannot
// support auth.
const std::vector<std::string> external_stratum_urls =
absl::StrSplit(FLAGS_external_stratum_urls, ',');
{
std::shared_ptr<::grpc::ServerCredentials> server_credentials =
credentials_manager_->GenerateExternalFacingServerCredentials();
::grpc::ServerBuilder builder;
SetGrpcServerKeepAliveArgs(&builder);
builder.AddListeningPort(FLAGS_local_stratum_url,
::grpc::InsecureServerCredentials());
for (const auto& url : external_stratum_urls) {
builder.AddListeningPort(url, server_credentials);
}
if (FLAGS_grpc_max_recv_msg_size > 0) {
builder.SetMaxReceiveMessageSize(FLAGS_grpc_max_recv_msg_size);
builder.AddChannelArgument<int>(GRPC_ARG_MAX_METADATA_SIZE,
FLAGS_grpc_max_recv_msg_size);
}
if (FLAGS_grpc_max_send_msg_size > 0) {
builder.SetMaxSendMessageSize(FLAGS_grpc_max_send_msg_size);
}
builder.RegisterService(config_monitoring_service_.get());
builder.RegisterService(p4_service_.get());
builder.RegisterService(admin_service_.get());
builder.RegisterService(certificate_management_service_.get());
builder.RegisterService(diag_service_.get());
builder.RegisterService(file_service_.get());
external_server_ = builder.BuildAndStart();
if (external_server_ == nullptr) {
return MAKE_ERROR(ERR_INTERNAL)
<< "Failed to start Stratum external facing services. This is an "
<< "internal error.";
}
LOG(ERROR) << "Stratum external facing services are listening to "
<< absl::StrJoin(external_stratum_urls, ", ") << ", "
<< FLAGS_local_stratum_url << "...";
}
if (mode_ != OPERATION_MODE_SIM) {
// Try checking in with Procmon if we are not running in sim mode. Continue
// if checkin fails.
::util::Status status = ProcmonCheckin();
if (!status.ok()) {
LOG(ERROR) << "Error when checking in with procmon: "
<< status.error_message() << ".";
}
}
external_server_->Wait(); // blocking until external_server_->Shutdown()
// is called. We dont wait on internal_service.
return Teardown();
}
void Hal::HandleSignal(int value) {
LOG(INFO) << "Received signal: " << strsignal(value);
// Calling Shutdown() so the blocking call to Wait() returns.
// NOTE: Seems like if there is an active stream Read(), calling Shutdown()
// with no deadline will block forever, as it waits for all the active RPCs
// to finish. To fix this, we give a deadline set to "now" so the call returns
// immediately.
external_server_->Shutdown(absl::ToChronoTime(absl::Now()));
}
Hal* Hal::CreateSingleton(OperationMode mode, SwitchInterface* switch_interface,
AuthPolicyChecker* auth_policy_checker,
CredentialsManager* credentials_manager) {
absl::WriterMutexLock l(&init_lock_);
if (!singleton_) {
singleton_ = new Hal(mode, switch_interface, auth_policy_checker,
credentials_manager);
::util::Status status = singleton_->RegisterSignalHandlers();
if (!status.ok()) {
LOG(ERROR) << "RegisterSignalHandlers() failed: " << status;
delete singleton_;
singleton_ = nullptr;
}
status = singleton_->InitializeServer();
if (!status.ok()) {
LOG(ERROR) << "InitializeServer() failed: " << status;
delete singleton_;
singleton_ = nullptr;
}
}
return singleton_;
}
Hal* Hal::GetSingleton() {
absl::ReaderMutexLock l(&init_lock_);
return singleton_;
}
#define CHECK_IS_NULL(ptr) \
if (ptr != nullptr) { \
return MAKE_ERROR(ERR_INTERNAL) \
<< #ptr << " is not nullptr. InitializeServer() cannot be called " \
<< "multiple times."; \
}
::util::Status Hal::InitializeServer() {
CHECK_IS_NULL(config_monitoring_service_);
CHECK_IS_NULL(p4_service_);
CHECK_IS_NULL(admin_service_);
CHECK_IS_NULL(certificate_management_service_);
CHECK_IS_NULL(diag_service_);
CHECK_IS_NULL(file_service_);
CHECK_IS_NULL(external_server_);
// FIXME(boc) google only
// CHECK_IS_NULL(internal_server_);
// Reset error_buffer_.
error_buffer_->ClearErrors();
// Build the HAL services.
config_monitoring_service_ = absl::make_unique<ConfigMonitoringService>(
mode_, switch_interface_, auth_policy_checker_, error_buffer_.get());
p4_service_ = absl::make_unique<P4Service>(
mode_, switch_interface_, auth_policy_checker_, error_buffer_.get());
admin_service_ = absl::make_unique<AdminService>(
mode_, switch_interface_, auth_policy_checker_, error_buffer_.get(),
SignalRcvCallback);
certificate_management_service_ =
absl::make_unique<CertificateManagementService>(
mode_, switch_interface_, auth_policy_checker_, error_buffer_.get());
diag_service_ = absl::make_unique<DiagService>(
mode_, switch_interface_, auth_policy_checker_, error_buffer_.get());
file_service_ = absl::make_unique<FileService>(
mode_, switch_interface_, auth_policy_checker_, error_buffer_.get());
return ::util::OkStatus();
}
#undef CHECK_IS_NULL // should not be used in any other method.
::util::Status Hal::RegisterSignalHandlers() {
// Register the signal handlers and save the old handlers as well.
std::vector<int> sig = {SIGINT, SIGTERM, SIGUSR2};
for (const int s : sig) {
sighandler_t h = signal(s, SignalRcvCallback);
if (h == SIG_ERR) {
return MAKE_ERROR(ERR_INTERNAL)
<< "Failed to register signal " << strsignal(s);
}
old_signal_handlers_[s] = h;
}
return ::util::OkStatus();
}
::util::Status Hal::UnregisterSignalHandlers() {
// Register the old handlers for all the signals.
for (const auto& e : old_signal_handlers_) {
signal(e.first, e.second);
}
old_signal_handlers_.clear();
return ::util::OkStatus();
}
::util::Status Hal::ProcmonCheckin() {
// FIXME replace Procmon with gNOI
std::unique_ptr<procmon::ProcmonService::Stub> stub =
procmon::ProcmonService::NewStub(::grpc::CreateChannel(
FLAGS_procmon_service_addr, ::grpc::InsecureChannelCredentials()));
if (stub == nullptr) {
return MAKE_ERROR(ERR_INTERNAL)
<< "Could not create stub for procmon gRPC service.";
}
procmon::CheckinRequest req;
procmon::CheckinResponse resp;
::grpc::ClientContext context;
req.set_checkin_key(getpid());
::grpc::Status status = stub->Checkin(&context, req, &resp);
if (!status.ok()) {
return MAKE_ERROR(ERR_INTERNAL)
<< "Failed to check in with procmon: " << status.error_message();
}
return ::util::OkStatus();
}
} // namespace hal
} // namespace stratum
<|endoftext|>
|
<commit_before>/**
* Description: BigInt (Big Integer library)
* Usage: See constructors, operators like +, -, *, /, >, >=, <, <=, ==, toString
* Note: Remove references '&' in overloaded operators for chaining operations.
* Source: https://github.com/dragonslayerx
*/
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
class Bigint {
const static int MAX = 100005;
char x[MAX];
int length;
void align(char *X, int numDigits) {
int length = strlen(X);
for (int i = length; i < numDigits; i++) X[i]='0';
X[numDigits]='\0';
}
int add(char *X, int lenX, char *Y, int lenY, int carry, char *Z) {
int maxLen = max(lenX, lenY);
align(X, maxLen); align(Y, maxLen);
for (int i = 0; i < maxLen; i++) {
int num = (X[i]-'0') + (Y[i]-'0') + carry;
Z[i] = num%10 + '0';
carry = num / 10;
}
if (carry) Z[maxLen++] = carry+'0';
Z[maxLen] = '\0';
//Put everything back to original state
X[lenX]='\0'; Y[lenY]='\0';
return maxLen;
}
int substract(char *X, int lenX, char *Y, int lenY, char *Z){
int maxLen = max(lenX, lenY);
align(X, maxLen); align(Y, maxLen);
for (int i = 0; i < maxLen; i++) Y[i]=('9'-Y[i])+'0';
int len = add(X, lenX, Y, maxLen, 1, Z);
Z[len--] = '\0';
//Put everything back to original state
for (int i = 0; i < maxLen; i++) Y[i]=('9'-Y[i])+'0';
X[lenX]='\0'; Y[lenY]='\0';
return len;
}
int multiply(char *X, int lenX, char *Y, int lenY, char *Z) {
if (lenX < lenY) {
swap(X, Y); swap(lenX, lenY);
}
char result[MAX];
int lenZ = 0;
for (int i = 0; Y[i]; i++) {
int digit = Y[i]-'0';
int carry = 0, size = 0;
for (int j = 0; X[j]; j++) {
int val = ((X[j]-'0')*digit) + carry;
carry = val/10;
val %= 10;
result[size++] = val+'0';
}
if (carry) result[size++] = carry + '0';
result[size]='\0';
for (int j = size; j >= 0; j--) result[j+i] = result[j];
for (int j = 0; j < i; j++) result[j]='0';
char finalResult[MAX];
lenZ = add(result, size+i, Z, lenZ, 0, finalResult);
strcpy(Z, finalResult);
}
return lenZ;
}
template<class T>
int divideNmodulo(char *X, int lenX, T divisor, char *Z, T &modulo) {
int remainder = 0;
int size = 0;
for(int i = lenX-1; i >= 0; i--){
remainder *= 10;
remainder += X[i]- '0';
Z[size++] = remainder/divisor + '0';
remainder %= divisor;
}
Z[size]='\0';
reverse(Z, Z+size);
modulo = remainder;
return size;
}
//Logical Operations
bool equals(char *X, int lenX, char *Y, int lenY) {
int maxLen = max(lenX, lenY);
align(X, maxLen); align(Y, maxLen);
for (int i = maxLen; i >= 0; i--) {
if (X[i] != Y[i]) return false;
}
//Put everything back to original state
X[lenX] = '\0'; Y[lenY] = '\0';
return true;
}
bool greater(char *X, int lenX, char *Y, int lenY) {
int maxLen = max(lenX, lenY);
align(X, maxLen); align(Y, maxLen);
for (int i = maxLen; i >= 0; i--) {
if (X[i] > Y[i]) return true;
}
//Put everything back to original state
X[lenX] = '\0'; Y[lenY] = '\0';
return false;
}
public:
//Constructors
Bigint() {
x[0]='0'; x[1]='\0';
length=1;
}
Bigint(string s) {
length = s.size();
for (int i=0, j=length-1; i < s.size(); i++, j--) x[j]=s[i];
x[length]='\0';
}
Bigint(int v) {
int size = 0;
while (v) {
x[size++] = v % 10 + '0';
v /= 10;
}
x[size]='\0';
length = size;
}
//Arithmetic Operations
Bigint operator +(Bigint &b) {
Bigint r;
r.length = add(this->x, this->length, b.x, b.length, 0, r.x);
return r;
}
Bigint operator *(Bigint &b) {
Bigint r;
r.length = multiply(this->x, this->length, b.x, b.length, r.x);
return r;
}
Bigint operator -(Bigint &b) {
Bigint r;
r.length = substract(this->x, this->length, b.x, b.length, r.x);
return r;
}
Bigint operator /(int divisor) {
Bigint r;
int modulo = 0;
r.length = divideNmodulo(this->x, this->length, divisor, r.x, modulo);
return r;
}
int operator %(int divisor) {
Bigint r;
int modulo = 0;
r.length = divideNmodulo(this->x, this->length, divisor, r.x, modulo);
return modulo;
}
//Logical Operators
bool operator ==(Bigint &b) {
return equals(this->x, this->length, b.x, b.length);
}
bool operator >(Bigint &b) {
return !greater(b.x, b.length, this->x, this->length);
}
bool operator >=(Bigint &b) {
return (((*this)>b) || ((*this)==b));
}
bool operator <(Bigint &b) {
return !((*this)>=b);
}
bool operator <=(Bigint &b) {
return !((*this)>b);
}
string trimZeros(string &s) {
int start = 0;
while (s[start]=='0') start++;
return s.substr(start);
}
string toString() {
string s(x, x+length);
reverse(s.begin(), s.end());
return trimZeros(s);
}
friend std::ostream& operator<<(ostream &o, Bigint v) {
o << v.toString();
return o;
}
};
int main() {
Bigint A("123456789"); // Construct Bigint using string representation
Bigint B(987654321); // Construct Bigint using integer representation
Bigint C("456789");
cout << A * B << endl; // Overridden ostream
cout << A * B + C << endl; // Chaining operations
cout << (A > B) << endl;
// logical operations
if (A > B) cout << "A is greater than B" << endl;
else cout << "B is greater than A" << endl;
}
<commit_msg>bigint: fix: toString with value 0<commit_after>/*
* Description: BigInt (Big Integer library)
* Usage: See constructors, operators like +, -, *, /, >, >=, <, <=, ==, toString
* Note: Remove references '&' in overloaded operators for chaining operations.
* Source: https://github.com/dragonslayerx
*/
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
class Bigint {
const static int MAX = 100005;
char x[MAX];
int length;
void align(char *X, int numDigits) {
int length = strlen(X);
for (int i = length; i < numDigits; i++) X[i]='0';
X[numDigits]='\0';
}
int add(char *X, int lenX, char *Y, int lenY, int carry, char *Z) {
int maxLen = max(lenX, lenY);
align(X, maxLen); align(Y, maxLen);
for (int i = 0; i < maxLen; i++) {
int num = (X[i]-'0') + (Y[i]-'0') + carry;
Z[i] = num%10 + '0';
carry = num / 10;
}
if (carry) Z[maxLen++] = carry+'0';
Z[maxLen] = '\0';
//Put everything back to original state
X[lenX]='\0'; Y[lenY]='\0';
return maxLen;
}
int substract(char *X, int lenX, char *Y, int lenY, char *Z){
int maxLen = max(lenX, lenY);
align(X, maxLen); align(Y, maxLen);
for (int i = 0; i < maxLen; i++) Y[i]=('9'-Y[i])+'0';
int len = add(X, lenX, Y, maxLen, 1, Z);
Z[len--] = '\0';
//Put everything back to original state
for (int i = 0; i < maxLen; i++) Y[i]=('9'-Y[i])+'0';
X[lenX]='\0'; Y[lenY]='\0';
return len;
}
int multiply(char *X, int lenX, char *Y, int lenY, char *Z) {
if (lenX < lenY) {
swap(X, Y); swap(lenX, lenY);
}
char result[MAX];
int lenZ = 0;
for (int i = 0; Y[i]; i++) {
int digit = Y[i]-'0';
int carry = 0, size = 0;
for (int j = 0; X[j]; j++) {
int val = ((X[j]-'0')*digit) + carry;
carry = val/10;
val %= 10;
result[size++] = val+'0';
}
if (carry) result[size++] = carry + '0';
result[size]='\0';
for (int j = size; j >= 0; j--) result[j+i] = result[j];
for (int j = 0; j < i; j++) result[j]='0';
char finalResult[MAX];
lenZ = add(result, size+i, Z, lenZ, 0, finalResult);
strcpy(Z, finalResult);
}
return lenZ;
}
template<class T>
int divideNmodulo(char *X, int lenX, T divisor, char *Z, T &modulo) {
int remainder = 0;
int size = 0;
for(int i = lenX-1; i >= 0; i--){
remainder *= 10;
remainder += X[i]- '0';
Z[size++] = remainder/divisor + '0';
remainder %= divisor;
}
Z[size]='\0';
reverse(Z, Z+size);
modulo = remainder;
return size;
}
//Logical Operations
bool equals(char *X, int lenX, char *Y, int lenY) {
int maxLen = max(lenX, lenY);
align(X, maxLen); align(Y, maxLen);
for (int i = maxLen; i >= 0; i--) {
if (X[i] != Y[i]) return false;
}
//Put everything back to original state
X[lenX] = '\0'; Y[lenY] = '\0';
return true;
}
bool greater(char *X, int lenX, char *Y, int lenY) {
int maxLen = max(lenX, lenY);
align(X, maxLen); align(Y, maxLen);
for (int i = maxLen; i >= 0; i--) {
if (X[i] > Y[i]) return true;
}
//Put everything back to original state
X[lenX] = '\0'; Y[lenY] = '\0';
return false;
}
public:
//Constructors
Bigint() {
x[0]='0'; x[1]='\0';
length=1;
}
Bigint(string s) {
length = s.size();
for (int i=0, j=length-1; i < s.size(); i++, j--) x[j]=s[i];
x[length]='\0';
}
Bigint(int v) {
int size = 0;
while (v) {
x[size++] = v % 10 + '0';
v /= 10;
}
x[size]='\0';
length = size;
}
//Arithmetic Operations
Bigint operator +(Bigint &b) {
Bigint r;
r.length = add(this->x, this->length, b.x, b.length, 0, r.x);
return r;
}
Bigint operator *(Bigint &b) {
Bigint r;
r.length = multiply(this->x, this->length, b.x, b.length, r.x);
return r;
}
Bigint operator -(Bigint &b) {
Bigint r;
r.length = substract(this->x, this->length, b.x, b.length, r.x);
return r;
}
Bigint operator /(int divisor) {
Bigint r;
int modulo = 0;
r.length = divideNmodulo(this->x, this->length, divisor, r.x, modulo);
return r;
}
int operator %(int divisor) {
Bigint r;
int modulo = 0;
r.length = divideNmodulo(this->x, this->length, divisor, r.x, modulo);
return modulo;
}
//Logical Operators
bool operator ==(Bigint &b) {
return equals(this->x, this->length, b.x, b.length);
}
bool operator >(Bigint &b) {
return !greater(b.x, b.length, this->x, this->length);
}
bool operator >=(Bigint &b) {
return (((*this)>b) || ((*this)==b));
}
bool operator <(Bigint &b) {
return !((*this)>=b);
}
bool operator <=(Bigint &b) {
return !((*this)>b);
}
string trimZeros(string &s) {
int start = 0;
while (s[start]=='0') start++;
return s.substr(start);
}
string toString() {
string s(x, x+length);
reverse(s.begin(), s.end());
s = trimZeros(s);
if(s.length() == 0)
return "0";
return s;
}
friend std::ostream& operator<<(ostream &o, Bigint v) {
o << v.toString();
return o;
}
};
int main() {
Bigint A("123456789"); // Construct Bigint using string representation
Bigint B(987654321); // Construct Bigint using integer representation
Bigint C("456789");
Bigint D("0");
cout << "A * B: " << A * B << endl; // Overridden ostream
cout << "A * B + C: " << A * B + C << endl; // Chaining operations
cout << "(A > B): " << (A > B) << endl;
cout << "D: " << D << endl;
// logical operations
if (A > B) cout << "A is greater than B" << endl;
if (B > A) cout << "B is greater than A" << endl;
if (A == B) cout << "A is equal to B" << endl;
}
<|endoftext|>
|
<commit_before>// RUN: cat %s | %cling -Xclang -verify | FileCheck %s
//This file checks a call instruction. The called function has arguments with nonnull attribute.
#include <string.h>
// XFAIL: darwin
// XFAIL: i686-pc-linux-gnu
char *p = 0;
strcmp("a", p); // expected-warning {{warning: null passed to a callee which requires a non-null argument}}
strcmp(p, "a"); // expected-warning {{warning: null passed to a callee which requires a non-null argument}}
extern "C" int printf(const char* fmt, ...);
.rawInput 1
extern "C" int cannotCallWithNull(int* p = 0);
extern "C" int cannotCallWithNull(int* p) __attribute__((nonnull(1)));
extern "C" int cannotCallWithNull(int* p);
extern "C" int cannotCallWithNull(int* p);
.rawInput 0
extern "C" int cannotCallWithNull(int* p) {
if (!p)
printf("Must not be called with p=0.\n");
return 1;
}
int *q = 0;
cannotCallWithNull(q); // expected-warning {{warning: null passed to a callee which requires a non-null argument}}
//CHECK-NOT: Must not be called with p=0.
cannotCallWithNull(new int(4))
//CHECK: (int) 1
.q
<commit_msg>Adapt to new diag format.<commit_after>// RUN: cat %s | %cling -Xclang -verify | FileCheck %s
//This file checks a call instruction. The called function has arguments with nonnull attribute.
#include <string.h>
// XFAIL: darwin
// XFAIL: i686-pc-linux-gnu
char *p = 0;
strcmp("a", p); // expected-warning {{null passed to a callee which requires a non-null argument}}
strcmp(p, "a"); // expected-warning {{null passed to a callee which requires a non-null argument}}
extern "C" int printf(const char* fmt, ...);
.rawInput 1
extern "C" int cannotCallWithNull(int* p = 0);
extern "C" int cannotCallWithNull(int* p) __attribute__((nonnull(1)));
extern "C" int cannotCallWithNull(int* p);
extern "C" int cannotCallWithNull(int* p);
.rawInput 0
extern "C" int cannotCallWithNull(int* p) {
if (!p)
printf("Must not be called with p=0.\n");
return 1;
}
int *q = 0;
cannotCallWithNull(q); // expected-warning {{null passed to a callee which requires a non-null argument}}
//CHECK-NOT: Must not be called with p=0.
cannotCallWithNull(new int(4))
//CHECK: (int) 1
.q
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2012 Google
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef __ARCH_X86_DECODER_HH__
#define __ARCH_X86_DECODER_HH__
#include <cassert>
#include <unordered_map>
#include <vector>
#include "arch/generic/decoder.hh"
#include "arch/x86/regs/misc.hh"
#include "arch/x86/types.hh"
#include "base/bitfield.hh"
#include "base/logging.hh"
#include "base/trace.hh"
#include "base/types.hh"
#include "cpu/decode_cache.hh"
#include "cpu/static_inst.hh"
#include "debug/Decoder.hh"
namespace X86ISA
{
class ISA;
class Decoder : public InstDecoder
{
private:
// These are defined and documented in decoder_tables.cc
static const uint8_t SizeTypeToSize[3][10];
typedef const uint8_t ByteTable[256];
static ByteTable Prefixes;
static ByteTable UsesModRMOneByte;
static ByteTable UsesModRMTwoByte;
static ByteTable UsesModRMThreeByte0F38;
static ByteTable UsesModRMThreeByte0F3A;
static ByteTable ImmediateTypeOneByte;
static ByteTable ImmediateTypeTwoByte;
static ByteTable ImmediateTypeThreeByte0F38;
static ByteTable ImmediateTypeThreeByte0F3A;
static ByteTable ImmediateTypeVex[10];
protected:
struct InstBytes
{
StaticInstPtr si;
std::vector<MachInst> chunks;
std::vector<MachInst> masks;
int lastOffset;
InstBytes() : lastOffset(0)
{}
};
static InstBytes dummy;
// The bytes to be predecoded.
MachInst fetchChunk;
InstBytes *instBytes;
int chunkIdx;
// The pc of the start of fetchChunk.
Addr basePC;
// The pc the current instruction started at.
Addr origPC;
// The offset into fetchChunk of current processing.
int offset;
// The extended machine instruction being generated.
ExtMachInst emi;
// Predecoding state.
X86Mode mode;
X86SubMode submode;
uint8_t altOp;
uint8_t defOp;
uint8_t altAddr;
uint8_t defAddr;
uint8_t stack;
uint8_t
getNextByte()
{
return ((uint8_t *)&fetchChunk)[offset];
}
void
getImmediate(int &collected, uint64_t ¤t, int size)
{
// Figure out how many bytes we still need to get for the
// immediate.
int toGet = size - collected;
// Figure out how many bytes are left in our "buffer".
int remaining = sizeof(MachInst) - offset;
// Get as much as we need, up to the amount available.
toGet = toGet > remaining ? remaining : toGet;
// Shift the bytes we want to be all the way to the right
uint64_t partialImm = fetchChunk >> (offset * 8);
// Mask off what we don't want.
partialImm &= mask(toGet * 8);
// Shift it over to overlay with our displacement.
partialImm <<= (immediateCollected * 8);
// Put it into our displacement.
current |= partialImm;
// Update how many bytes we've collected.
collected += toGet;
consumeBytes(toGet);
}
void
updateOffsetState()
{
assert(offset <= sizeof(MachInst));
if (offset == sizeof(MachInst)) {
DPRINTF(Decoder, "At the end of a chunk, idx = %d, chunks = %d.\n",
chunkIdx, instBytes->chunks.size());
chunkIdx++;
if (chunkIdx == instBytes->chunks.size()) {
outOfBytes = true;
} else {
offset = 0;
fetchChunk = instBytes->chunks[chunkIdx];
basePC += sizeof(MachInst);
}
}
}
void
consumeByte()
{
offset++;
updateOffsetState();
}
void
consumeBytes(int numBytes)
{
offset += numBytes;
updateOffsetState();
}
// State machine state.
protected:
// Whether or not we're out of bytes.
bool outOfBytes;
// Whether we've completed generating an ExtMachInst.
bool instDone;
// The size of the displacement value.
int displacementSize;
// The size of the immediate value.
int immediateSize;
// This is how much of any immediate value we've gotten. This is used
// for both the actual immediate and the displacement.
int immediateCollected;
enum State {
ResetState,
FromCacheState,
PrefixState,
Vex2Of2State,
Vex2Of3State,
Vex3Of3State,
VexOpcodeState,
OneByteOpcodeState,
TwoByteOpcodeState,
ThreeByte0F38OpcodeState,
ThreeByte0F3AOpcodeState,
ModRMState,
SIBState,
DisplacementState,
ImmediateState,
// We should never get to this state. Getting here is an error.
ErrorState
};
State state;
// Functions to handle each of the states
State doResetState();
State doFromCacheState();
State doPrefixState(uint8_t);
State doVex2Of2State(uint8_t);
State doVex2Of3State(uint8_t);
State doVex3Of3State(uint8_t);
State doVexOpcodeState(uint8_t);
State doOneByteOpcodeState(uint8_t);
State doTwoByteOpcodeState(uint8_t);
State doThreeByte0F38OpcodeState(uint8_t);
State doThreeByte0F3AOpcodeState(uint8_t);
State doModRMState(uint8_t);
State doSIBState(uint8_t);
State doDisplacementState();
State doImmediateState();
// Process the actual opcode found earlier, using the supplied tables.
State processOpcode(ByteTable &immTable, ByteTable &modrmTable,
bool addrSizedImm = false);
// Process the opcode found with VEX / XOP prefix.
State processExtendedOpcode(ByteTable &immTable);
protected:
/// Caching for decoded instruction objects.
typedef RegVal CacheKey;
typedef DecodeCache::AddrMap<Decoder::InstBytes> DecodePages;
DecodePages *decodePages;
typedef std::unordered_map<CacheKey, DecodePages *> AddrCacheMap;
AddrCacheMap addrCacheMap;
DecodeCache::InstMap<ExtMachInst> *instMap;
typedef std::unordered_map<
CacheKey, DecodeCache::InstMap<ExtMachInst> *> InstCacheMap;
static InstCacheMap instCacheMap;
public:
Decoder(ISA* isa = nullptr) : basePC(0), origPC(0), offset(0),
outOfBytes(true), instDone(false), state(ResetState)
{
emi.reset();
mode = LongMode;
submode = SixtyFourBitMode;
emi.mode.mode = mode;
emi.mode.submode = submode;
altOp = 0;
defOp = 0;
altAddr = 0;
defAddr = 0;
stack = 0;
instBytes = &dummy;
decodePages = NULL;
instMap = NULL;
}
void
setM5Reg(HandyM5Reg m5Reg)
{
mode = (X86Mode)(uint64_t)m5Reg.mode;
submode = (X86SubMode)(uint64_t)m5Reg.submode;
emi.mode.mode = mode;
emi.mode.submode = submode;
altOp = m5Reg.altOp;
defOp = m5Reg.defOp;
altAddr = m5Reg.altAddr;
defAddr = m5Reg.defAddr;
stack = m5Reg.stack;
AddrCacheMap::iterator amIter = addrCacheMap.find(m5Reg);
if (amIter != addrCacheMap.end()) {
decodePages = amIter->second;
} else {
decodePages = new DecodePages;
addrCacheMap[m5Reg] = decodePages;
}
InstCacheMap::iterator imIter = instCacheMap.find(m5Reg);
if (imIter != instCacheMap.end()) {
instMap = imIter->second;
} else {
instMap = new DecodeCache::InstMap<ExtMachInst>;
instCacheMap[m5Reg] = instMap;
}
}
void
takeOverFrom(Decoder *old)
{
mode = old->mode;
submode = old->submode;
emi.mode.mode = mode;
emi.mode.submode = submode;
altOp = old->altOp;
defOp = old->defOp;
altAddr = old->altAddr;
defAddr = old->defAddr;
stack = old->stack;
}
void reset() { state = ResetState; }
void process();
// Use this to give data to the decoder. This should be used
// when there is control flow.
void
moreBytes(const PCState &pc, Addr fetchPC, MachInst data)
{
DPRINTF(Decoder, "Getting more bytes.\n");
basePC = fetchPC;
offset = (fetchPC >= pc.instAddr()) ? 0 : pc.instAddr() - fetchPC;
fetchChunk = letoh(data);
outOfBytes = false;
process();
}
bool needMoreBytes() { return outOfBytes; }
bool instReady() { return instDone; }
void
updateNPC(X86ISA::PCState &nextPC)
{
if (!nextPC.size()) {
int size = basePC + offset - origPC;
DPRINTF(Decoder,
"Calculating the instruction size: "
"basePC: %#x offset: %#x origPC: %#x size: %d\n",
basePC, offset, origPC, size);
nextPC.size(size);
nextPC.npc(nextPC.pc() + size);
}
}
public:
StaticInstPtr decodeInst(ExtMachInst mach_inst);
/// Decode a machine instruction.
/// @param mach_inst The binary instruction to decode.
/// @retval A pointer to the corresponding StaticInst object.
StaticInstPtr decode(ExtMachInst mach_inst, Addr addr);
StaticInstPtr decode(X86ISA::PCState &nextPC);
};
} // namespace X86ISA
#endif // __ARCH_X86_DECODER_HH__
<commit_msg>x86: Use default initializers to simplify the decoder constructor.<commit_after>/*
* Copyright (c) 2012 Google
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef __ARCH_X86_DECODER_HH__
#define __ARCH_X86_DECODER_HH__
#include <cassert>
#include <unordered_map>
#include <vector>
#include "arch/generic/decoder.hh"
#include "arch/x86/regs/misc.hh"
#include "arch/x86/types.hh"
#include "base/bitfield.hh"
#include "base/logging.hh"
#include "base/trace.hh"
#include "base/types.hh"
#include "cpu/decode_cache.hh"
#include "cpu/static_inst.hh"
#include "debug/Decoder.hh"
namespace X86ISA
{
class ISA;
class Decoder : public InstDecoder
{
private:
// These are defined and documented in decoder_tables.cc
static const uint8_t SizeTypeToSize[3][10];
typedef const uint8_t ByteTable[256];
static ByteTable Prefixes;
static ByteTable UsesModRMOneByte;
static ByteTable UsesModRMTwoByte;
static ByteTable UsesModRMThreeByte0F38;
static ByteTable UsesModRMThreeByte0F3A;
static ByteTable ImmediateTypeOneByte;
static ByteTable ImmediateTypeTwoByte;
static ByteTable ImmediateTypeThreeByte0F38;
static ByteTable ImmediateTypeThreeByte0F3A;
static ByteTable ImmediateTypeVex[10];
protected:
struct InstBytes
{
StaticInstPtr si;
std::vector<MachInst> chunks;
std::vector<MachInst> masks;
int lastOffset;
InstBytes() : lastOffset(0)
{}
};
static InstBytes dummy;
// The bytes to be predecoded.
MachInst fetchChunk;
InstBytes *instBytes = &dummy;
int chunkIdx;
// The pc of the start of fetchChunk.
Addr basePC = 0;
// The pc the current instruction started at.
Addr origPC = 0;
// The offset into fetchChunk of current processing.
int offset = 0;
// The extended machine instruction being generated.
ExtMachInst emi;
// Predecoding state.
X86Mode mode = LongMode;
X86SubMode submode = SixtyFourBitMode;
uint8_t altOp = 0;
uint8_t defOp = 0;
uint8_t altAddr = 0;
uint8_t defAddr = 0;
uint8_t stack = 0;
uint8_t
getNextByte()
{
return ((uint8_t *)&fetchChunk)[offset];
}
void
getImmediate(int &collected, uint64_t ¤t, int size)
{
// Figure out how many bytes we still need to get for the
// immediate.
int toGet = size - collected;
// Figure out how many bytes are left in our "buffer".
int remaining = sizeof(MachInst) - offset;
// Get as much as we need, up to the amount available.
toGet = toGet > remaining ? remaining : toGet;
// Shift the bytes we want to be all the way to the right
uint64_t partialImm = fetchChunk >> (offset * 8);
// Mask off what we don't want.
partialImm &= mask(toGet * 8);
// Shift it over to overlay with our displacement.
partialImm <<= (immediateCollected * 8);
// Put it into our displacement.
current |= partialImm;
// Update how many bytes we've collected.
collected += toGet;
consumeBytes(toGet);
}
void
updateOffsetState()
{
assert(offset <= sizeof(MachInst));
if (offset == sizeof(MachInst)) {
DPRINTF(Decoder, "At the end of a chunk, idx = %d, chunks = %d.\n",
chunkIdx, instBytes->chunks.size());
chunkIdx++;
if (chunkIdx == instBytes->chunks.size()) {
outOfBytes = true;
} else {
offset = 0;
fetchChunk = instBytes->chunks[chunkIdx];
basePC += sizeof(MachInst);
}
}
}
void
consumeByte()
{
offset++;
updateOffsetState();
}
void
consumeBytes(int numBytes)
{
offset += numBytes;
updateOffsetState();
}
// State machine state.
protected:
// Whether or not we're out of bytes.
bool outOfBytes = true;
// Whether we've completed generating an ExtMachInst.
bool instDone = false;
// The size of the displacement value.
int displacementSize;
// The size of the immediate value.
int immediateSize;
// This is how much of any immediate value we've gotten. This is used
// for both the actual immediate and the displacement.
int immediateCollected;
enum State {
ResetState,
FromCacheState,
PrefixState,
Vex2Of2State,
Vex2Of3State,
Vex3Of3State,
VexOpcodeState,
OneByteOpcodeState,
TwoByteOpcodeState,
ThreeByte0F38OpcodeState,
ThreeByte0F3AOpcodeState,
ModRMState,
SIBState,
DisplacementState,
ImmediateState,
// We should never get to this state. Getting here is an error.
ErrorState
};
State state = ResetState;
// Functions to handle each of the states
State doResetState();
State doFromCacheState();
State doPrefixState(uint8_t);
State doVex2Of2State(uint8_t);
State doVex2Of3State(uint8_t);
State doVex3Of3State(uint8_t);
State doVexOpcodeState(uint8_t);
State doOneByteOpcodeState(uint8_t);
State doTwoByteOpcodeState(uint8_t);
State doThreeByte0F38OpcodeState(uint8_t);
State doThreeByte0F3AOpcodeState(uint8_t);
State doModRMState(uint8_t);
State doSIBState(uint8_t);
State doDisplacementState();
State doImmediateState();
// Process the actual opcode found earlier, using the supplied tables.
State processOpcode(ByteTable &immTable, ByteTable &modrmTable,
bool addrSizedImm = false);
// Process the opcode found with VEX / XOP prefix.
State processExtendedOpcode(ByteTable &immTable);
protected:
/// Caching for decoded instruction objects.
typedef RegVal CacheKey;
typedef DecodeCache::AddrMap<Decoder::InstBytes> DecodePages;
DecodePages *decodePages = nullptr;
typedef std::unordered_map<CacheKey, DecodePages *> AddrCacheMap;
AddrCacheMap addrCacheMap;
DecodeCache::InstMap<ExtMachInst> *instMap = nullptr;
typedef std::unordered_map<
CacheKey, DecodeCache::InstMap<ExtMachInst> *> InstCacheMap;
static InstCacheMap instCacheMap;
public:
Decoder(ISA *isa=nullptr)
{
emi.reset();
emi.mode.mode = mode;
emi.mode.submode = submode;
}
void
setM5Reg(HandyM5Reg m5Reg)
{
mode = (X86Mode)(uint64_t)m5Reg.mode;
submode = (X86SubMode)(uint64_t)m5Reg.submode;
emi.mode.mode = mode;
emi.mode.submode = submode;
altOp = m5Reg.altOp;
defOp = m5Reg.defOp;
altAddr = m5Reg.altAddr;
defAddr = m5Reg.defAddr;
stack = m5Reg.stack;
AddrCacheMap::iterator amIter = addrCacheMap.find(m5Reg);
if (amIter != addrCacheMap.end()) {
decodePages = amIter->second;
} else {
decodePages = new DecodePages;
addrCacheMap[m5Reg] = decodePages;
}
InstCacheMap::iterator imIter = instCacheMap.find(m5Reg);
if (imIter != instCacheMap.end()) {
instMap = imIter->second;
} else {
instMap = new DecodeCache::InstMap<ExtMachInst>;
instCacheMap[m5Reg] = instMap;
}
}
void
takeOverFrom(Decoder *old)
{
mode = old->mode;
submode = old->submode;
emi.mode.mode = mode;
emi.mode.submode = submode;
altOp = old->altOp;
defOp = old->defOp;
altAddr = old->altAddr;
defAddr = old->defAddr;
stack = old->stack;
}
void reset() { state = ResetState; }
void process();
// Use this to give data to the decoder. This should be used
// when there is control flow.
void
moreBytes(const PCState &pc, Addr fetchPC, MachInst data)
{
DPRINTF(Decoder, "Getting more bytes.\n");
basePC = fetchPC;
offset = (fetchPC >= pc.instAddr()) ? 0 : pc.instAddr() - fetchPC;
fetchChunk = letoh(data);
outOfBytes = false;
process();
}
bool needMoreBytes() { return outOfBytes; }
bool instReady() { return instDone; }
void
updateNPC(X86ISA::PCState &nextPC)
{
if (!nextPC.size()) {
int size = basePC + offset - origPC;
DPRINTF(Decoder,
"Calculating the instruction size: "
"basePC: %#x offset: %#x origPC: %#x size: %d\n",
basePC, offset, origPC, size);
nextPC.size(size);
nextPC.npc(nextPC.pc() + size);
}
}
public:
StaticInstPtr decodeInst(ExtMachInst mach_inst);
/// Decode a machine instruction.
/// @param mach_inst The binary instruction to decode.
/// @retval A pointer to the corresponding StaticInst object.
StaticInstPtr decode(ExtMachInst mach_inst, Addr addr);
StaticInstPtr decode(X86ISA::PCState &nextPC);
};
} // namespace X86ISA
#endif // __ARCH_X86_DECODER_HH__
<|endoftext|>
|
<commit_before>/// @brief provides a proxy class to deal with integer below fixed-point number
#include <boost/operators.hpp>
namespace utils {
template<typename storage_type, size_t total, size_t fractionals>
class number;
/// @brief proxy class for dealing with fixed-point numbers as with integers
template<typename T, size_t n, size_t f>
class as_native_proxy
: boost::operators<as_native_proxy<T, n, f> >,
boost::operators2<as_native_proxy<T, n, f>, T>,
boost::shiftable<as_native_proxy<T, n, f> >,
boost::shiftable2<as_native_proxy<T, n, f>, T>
{
typedef as_native_proxy<T, n, f> this_class;
typedef number<T, n, f> fixed_point_class;
public:
explicit as_native_proxy(fixed_point_class& x)
: m_value(x.m_value){};
/// @brief less operator. It is the same as one for native integral types
/// is
bool operator <(this_class const& x) const{ return x.value() < this->value(); }
bool operator <(T x) const{ return x < this->value(); }
/// @brief equality comparison operator. It is the same as one for native
/// integral types is
bool operator ==(this_class const& x) const{ return x.value() == this->value(); }
bool operator ==(T x) const{ return x == this->value(); }
/// @brief addition operator. It checks if result fits the bounds drawn
/// from n bits of length
this_class& operator +=(this_class const& x)
{
fixed_point_class::bounds::check(this->value() += x.value());
return *this;
}
this_class& operator +=(T x)
{
fixed_point_class::bounds::check(this->value() += x);
return *this;
}
/// @brief subtraction operator. It checks if result fits the bounds drawn
/// from n bits of length (signed/unsigned).
this_class& operator -=(this_class const& x)
{
fixed_point_class::bounds::check(this->value() -= x.value());
return *this;
}
this_class& operator -=(T x)
{
fixed_point_class::bounds::check(this->value() -= x);
return *this;
}
/// @brief multiplication operator. It checks if result fits the bounds
/// drawn from n bits of length.
this_class& operator *=(this_class const& x)
{
fixed_point_class::bounds::check(this->value() *= x.value());
return *this;
}
this_class& operator *=(T x)
{
fixed_point_class::bounds::check(this->value() *= x);
return *this;
}
/// @brief division operator. It checks if result fits the bounds drawn
/// from n bits of length.
this_class& operator /=(this_class const& x)
{
fixed_point_class::bounds::check(this->value() /= x.value());
return *this;
}
this_class& operator /=(T x)
{
fixed_point_class::bounds::check(this->value() /= x);
return *this;
}
/// @brief mod operator. It is the same as one for native types is.
this_class& operator %=(this_class const& x)
{
this->value() %= x.value();
return *this;
}
this_class& operator %=(T x){ this->value() %= x; return *this; }
/// @brief xor operator. It checks if result fits the bounds drawn from
/// n bits of length
this_class& operator ^=(this_class const& x)
{
fixed_point_class::bounds::check(this->value() ^= x.value());
return *this;
}
this_class& operator ^=(T x)
{
fixed_point_class::bounds::check(this->value() ^= x);
return *this;
}
/// @brief and operator. It is the same as one for native types is.
this_class& operator &=(this_class const& x)
{
this->value() &= x.value();
return *this;
}
this_class& operator &=(T x){ this->value() &= x; return *this; }
/// @brief or operator. It checks if result fits the bounds drawn from
/// n bits of length
this_class& operator |=(this_class const& x)
{
fixed_point_class::bounds::check(this->value() |= x.value());
return *this;
}
this_class& operator !=(T x)
{
fixed_point_class::bounds::check(this->value() |= x);
return *this;
}
/// @brief increment operator. It checks if result fits the bounds drawn
/// from n bits of length.
this_class& operator ++()
{
fixed_point_class::bounds::check(this->value()++);
return *this;
}
/// @brief decrement operator. It checks if result fits the bounds drawn
/// from n bits of length.
this_class& operator --()
{
fixed_point_class::bounds::check(this->value()--);
return *this;
}
/// @brief left shift operator. It checks if result fits the bounds drawn
/// from n bits of length.
this_class& operator <<=(this_class const& x)
{
fixed_point_class::bounds::check(this_value() >>= x.value());
return *this;
}
this_class& operator <<=(T x)
{
fixed_point_class::bounds::check(this_value() >>= x);
return *this;
}
/// @brief right shift operator. It is the same as one for native integers
/// is.
this_class& operator >>=(this_class const& x)
{
this->value() >>= x.value();
return *this;
}
this_class& operator >>=(T x){ this->value() >>= x; return x; }
private:
T& m_value;
T& value(){ return this->m_value; }
};
}
<commit_msg>as_native_proxy.hpp: just refactoring + public copy operator + private copy constructor<commit_after>/// @brief provides a proxy class to deal with integer below fixed-point number
#include <boost/operators.hpp>
namespace utils {
template<typename storage_type, size_t total, size_t fractionals, class op,
class up>
class number;
/// @brief proxy class for dealing with fixed-point numbers as with integers
template<typename T, size_t n, size_t f, class op, class up>
class as_native_proxy
: boost::operators<as_native_proxy<T, n, f, op, up> >,
boost::operators2<as_native_proxy<T, n, f, op, up>, T>,
boost::shiftable<as_native_proxy<T, n, f, op, up> >,
boost::shiftable2<as_native_proxy<T, n, f, op, up>, T>
{
typedef as_native_proxy<T, n, f, op, up> this_class;
typedef number<T, n, f, op, up> fixed_point_class;
public:
/// @brief copy operator
template<typename T>
void operator =(T val){ this->m_value = val; }
/// @brief less operator. It is the same as one for native integral types
/// is
bool operator <(this_class const& x) const{ return x.value() < this->value(); }
bool operator <(T x) const{ return x < this->value(); }
/// @brief equality comparison operator. It is the same as one for native
/// integral types is
bool operator ==(this_class const& x) const{ return x.value() == this->value(); }
bool operator ==(T x) const{ return x == this->value(); }
/// @brief addition operator. It checks if result fits the bounds drawn
/// from n bits of length
this_class& operator +=(this_class const& x)
{
fixed_point_class::bounds::check(this->value() += x.value());
return *this;
}
this_class& operator +=(T x)
{
fixed_point_class::bounds::check(this->value() += x);
return *this;
}
/// @brief subtraction operator. It checks if result fits the bounds drawn
/// from n bits of length (signed/unsigned).
this_class& operator -=(this_class const& x)
{
fixed_point_class::bounds::check(this->value() -= x.value());
return *this;
}
this_class& operator -=(T x)
{
fixed_point_class::bounds::check(this->value() -= x);
return *this;
}
/// @brief multiplication operator. It checks if result fits the bounds
/// drawn from n bits of length.
this_class& operator *=(this_class const& x)
{
fixed_point_class::bounds::check(this->value() *= x.value());
return *this;
}
this_class& operator *=(T x)
{
fixed_point_class::bounds::check(this->value() *= x);
return *this;
}
/// @brief division operator. It checks if result fits the bounds drawn
/// from n bits of length.
this_class& operator /=(this_class const& x)
{
fixed_point_class::bounds::check(this->value() /= x.value());
return *this;
}
this_class& operator /=(T x)
{
fixed_point_class::bounds::check(this->value() /= x);
return *this;
}
/// @brief mod operator. It is the same as one for native types is.
this_class& operator %=(this_class const& x)
{
this->value() %= x.value();
return *this;
}
this_class& operator %=(T x){ this->value() %= x; return *this; }
/// @brief xor operator. It checks if result fits the bounds drawn from
/// n bits of length
this_class& operator ^=(this_class const& x)
{
fixed_point_class::bounds::check(this->value() ^= x.value());
return *this;
}
this_class& operator ^=(T x)
{
fixed_point_class::bounds::check(this->value() ^= x);
return *this;
}
/// @brief and operator. It is the same as one for native types is.
this_class& operator &=(this_class const& x)
{
this->value() &= x.value();
return *this;
}
this_class& operator &=(T x){ this->value() &= x; return *this; }
/// @brief or operator. It checks if result fits the bounds drawn from
/// n bits of length
this_class& operator |=(this_class const& x)
{
fixed_point_class::bounds::check(this->value() |= x.value());
return *this;
}
this_class& operator !=(T x)
{
fixed_point_class::bounds::check(this->value() |= x);
return *this;
}
/// @brief increment operator. It checks if result fits the bounds drawn
/// from n bits of length.
this_class& operator ++()
{
fixed_point_class::bounds::check(this->value()++);
return *this;
}
/// @brief decrement operator. It checks if result fits the bounds drawn
/// from n bits of length.
this_class& operator --()
{
fixed_point_class::bounds::check(this->value()--);
return *this;
}
/// @brief left shift operator. It checks if result fits the bounds drawn
/// from n bits of length.
this_class& operator <<=(this_class const& x)
{
fixed_point_class::bounds::check(this_value() >>= x.value());
return *this;
}
this_class& operator <<=(T x)
{
fixed_point_class::bounds::check(this_value() >>= x);
return *this;
}
/// @brief right shift operator. It is the same as one for native integers
/// is.
this_class& operator >>=(this_class const& x)
{
this->value() >>= x.value();
return *this;
}
this_class& operator >>=(T x){ this->value() >>= x; return x; }
private:
T& m_value;
T& value(){ return this->m_value; }
as_native_proxy(fixed_point_class& x)
: m_value(x.m_value){};
template<>
friend this_class as_native(fixed_point_class&);
};
}
<|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.
//
//===----------------------------------------------------------------------===//
// XFAIL: libcpp-no-exceptions
// <string>
// template <class T>
// basic_string& append(const T& t, size_type pos, size_type n=npos); // C++17
#include <string>
#include <string>
#include <stdexcept>
#include <cassert>
#include "test_macros.h"
#include "min_allocator.h"
template <class S, class SV>
void
test(S s, SV sv, typename S::size_type pos, typename S::size_type n, S expected)
{
try
{
s.append(sv, pos, n);
LIBCPP_ASSERT(s.__invariants());
assert(pos <= sv.size());
assert(s == expected);
}
catch (std::out_of_range&)
{
assert(pos > sv.size());
}
}
template <class S, class SV>
void
test_npos(S s, SV sv, typename S::size_type pos, S expected)
{
try
{
s.append(sv, pos);
LIBCPP_ASSERT(s.__invariants());
assert(pos <= sv.size());
assert(s == expected);
}
catch (std::out_of_range&)
{
assert(pos > sv.size());
}
}
int main()
{
{
typedef std::string S;
typedef std::string_view SV;
test(S(), SV(), 0, 0, S());
test(S(), SV(), 1, 0, S());
test(S(), SV("12345"), 0, 3, S("123"));
test(S(), SV("12345"), 1, 4, S("2345"));
test(S(), SV("12345"), 3, 15, S("45"));
test(S(), SV("12345"), 5, 15, S(""));
test(S(), SV("12345"), 6, 15, S("not happening"));
test(S(), SV("12345678901234567890"), 0, 0, S());
test(S(), SV("12345678901234567890"), 1, 1, S("2"));
test(S(), SV("12345678901234567890"), 2, 3, S("345"));
test(S(), SV("12345678901234567890"), 12, 13, S("34567890"));
test(S(), SV("12345678901234567890"), 21, 13, S("not happening"));
test(S("12345"), SV(), 0, 0, S("12345"));
test(S("12345"), SV("12345"), 2, 2, S("1234534"));
test(S("12345"), SV("1234567890"), 0, 100, S("123451234567890"));
test(S("12345678901234567890"), SV(), 0, 0, S("12345678901234567890"));
test(S("12345678901234567890"), SV("12345"), 1, 3, S("12345678901234567890234"));
test(S("12345678901234567890"), SV("12345678901234567890"), 5, 10,
S("123456789012345678906789012345"));
}
#if TEST_STD_VER >= 11
{
typedef std::basic_string <char, std::char_traits<char>, min_allocator<char>> S;
typedef std::basic_string_view<char, std::char_traits<char> > SV;
test(S(), SV(), 0, 0, S());
test(S(), SV(), 1, 0, S());
test(S(), SV("12345"), 0, 3, S("123"));
test(S(), SV("12345"), 1, 4, S("2345"));
test(S(), SV("12345"), 3, 15, S("45"));
test(S(), SV("12345"), 5, 15, S(""));
test(S(), SV("12345"), 6, 15, S("not happening"));
test(S(), SV("12345678901234567890"), 0, 0, S());
test(S(), SV("12345678901234567890"), 1, 1, S("2"));
test(S(), SV("12345678901234567890"), 2, 3, S("345"));
test(S(), SV("12345678901234567890"), 12, 13, S("34567890"));
test(S(), SV("12345678901234567890"), 21, 13, S("not happening"));
test(S("12345"), SV(), 0, 0, S("12345"));
test(S("12345"), SV("12345"), 2, 2, S("1234534"));
test(S("12345"), SV("1234567890"), 0, 100, S("123451234567890"));
test(S("12345678901234567890"), SV(), 0, 0, S("12345678901234567890"));
test(S("12345678901234567890"), SV("12345"), 1, 3, S("12345678901234567890234"));
test(S("12345678901234567890"), SV("12345678901234567890"), 5, 10,
S("123456789012345678906789012345"));
}
#endif
{
typedef std::string S;
typedef std::string_view SV;
test_npos(S(), SV(), 0, S());
test_npos(S(), SV(), 1, S());
test_npos(S(), SV("12345"), 0, S("12345"));
test_npos(S(), SV("12345"), 1, S("2345"));
test_npos(S(), SV("12345"), 3, S("45"));
test_npos(S(), SV("12345"), 5, S(""));
test_npos(S(), SV("12345"), 6, S("not happening"));
}
{
typedef std::string S;
typedef std::string_view SV;
S s;
SV sv = "EFGH";
char arr[] = "IJKL";
s.append("CDEF", 0); // calls append(const char *, len)
assert(s == "");
s.clear();
s.append("QRST", 0, std::string::npos); // calls append(string("QRST"), pos, npos)
assert(s == "QRST");
s.clear();
s.append(sv, 0); // calls append(T, pos, npos)
assert(s == sv);
s.clear();
s.append(sv, 0, std::string::npos); // calls append(T, pos, npos)
assert(s == sv);
s.clear();
s.append(arr, 0); // calls append(const char *, len)
assert(s == "");
s.clear();
s.append(arr, 0, std::string::npos); // calls append(string("IJKL"), pos, npos)
assert(s == "IJKL");
s.clear();
s.append(arr, 0); // calls append(const char *, len)
assert(s == "");
s.clear();
{
S s = "ABCD";
SV sv = s;
s.append(sv);
assert(s == "ABCDABCD");
sv = s;
s.append(sv, 0, std::string::npos);
assert(s == "ABCDABCDABCDABCD");
}
{
S s = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
SV sv = s;
s.append(sv);
assert(s == "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ");
sv = s;
s.append(sv, 0, std::string::npos);
assert(s == "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ");
}
}
}
<commit_msg>Add another append test for basic_string<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.
//
//===----------------------------------------------------------------------===//
// XFAIL: libcpp-no-exceptions
// <string>
// template <class T>
// basic_string& append(const T& t, size_type pos, size_type n=npos); // C++17
#include <string>
#include <string>
#include <stdexcept>
#include <cassert>
#include "test_macros.h"
#include "min_allocator.h"
template <class S, class SV>
void
test(S s, SV sv, typename S::size_type pos, typename S::size_type n, S expected)
{
try
{
s.append(sv, pos, n);
LIBCPP_ASSERT(s.__invariants());
assert(pos <= sv.size());
assert(s == expected);
}
catch (std::out_of_range&)
{
assert(pos > sv.size());
}
}
template <class S, class SV>
void
test_npos(S s, SV sv, typename S::size_type pos, S expected)
{
try
{
s.append(sv, pos);
LIBCPP_ASSERT(s.__invariants());
assert(pos <= sv.size());
assert(s == expected);
}
catch (std::out_of_range&)
{
assert(pos > sv.size());
}
}
int main()
{
{
typedef std::string S;
typedef std::string_view SV;
test(S(), SV(), 0, 0, S());
test(S(), SV(), 1, 0, S());
test(S(), SV("12345"), 0, 3, S("123"));
test(S(), SV("12345"), 1, 4, S("2345"));
test(S(), SV("12345"), 3, 15, S("45"));
test(S(), SV("12345"), 5, 15, S(""));
test(S(), SV("12345"), 6, 15, S("not happening"));
test(S(), SV("12345678901234567890"), 0, 0, S());
test(S(), SV("12345678901234567890"), 1, 1, S("2"));
test(S(), SV("12345678901234567890"), 2, 3, S("345"));
test(S(), SV("12345678901234567890"), 12, 13, S("34567890"));
test(S(), SV("12345678901234567890"), 21, 13, S("not happening"));
test(S("12345"), SV(), 0, 0, S("12345"));
test(S("12345"), SV("12345"), 2, 2, S("1234534"));
test(S("12345"), SV("1234567890"), 0, 100, S("123451234567890"));
test(S("12345678901234567890"), SV(), 0, 0, S("12345678901234567890"));
test(S("12345678901234567890"), SV("12345"), 1, 3, S("12345678901234567890234"));
test(S("12345678901234567890"), SV("12345678901234567890"), 5, 10,
S("123456789012345678906789012345"));
}
#if TEST_STD_VER >= 11
{
typedef std::basic_string <char, std::char_traits<char>, min_allocator<char>> S;
typedef std::basic_string_view<char, std::char_traits<char> > SV;
test(S(), SV(), 0, 0, S());
test(S(), SV(), 1, 0, S());
test(S(), SV("12345"), 0, 3, S("123"));
test(S(), SV("12345"), 1, 4, S("2345"));
test(S(), SV("12345"), 3, 15, S("45"));
test(S(), SV("12345"), 5, 15, S(""));
test(S(), SV("12345"), 6, 15, S("not happening"));
test(S(), SV("12345678901234567890"), 0, 0, S());
test(S(), SV("12345678901234567890"), 1, 1, S("2"));
test(S(), SV("12345678901234567890"), 2, 3, S("345"));
test(S(), SV("12345678901234567890"), 12, 13, S("34567890"));
test(S(), SV("12345678901234567890"), 21, 13, S("not happening"));
test(S("12345"), SV(), 0, 0, S("12345"));
test(S("12345"), SV("12345"), 2, 2, S("1234534"));
test(S("12345"), SV("1234567890"), 0, 100, S("123451234567890"));
test(S("12345678901234567890"), SV(), 0, 0, S("12345678901234567890"));
test(S("12345678901234567890"), SV("12345"), 1, 3, S("12345678901234567890234"));
test(S("12345678901234567890"), SV("12345678901234567890"), 5, 10,
S("123456789012345678906789012345"));
}
#endif
{
typedef std::string S;
typedef std::string_view SV;
test_npos(S(), SV(), 0, S());
test_npos(S(), SV(), 1, S());
test_npos(S(), SV("12345"), 0, S("12345"));
test_npos(S(), SV("12345"), 1, S("2345"));
test_npos(S(), SV("12345"), 3, S("45"));
test_npos(S(), SV("12345"), 5, S(""));
test_npos(S(), SV("12345"), 6, S("not happening"));
}
{
typedef std::string S;
typedef std::string_view SV;
S s;
SV sv = "EFGH";
char arr[] = "IJKL";
s.append("CDEF", 0); // calls append(const char *, len)
assert(s == "");
s.clear();
s.append("QRST", 0, std::string::npos); // calls append(string("QRST"), pos, npos)
assert(s == "QRST");
s.clear();
s.append(sv, 0); // calls append(T, pos, npos)
assert(s == sv);
s.clear();
s.append(sv, 0, std::string::npos); // calls append(T, pos, npos)
assert(s == sv);
s.clear();
s.append(arr, 0); // calls append(const char *, len)
assert(s == "");
s.clear();
s.append(arr, 0, std::string::npos); // calls append(string("IJKL"), pos, npos)
assert(s == "IJKL");
s.clear();
s.append(arr, 0); // calls append(const char *, len)
assert(s == "");
s.clear();
{
S s = "ABCD";
SV sv = s;
s.append(sv);
assert(s == "ABCDABCD");
sv = s;
s.append(sv, 0, std::string::npos);
assert(s == "ABCDABCDABCDABCD");
sv = s;
s.append(sv, sv.size());
assert(s == "ABCDABCDABCDABCD");
}
{
S s = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
SV sv = s;
s.append(sv);
assert(s == "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ");
sv = s;
s.append(sv, 0, std::string::npos);
assert(s == "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ");
}
}
}
<|endoftext|>
|
<commit_before>/**
* A server which is responsible for interacting with devices.
*
* @date July 7, 2014
* @author Joeri HERMANS
* @version 0.1
*
* Copyright 2013 Joeri HERMANS
*
* 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.
*/
// BEGIN Includes. ///////////////////////////////////////////////////
// System dependencies.
#include <arpa/inet.h>
#include <cassert>
#include <cstdio>
#include <iostream>
// Application dependencies.
#include <ias/server/device_server.h>
#include <ias/server/session/device_session.h>
#include <ias/logger/logger.h>
// END Includes. /////////////////////////////////////////////////////
inline void DeviceServer::initialize( void ) {
mSocket = nullptr;
mListenThread = nullptr;
mDispatchThread = nullptr;
mFlagRunning = true;
}
void DeviceServer::setSocket( Socket * socket ) {
// Checking the precondition.
assert( socket != nullptr && socket->isConnected() );
mSocket = socket;
}
void DeviceServer::setDeviceIdentifiers( const std::vector<std::string> & i ) {
mDeviceIdentifiers = i;
}
void DeviceServer::startListenThread( void ) {
mListenThread = new std::thread([this](){
ServerSocket * serverSocket;
Session * session;
Socket * socket;
serverSocket = getServerSocket();
while( mFlagRunning && mSocket->isConnected() ) {
socket = serverSocket->acceptSocket(1);
if( socket != nullptr ) {
logi("Starting new device session.");
session = new DeviceSession(socket,
mSocket,
&mConnectedDevices,
&mDeviceIdentifiers);
session->addObserver(this);
mSessions[session] =
new std::thread([session]{
session->run();
session->notifyObservers(session);
delete session;
logi("Device session terminated.");
});
} else if( !serverSocket->isBound() ) {
stop();
}
cleanupFinishingThreads();
}
signalSessions();
mSocket->closeConnection();
while( mSessions.size() > 0 ||
mInactiveThreads.size() > 0 ) {
signalSessions();
cleanupFinishingThreads();
}
});
}
bool DeviceServer::readBytes( char * buffer , const unsigned int n ) {
std::size_t bytesRead;
std::size_t nBytes;
Reader * reader;
// Checking the precondition.
assert( buffer != nullptr && n > 0 );
if( !mSocket->isConnected() ) return ( false );
reader = mSocket->getReader();
bytesRead = 0;
while( bytesRead != n ) {
nBytes = reader->readBytes(buffer + bytesRead,n - bytesRead);
if( nBytes == 0 )
return ( false );
bytesRead += nBytes;
}
return ( true );
}
void DeviceServer::dispatchCommand( void ) {
std::uint8_t deviceLength;
std::uint8_t identifierLength;
std::uint8_t parameterLength;
std::string message;
Reader * reader;
Writer * writer;
if( !mSocket->isConnected() )
stop();
reader = mSocket->getReader();
writer = mSocket->getWriter();
if( !readBytes(reinterpret_cast<char *>(&deviceLength),1) ) return;
if( !readBytes(reinterpret_cast<char *>(&identifierLength),1) ) return;
if( !readBytes(reinterpret_cast<char *>(¶meterLength),1) ) return;
char deviceIdentifier[deviceLength + 1];
char identifier[identifierLength + 1];
char parameter[parameterLength + 1];
if( !readBytes(deviceIdentifier,deviceLength) ) return;
if( !readBytes(identifier,identifierLength) ) return;
if( parameterLength > 0 && !readBytes(parameter,parameterLength) ) return;
deviceIdentifier[deviceLength] = 0;
identifier[identifierLength] = 0;
parameter[parameterLength] = 0;
// Format the message
message += 0x01;
message += identifierLength;
message += parameterLength;
message.append(identifier);
message.append(parameter);
mConnectedDevices.dispatch(deviceIdentifier,message);
}
void DeviceServer::startDispatchThread( void ) {
mDispatchThread = new std::thread([this](){
std::size_t nBytes;
std::uint8_t type;
Reader * reader;
reader = mSocket->getReader();
while( mFlagRunning && mSocket->isConnected() ) {
std::cout << "Waiting for next byte." << std::endl;
nBytes = reader->readByte(reinterpret_cast<char *>(&type));
std::cout << "Byte received: " << std::to_string(type) << std::endl;
if( nBytes == 0 ) {
stop();
} else {
switch(type) {
case 0x01:
dispatchCommand();
break;
case 0xff:
mFlagRunning = false;
break;
default:
stop();
break;
}
}
}
stop();
});
}
void DeviceServer::signalSessions( void ) {
std::map<Session *,std::thread *>::iterator it;
mMutexSessions.lock();
for( it = mSessions.begin() ; it != mSessions.end() ; ++it )
it->first->stop();
mMutexSessions.unlock();
}
void DeviceServer::cleanupFinishingThreads( void ) {
std::thread * t;
while( mInactiveThreads.size() > 0 ) {
t = mInactiveThreads.front();
if( t != nullptr ) {
t->join();
delete t;
}
mInactiveThreads.erase(mInactiveThreads.begin());
}
}
DeviceServer::DeviceServer( ServerSocket * serverSocket,
Socket * socket,
const std::vector<std::string> & devices ) :
Server(serverSocket) {
initialize();
setSocket(socket);
setDeviceIdentifiers(devices);
}
DeviceServer::~DeviceServer( void ) {
join();
}
void DeviceServer::start( void ) {
if( mListenThread == nullptr && mDispatchThread == nullptr ) {
startListenThread();
startDispatchThread();
}
}
void DeviceServer::stop( void ) {
mFlagRunning = false;
mSocket->closeConnection();
getServerSocket()->stopListening();
}
void DeviceServer::join( void ) {
if( mListenThread != nullptr ) {
mListenThread->join();
delete mListenThread;
mListenThread = nullptr;
}
if( mDispatchThread != nullptr ) {
mDispatchThread->join();
delete mDispatchThread;
mDispatchThread = nullptr;
}
}
void DeviceServer::update( void ) {
// Do nothing.
}
void DeviceServer::update( void * argument ) {
std::map<Session *,std::thread *>::iterator it;
Session * session;
// Checking the precondition.
assert( argument != nullptr );
session = static_cast<Session *>(argument);
it = mSessions.find(session);
if( it != mSessions.end() ) {
mInactiveThreads.push_back(it->second);
mMutexSessions.lock();
mSessions.erase(it);
mMutexSessions.unlock();
}
}
<commit_msg>Remove debugging information.<commit_after>/**
* A server which is responsible for interacting with devices.
*
* @date July 7, 2014
* @author Joeri HERMANS
* @version 0.1
*
* Copyright 2013 Joeri HERMANS
*
* 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.
*/
// BEGIN Includes. ///////////////////////////////////////////////////
// System dependencies.
#include <arpa/inet.h>
#include <cassert>
#include <cstdio>
#include <iostream>
// Application dependencies.
#include <ias/server/device_server.h>
#include <ias/server/session/device_session.h>
#include <ias/logger/logger.h>
// END Includes. /////////////////////////////////////////////////////
inline void DeviceServer::initialize( void ) {
mSocket = nullptr;
mListenThread = nullptr;
mDispatchThread = nullptr;
mFlagRunning = true;
}
void DeviceServer::setSocket( Socket * socket ) {
// Checking the precondition.
assert( socket != nullptr && socket->isConnected() );
mSocket = socket;
}
void DeviceServer::setDeviceIdentifiers( const std::vector<std::string> & i ) {
mDeviceIdentifiers = i;
}
void DeviceServer::startListenThread( void ) {
mListenThread = new std::thread([this](){
ServerSocket * serverSocket;
Session * session;
Socket * socket;
serverSocket = getServerSocket();
while( mFlagRunning && mSocket->isConnected() ) {
socket = serverSocket->acceptSocket(1);
if( socket != nullptr ) {
logi("Starting new device session.");
session = new DeviceSession(socket,
mSocket,
&mConnectedDevices,
&mDeviceIdentifiers);
session->addObserver(this);
mSessions[session] =
new std::thread([session]{
session->run();
session->notifyObservers(session);
delete session;
logi("Device session terminated.");
});
} else if( !serverSocket->isBound() ) {
stop();
}
cleanupFinishingThreads();
}
signalSessions();
mSocket->closeConnection();
while( mSessions.size() > 0 ||
mInactiveThreads.size() > 0 ) {
signalSessions();
cleanupFinishingThreads();
}
});
}
bool DeviceServer::readBytes( char * buffer , const unsigned int n ) {
std::size_t bytesRead;
std::size_t nBytes;
Reader * reader;
// Checking the precondition.
assert( buffer != nullptr && n > 0 );
if( !mSocket->isConnected() ) return ( false );
reader = mSocket->getReader();
bytesRead = 0;
while( bytesRead != n ) {
nBytes = reader->readBytes(buffer + bytesRead,n - bytesRead);
if( nBytes == 0 )
return ( false );
bytesRead += nBytes;
}
return ( true );
}
void DeviceServer::dispatchCommand( void ) {
std::uint8_t deviceLength;
std::uint8_t identifierLength;
std::uint8_t parameterLength;
std::string message;
Reader * reader;
Writer * writer;
if( !mSocket->isConnected() )
stop();
reader = mSocket->getReader();
writer = mSocket->getWriter();
if( !readBytes(reinterpret_cast<char *>(&deviceLength),1) ) return;
if( !readBytes(reinterpret_cast<char *>(&identifierLength),1) ) return;
if( !readBytes(reinterpret_cast<char *>(¶meterLength),1) ) return;
char deviceIdentifier[deviceLength + 1];
char identifier[identifierLength + 1];
char parameter[parameterLength + 1];
if( !readBytes(deviceIdentifier,deviceLength) ) return;
if( !readBytes(identifier,identifierLength) ) return;
if( parameterLength > 0 && !readBytes(parameter,parameterLength) ) return;
deviceIdentifier[deviceLength] = 0;
identifier[identifierLength] = 0;
parameter[parameterLength] = 0;
// Format the message
message += 0x01;
message += identifierLength;
message += parameterLength;
message.append(identifier);
message.append(parameter);
mConnectedDevices.dispatch(deviceIdentifier,message);
}
void DeviceServer::startDispatchThread( void ) {
mDispatchThread = new std::thread([this](){
std::size_t nBytes;
std::uint8_t type;
Reader * reader;
reader = mSocket->getReader();
while( mFlagRunning && mSocket->isConnected() ) {
nBytes = reader->readByte(reinterpret_cast<char *>(&type));
if( nBytes == 0 ) {
stop();
} else {
switch(type) {
case 0x01:
dispatchCommand();
break;
default:
stop();
break;
}
}
}
stop();
});
}
void DeviceServer::signalSessions( void ) {
std::map<Session *,std::thread *>::iterator it;
mMutexSessions.lock();
for( it = mSessions.begin() ; it != mSessions.end() ; ++it )
it->first->stop();
mMutexSessions.unlock();
}
void DeviceServer::cleanupFinishingThreads( void ) {
std::thread * t;
while( mInactiveThreads.size() > 0 ) {
t = mInactiveThreads.front();
if( t != nullptr ) {
t->join();
delete t;
}
mInactiveThreads.erase(mInactiveThreads.begin());
}
}
DeviceServer::DeviceServer( ServerSocket * serverSocket,
Socket * socket,
const std::vector<std::string> & devices ) :
Server(serverSocket) {
initialize();
setSocket(socket);
setDeviceIdentifiers(devices);
}
DeviceServer::~DeviceServer( void ) {
join();
}
void DeviceServer::start( void ) {
if( mListenThread == nullptr && mDispatchThread == nullptr ) {
startListenThread();
startDispatchThread();
}
}
void DeviceServer::stop( void ) {
mFlagRunning = false;
mSocket->closeConnection();
getServerSocket()->stopListening();
}
void DeviceServer::join( void ) {
if( mListenThread != nullptr ) {
mListenThread->join();
delete mListenThread;
mListenThread = nullptr;
}
if( mDispatchThread != nullptr ) {
mDispatchThread->join();
delete mDispatchThread;
mDispatchThread = nullptr;
}
}
void DeviceServer::update( void ) {
// Do nothing.
}
void DeviceServer::update( void * argument ) {
std::map<Session *,std::thread *>::iterator it;
Session * session;
// Checking the precondition.
assert( argument != nullptr );
session = static_cast<Session *>(argument);
it = mSessions.find(session);
if( it != mSessions.end() ) {
mInactiveThreads.push_back(it->second);
mMutexSessions.lock();
mSessions.erase(it);
mMutexSessions.unlock();
}
}
<|endoftext|>
|
<commit_before>
// -*- mode: c++; c-basic-offset:4 -*-
// This file is part of libdap, A C++ implementation of the OPeNDAP Data
// Access Protocol.
// Copyright (c) 2002,2003 OPeNDAP, Inc.
// Author: James Gallagher <jgallagher@opendap.org>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.
#include <cppunit/TextTestRunner.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/extensions/HelperMacros.h>
#include <iterator>
#include <string>
#include <algorithm>
#include "GNURegex.h"
#include "HTTPConnect.h"
#include "RCReader.h"
#include "debug.h"
using namespace CppUnit;
using namespace std;
class HTTPConnectTest : public TestFixture {
private:
HTTPConnect *http;
string localhost_url, localhost_pw_url, localhost_digest_pw_url;
string etag;
string lm;
string netcdf_das_url;
protected:
bool re_match(Regex &r, const char *s) {
return r.match(s, strlen(s)) == (int)strlen(s);
}
public:
HTTPConnectTest() {}
~HTTPConnectTest() {}
void setUp () {
putenv("DODS_CACHE_INIT=cache-testsuite/dodsrc");
http = new HTTPConnect(RCReader::instance());
localhost_url = "http://test.opendap.org/test-304.html";
// Two request header values that will generate a 304 response to the
// above URL. The values below much match the etag and last-modified
// time returned by the server. Run this test with DODS_DEBUG defined
// to see the values it's returning.
etag = "\"928ec-157-139c2680\"";
lm = "Wed, 13 Jul 2005 19:32:26 GMT";
localhost_pw_url = "http://jimg:dods_test@test.opendap.org/basic/page.txt";
localhost_digest_pw_url = "http://jimg:dods_digest@test.opendap.org/digest/page.txt";
netcdf_das_url = "http://test.opendap.org/opendap/nph-dods/data/nc/fnoc1.nc.das";
}
void tearDown() {
delete http; http = 0;
}
CPPUNIT_TEST_SUITE( HTTPConnectTest );
CPPUNIT_TEST(read_url_test);
CPPUNIT_TEST(fetch_url_test);
CPPUNIT_TEST(get_response_headers_test);
CPPUNIT_TEST(server_version_test);
CPPUNIT_TEST(type_test);
CPPUNIT_TEST(cache_test);
CPPUNIT_TEST(set_accept_deflate_test);
CPPUNIT_TEST(read_url_password_test);
CPPUNIT_TEST(read_url_password_test2);
#if 0
CPPUNIT_TEST(read_url_password_proxy_test);
#endif
CPPUNIT_TEST_SUITE_END();
void read_url_test() {
vector<string> *resp_h = new vector<string>;;
try {
FILE *dump = fopen("/dev/null", "w");
long status = http->read_url(localhost_url, dump, resp_h);
CPPUNIT_ASSERT(status == 200);
vector<string> request_h;
// First test using a time with if-modified-since
request_h.push_back(string("If-Modified-Since: ") + lm);
status = http->read_url(localhost_url, dump, resp_h, &request_h);
DBG(cerr << "If modified since test, status: " << status << endl);
DBG(copy(resp_h->begin(), resp_h->end(),
ostream_iterator<string>(cerr, "\n")));
CPPUNIT_ASSERT(status == 304);
// Now test an etag
resp_h->clear();
request_h.clear();
request_h.push_back(string("If-None-Match: ") + etag);
status = http->read_url(localhost_url, dump, resp_h, &request_h);
DBG(cerr << "If none match test, status: " << status << endl);
DBG(copy(resp_h->begin(), resp_h->end(),
ostream_iterator<string>(cerr, "\n")));
CPPUNIT_ASSERT(status == 304);
// now test a combined etag and time4
resp_h->clear();
request_h.clear();
request_h.push_back(string("If-None-Match: ") + etag);
request_h.push_back(string("If-Modified-Since: ") + lm);
status = http->read_url(localhost_url, dump, resp_h, &request_h);
DBG(cerr << "Combined test, status: " << status << endl);
DBG(copy(resp_h->begin(), resp_h->end(),
ostream_iterator<string>(cerr, "\n")));
CPPUNIT_ASSERT(status == 304);
delete resp_h; resp_h = 0;
}
catch(Error &e) {
cerr << e.get_error_message() << endl;
delete resp_h; resp_h = 0;
CPPUNIT_ASSERT(!"Should not get an Error");
}
}
void fetch_url_test() {
HTTPResponse *stuff = http->fetch_url(localhost_url);
try {
char c;
CPPUNIT_ASSERT(fread(&c, 1, 1, stuff->get_stream()) == 1
&& !ferror(stuff->get_stream())
&& !feof(stuff->get_stream()));
delete stuff; stuff = 0;
stuff = http->fetch_url(netcdf_das_url);
DBG2(char ln[1024];
while (!feof(stuff->get_stream())) {
fgets(ln, 1024, stuff->get_stream());
cerr << ln;
}
rewind(stuff->get_stream()));
CPPUNIT_ASSERT(fread(&c, 1, 1, stuff->get_stream()) == 1
&& !ferror(stuff->get_stream())
&& !feof(stuff->get_stream()));
delete stuff; stuff = 0;
stuff = http->fetch_url("file:///etc/passwd");
CPPUNIT_ASSERT(fread(&c, 1, 1, stuff->get_stream()) == 1
&& !ferror(stuff->get_stream())
&& !feof(stuff->get_stream()));
delete stuff; stuff = 0;
stuff = http->fetch_url("file://HTTPConnectTest.cc");
CPPUNIT_ASSERT(fread(&c, 1, 1, stuff->get_stream()) == 1
&& !ferror(stuff->get_stream())
&& !feof(stuff->get_stream()));
delete stuff; stuff = 0;
}
catch (InternalErr &e) {
delete stuff; stuff = 0;
cerr << "InternalErr: " << e.get_error_message() << endl;
CPPUNIT_ASSERT(!"Caught a DODS exception from fetch_url");
}
catch (Error &e) {
delete stuff; stuff = 0;
cerr << "Error: " << e.get_error_message() << endl;
CPPUNIT_ASSERT(!"Caught a DODS exception from fetch_url");
}
}
void get_response_headers_test() {
HTTPResponse *r = http->fetch_url(netcdf_das_url);
try {
vector<string> *h = r->get_headers();
DBG(copy(h->begin(), h->end(),
ostream_iterator<string>(cerr, "\n")));
// Should get five or six headers back.
Regex header("XDODS-Server: DAP/.*");
CPPUNIT_ASSERT(re_match(header, (*h)[0].c_str()));
Regex protocol_header("XDAP: .*");
unsigned int num_headers;
if (re_match(protocol_header, (*h)[1].c_str()))
num_headers = 7;
else
num_headers = 5;
CPPUNIT_ASSERT((*h)[4] == "Content-Description: dods_das");
CPPUNIT_ASSERT(h->size() == num_headers);
delete r; r = 0;
}
catch (InternalErr &e) {
delete r; r = 0;
CPPUNIT_ASSERT(!"Caught an exception from get_response_headers");
}
}
void server_version_test() {
Response *r = http->fetch_url(netcdf_das_url);
Regex version("dap/[0-9]+\\.[0-9]+\\.[0-9]+");
try {
CPPUNIT_ASSERT(re_match(version, r->get_version().c_str()));
delete r; r = 0;
}
catch (InternalErr &e) {
delete r; r = 0;
CPPUNIT_ASSERT(!"Caught an exception from server_version");
}
}
void type_test() {
Response *r = http->fetch_url(netcdf_das_url);
try {
CPPUNIT_ASSERT(r->get_type() == dods_das);
delete r; r = 0;
}
catch (InternalErr &e) {
delete r; r = 0;
CPPUNIT_ASSERT(!"Caught an exception from type()");
}
}
void set_credentials_test() {
http->set_credentials("jimg", "was_quit");
Response *stuff = http->fetch_url("http://localhost/secret");
try {
char c;
CPPUNIT_ASSERT(fread(&c, 1, 1, stuff->get_stream()) == 1
&& !ferror(stuff->get_stream())
&& !feof(stuff->get_stream()));
delete stuff; stuff = 0;
}
catch (InternalErr &e) {
delete stuff; stuff = 0;
CPPUNIT_ASSERT(!"Caught exception from output");
}
}
void cache_test() {
DBG(cerr << endl << "Entering Caching tests." << endl);
// The cache-testsuite/dodsrc file turns this off; all the other
// params are set up. It used to be that HTTPConnect had an option to
// turn caching on, but that no longer is present. This hack enables
// caching for this test. 06/18/04 jhrg
http->d_http_cache
= HTTPCache::instance(http->d_rcr->get_dods_cache_root(), false);
CPPUNIT_ASSERT(http->d_http_cache != 0);
http->d_http_cache->set_cache_enabled(true);
fetch_url_test();
get_response_headers_test();
server_version_test();
type_test();
}
void set_accept_deflate_test() {
http->set_accept_deflate(false);
CPPUNIT_ASSERT(count(http->d_request_headers.begin(),
http->d_request_headers.end(),
"Accept-Encoding: deflate") == 0);
http->set_accept_deflate(true);
CPPUNIT_ASSERT(count(http->d_request_headers.begin(),
http->d_request_headers.end(),
"Accept-Encoding: deflate") == 1);
http->set_accept_deflate(true);
CPPUNIT_ASSERT(count(http->d_request_headers.begin(),
http->d_request_headers.end(),
"Accept-Encoding: deflate") == 1);
http->set_accept_deflate(false);
CPPUNIT_ASSERT(count(http->d_request_headers.begin(),
http->d_request_headers.end(),
"Accept-Encoding: deflate") == 0);
}
void read_url_password_test() {
FILE *dump = fopen("/dev/null", "w");
vector<string> *resp_h = new vector<string>;
long status = http->read_url(localhost_pw_url, dump, resp_h);
DBG(cerr << endl << http->d_upstring << endl);
CPPUNIT_ASSERT(http->d_upstring == "jimg:dods_test");
DBG(cerr << "Status: " << status << endl);
CPPUNIT_ASSERT(status == 200);
delete resp_h; resp_h = 0;
}
void read_url_password_test2() {
FILE *dump = fopen("/dev/null", "w");
vector<string> *resp_h = new vector<string>;
long status = http->read_url(localhost_digest_pw_url, dump, resp_h);
DBG(cerr << endl << http->d_upstring << endl);
CPPUNIT_ASSERT(http->d_upstring == "jimg:dods_digest");
DBG(cerr << "Status: " << status << endl);
CPPUNIT_ASSERT(status == 200);
delete resp_h; resp_h = 0;
}
// I'm going to remove this test. All of the other tests now work off of
// test.opendap.org. jhrg 7/13/05
void read_url_password_proxy_test() {
cerr << endl <<
"This test will fail if localhost is not configured as a proxy server\n\
with authentication. The username must be jimg and the password must be\n\
dods_test." << endl;
delete http; http = 0; // get rid of the default object; build a
// special one.
RCReader::delete_instance();
// this dodsrc directs all access through a proxy server. The
// localhost must be configured as such.
putenv("DODS_CONF=cache-testsuite/dodsrc_proxy");
try {
RCReader::initialize_instance(); // work-around pthreads for tests
http = new HTTPConnect(RCReader::instance());
fetch_url_test();
}
catch(Error &e) {
cerr << "Error: " << e.get_error_message() << endl;
CPPUNIT_ASSERT(!"Error");
}
}
};
CPPUNIT_TEST_SUITE_REGISTRATION(HTTPConnectTest);
int
main( int, char** )
{
CppUnit::TextTestRunner runner;
runner.addTest( CppUnit::TestFactoryRegistry::getRegistry().makeTest() );
cerr << "These tests require a working network connection." << endl;
bool wasSuccessful = runner.run( "", false ) ;
return wasSuccessful ? 0 : 1;
}
<commit_msg>HTTPConnectTest: Fixed most, but not all, of the failures. See ticket 552 for more info.<commit_after>
// -*- mode: c++; c-basic-offset:4 -*-
// This file is part of libdap, A C++ implementation of the OPeNDAP Data
// Access Protocol.
// Copyright (c) 2002,2003 OPeNDAP, Inc.
// Author: James Gallagher <jgallagher@opendap.org>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.
#include <cppunit/TextTestRunner.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/extensions/HelperMacros.h>
#include <iterator>
#include <string>
#include <algorithm>
#include "GNURegex.h"
//#define DODS_DEBUG
#include "HTTPConnect.h"
#include "RCReader.h"
#include "debug.h"
using namespace CppUnit;
using namespace std;
class HTTPConnectTest : public TestFixture {
private:
HTTPConnect *http;
string localhost_url, localhost_pw_url, localhost_digest_pw_url;
string etag;
string lm;
string netcdf_das_url;
protected:
bool re_match(Regex &r, const char *s) {
return r.match(s, strlen(s)) == (int)strlen(s);
}
public:
HTTPConnectTest() {}
~HTTPConnectTest() {}
void setUp () {
putenv("DODS_CACHE_INIT=cache-testsuite/dodsrc");
http = new HTTPConnect(RCReader::instance());
localhost_url = "http://test.opendap.org/test-304.html";
// Two request header values that will generate a 304 response to the
// above URL. The values below much match the etag and last-modified
// time returned by the server. Run this test with DODS_DEBUG defined
// to see the values it's returning.
etag = "\"928ec-157-139c2680\"";
lm = "Wed, 13 Jul 2005 19:32:26 GMT";
localhost_pw_url = "http://jimg:dods_test@test.opendap.org/basic/page.txt";
localhost_digest_pw_url = "http://jimg:dods_digest@test.opendap.org/digest/page.txt";
netcdf_das_url = "http://test.opendap.org/opendap/nph-dods/data/nc/fnoc1.nc.das";
}
void tearDown() {
delete http; http = 0;
}
CPPUNIT_TEST_SUITE( HTTPConnectTest );
CPPUNIT_TEST(read_url_test);
CPPUNIT_TEST(fetch_url_test);
CPPUNIT_TEST(get_response_headers_test);
CPPUNIT_TEST(server_version_test);
CPPUNIT_TEST(type_test);
CPPUNIT_TEST(cache_test);
CPPUNIT_TEST(set_accept_deflate_test);
CPPUNIT_TEST(read_url_password_test);
CPPUNIT_TEST(read_url_password_test2);
#if 0
CPPUNIT_TEST(read_url_password_proxy_test);
#endif
CPPUNIT_TEST_SUITE_END();
void read_url_test() {
vector<string> *resp_h = new vector<string>;;
try {
FILE *dump = fopen("/dev/null", "w");
long status = http->read_url(localhost_url, dump, resp_h);
CPPUNIT_ASSERT(status == 200);
vector<string> request_h;
// First test using a time with if-modified-since
request_h.push_back(string("If-Modified-Since: ") + lm);
status = http->read_url(localhost_url, dump, resp_h, &request_h);
DBG(cerr << "If modified since test, status: " << status << endl);
DBG(copy(resp_h->begin(), resp_h->end(),
ostream_iterator<string>(cerr, "\n")));
CPPUNIT_ASSERT(status == 304);
// Now test an etag
resp_h->clear();
request_h.clear();
request_h.push_back(string("If-None-Match: ") + etag);
status = http->read_url(localhost_url, dump, resp_h, &request_h);
DBG(cerr << "If none match test, status: " << status << endl);
DBG(copy(resp_h->begin(), resp_h->end(),
ostream_iterator<string>(cerr, "\n")));
CPPUNIT_ASSERT(status == 304);
// now test a combined etag and time4
resp_h->clear();
request_h.clear();
request_h.push_back(string("If-None-Match: ") + etag);
request_h.push_back(string("If-Modified-Since: ") + lm);
status = http->read_url(localhost_url, dump, resp_h, &request_h);
DBG(cerr << "Combined test, status: " << status << endl);
DBG(copy(resp_h->begin(), resp_h->end(),
ostream_iterator<string>(cerr, "\n")));
CPPUNIT_ASSERT(status == 304);
delete resp_h; resp_h = 0;
}
catch(Error &e) {
cerr << e.get_error_message() << endl;
delete resp_h; resp_h = 0;
CPPUNIT_ASSERT(!"Should not get an Error");
}
}
void fetch_url_test() {
HTTPResponse *stuff = http->fetch_url(localhost_url);
try {
char c;
CPPUNIT_ASSERT(fread(&c, 1, 1, stuff->get_stream()) == 1
&& !ferror(stuff->get_stream())
&& !feof(stuff->get_stream()));
delete stuff; stuff = 0;
stuff = http->fetch_url(netcdf_das_url);
DBG2(char ln[1024];
while (!feof(stuff->get_stream())) {
fgets(ln, 1024, stuff->get_stream());
cerr << ln;
}
rewind(stuff->get_stream()));
CPPUNIT_ASSERT(fread(&c, 1, 1, stuff->get_stream()) == 1
&& !ferror(stuff->get_stream())
&& !feof(stuff->get_stream()));
delete stuff; stuff = 0;
stuff = http->fetch_url("file:///etc/passwd");
CPPUNIT_ASSERT(fread(&c, 1, 1, stuff->get_stream()) == 1
&& !ferror(stuff->get_stream())
&& !feof(stuff->get_stream()));
delete stuff; stuff = 0;
stuff = http->fetch_url("file://HTTPConnectTest.cc");
CPPUNIT_ASSERT(fread(&c, 1, 1, stuff->get_stream()) == 1
&& !ferror(stuff->get_stream())
&& !feof(stuff->get_stream()));
delete stuff; stuff = 0;
}
catch (InternalErr &e) {
delete stuff; stuff = 0;
cerr << "InternalErr: " << e.get_error_message() << endl;
CPPUNIT_ASSERT(!"Caught a DODS exception from fetch_url");
}
catch (Error &e) {
delete stuff; stuff = 0;
cerr << "Error: " << e.get_error_message() << endl;
CPPUNIT_ASSERT(!"Caught a DODS exception from fetch_url");
}
}
void get_response_headers_test() {
HTTPResponse *r = http->fetch_url(netcdf_das_url);
try {
vector<string> *h = r->get_headers();
DBG(copy(h->begin(), h->end(),
ostream_iterator<string>(cerr, "\n")));
// Should get five or six headers back.
Regex header("XDODS-Server: DAP[0-4]?/.*");
DBG(cerr << "get_response_headers_test(), (*h)[0]: "
<< (*h)[0] << endl);
CPPUNIT_ASSERT(re_match(header, (*h)[0].c_str()));
Regex protocol_header("XDAP: .*");
unsigned int num_headers;
if (re_match(protocol_header, (*h)[2].c_str()))
num_headers = 7;
else
num_headers = 5;
DBG(cerr << "num_headers: " << num_headers << endl);
DBG(cerr << "h->size(): " << h->size() << endl);
DBG(cerr << "(*h)[num_headers-1]: " << (*h)[num_headers-1] << endl);
CPPUNIT_ASSERT((*h)[num_headers-1] == "Content-Description: dods_das");
#if 0
CPPUNIT_ASSERT(h->size() == num_headers);
#endif
delete r; r = 0;
}
catch (InternalErr &e) {
delete r; r = 0;
CPPUNIT_ASSERT(!"Caught an exception from get_response_headers");
}
}
void server_version_test() {
Response *r = http->fetch_url(netcdf_das_url);
Regex version("dap[0-4]?/[0-9]+\\.[0-9]+\\.[0-9]+");
try {
DBG(cerr << "r->get_version().c_str(): "
<< r->get_version().c_str() << endl);
CPPUNIT_ASSERT(re_match(version, r->get_version().c_str()));
delete r; r = 0;
}
catch (InternalErr &e) {
delete r; r = 0;
CPPUNIT_ASSERT(!"Caught an exception from server_version");
}
}
void type_test() {
Response *r = http->fetch_url(netcdf_das_url);
try {
CPPUNIT_ASSERT(r->get_type() == dods_das);
delete r; r = 0;
}
catch (InternalErr &e) {
delete r; r = 0;
CPPUNIT_ASSERT(!"Caught an exception from type()");
}
}
void set_credentials_test() {
http->set_credentials("jimg", "was_quit");
Response *stuff = http->fetch_url("http://localhost/secret");
try {
char c;
CPPUNIT_ASSERT(fread(&c, 1, 1, stuff->get_stream()) == 1
&& !ferror(stuff->get_stream())
&& !feof(stuff->get_stream()));
delete stuff; stuff = 0;
}
catch (InternalErr &e) {
delete stuff; stuff = 0;
CPPUNIT_ASSERT(!"Caught exception from output");
}
}
void cache_test() {
DBG(cerr << endl << "Entering Caching tests." << endl);
// The cache-testsuite/dodsrc file turns this off; all the other
// params are set up. It used to be that HTTPConnect had an option to
// turn caching on, but that no longer is present. This hack enables
// caching for this test. 06/18/04 jhrg
http->d_http_cache
= HTTPCache::instance(http->d_rcr->get_dods_cache_root(), false);
CPPUNIT_ASSERT(http->d_http_cache != 0);
http->d_http_cache->set_cache_enabled(true);
fetch_url_test();
get_response_headers_test();
server_version_test();
type_test();
}
void set_accept_deflate_test() {
http->set_accept_deflate(false);
CPPUNIT_ASSERT(count(http->d_request_headers.begin(),
http->d_request_headers.end(),
"Accept-Encoding: deflate") == 0);
http->set_accept_deflate(true);
CPPUNIT_ASSERT(count(http->d_request_headers.begin(),
http->d_request_headers.end(),
"Accept-Encoding: deflate") == 1);
http->set_accept_deflate(true);
CPPUNIT_ASSERT(count(http->d_request_headers.begin(),
http->d_request_headers.end(),
"Accept-Encoding: deflate") == 1);
http->set_accept_deflate(false);
CPPUNIT_ASSERT(count(http->d_request_headers.begin(),
http->d_request_headers.end(),
"Accept-Encoding: deflate") == 0);
}
void read_url_password_test() {
FILE *dump = fopen("/dev/null", "w");
vector<string> *resp_h = new vector<string>;
long status = http->read_url(localhost_pw_url, dump, resp_h);
DBG(cerr << endl << http->d_upstring << endl);
CPPUNIT_ASSERT(http->d_upstring == "jimg:dods_test");
DBG(cerr << "Status: " << status << endl);
CPPUNIT_ASSERT(status == 200);
delete resp_h; resp_h = 0;
}
void read_url_password_test2() {
FILE *dump = fopen("/dev/null", "w");
vector<string> *resp_h = new vector<string>;
long status = http->read_url(localhost_digest_pw_url, dump, resp_h);
DBG(cerr << endl << http->d_upstring << endl);
CPPUNIT_ASSERT(http->d_upstring == "jimg:dods_digest");
DBG(cerr << "Status: " << status << endl);
CPPUNIT_ASSERT(status == 200);
delete resp_h; resp_h = 0;
}
// I'm going to remove this test. All of the other tests now work off of
// test.opendap.org. jhrg 7/13/05
void read_url_password_proxy_test() {
cerr << endl <<
"This test will fail if localhost is not configured as a proxy server\n\
with authentication. The username must be jimg and the password must be\n\
dods_test." << endl;
delete http; http = 0; // get rid of the default object; build a
// special one.
RCReader::delete_instance();
// this dodsrc directs all access through a proxy server. The
// localhost must be configured as such.
putenv("DODS_CONF=cache-testsuite/dodsrc_proxy");
try {
RCReader::initialize_instance(); // work-around pthreads for tests
http = new HTTPConnect(RCReader::instance());
fetch_url_test();
}
catch(Error &e) {
cerr << "Error: " << e.get_error_message() << endl;
CPPUNIT_ASSERT(!"Error");
}
}
};
CPPUNIT_TEST_SUITE_REGISTRATION(HTTPConnectTest);
int
main( int, char** )
{
CppUnit::TextTestRunner runner;
runner.addTest( CppUnit::TestFactoryRegistry::getRegistry().makeTest() );
cerr << "These tests require a working network connection." << endl;
bool wasSuccessful = runner.run( "", false ) ;
return wasSuccessful ? 0 : 1;
}
<|endoftext|>
|
<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------
// RUN: cat %s | %cling | FileCheck %s
// Checks:
// Savannah #99210 https://savannah.cern.ch/bugs/index.php?99210
// Savannah #99234 https://savannah.cern.ch/bugs/?99234
// Let's start with simpler example pointing out the issue:
int i = 1; i++; int j = i;
j
// CHECK: (int) 2
extern "C" int printf(const char*,...);
.rawInput
class RAII {
public:
RAII(int i) { I = new int(i); printf("RAII%d\n", ++InstanceCount); };
int incr() { return ++(*I); }
int get() { return *I; }
~RAII() { delete I; printf("~RAII%d\n", InstanceCount--); }
private:
RAII(RAII&) {throw;};
RAII& operator=(RAII) {throw;}
int* I;
static int InstanceCount; // will notice object copy
};
int RAII::InstanceCount = 0;
.rawInput
// This works because each line ends up in a separate wrapper
RAII R(12); // CHECK: RAII1
R.get();
int res = R.incr() // CHECK: 13
// This does not work because the decls and their inits are run before the
// call to R2.incr(), i.e. the second statement in the line.
// Savannah #99210 https://savannah.cern.ch/bugs/index.php?99210
RAII R2(42);R2.incr();int res2 = R2.get()
// CHECK: RAII2
// CHECK: 43
.q
// CHECK: ~RAII2
// CHECK: ~RAII1
// Enforce that only two objects got ever constructed:
// CHECK-NOT: ~RAII0
<commit_msg>Windows: Trivial fix for initorder.C.<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------
// RUN: cat %s | %cling | FileCheck %s
// Checks:
// Savannah #99210 https://savannah.cern.ch/bugs/index.php?99210
// Savannah #99234 https://savannah.cern.ch/bugs/?99234
// Let's start with simpler example pointing out the issue:
int i = 1; i++; int j = i;
j
// CHECK: (int) 2
extern "C" int printf(const char*,...);
.rawInput
class RAII {
public:
RAII(int i) { I = new int(i); printf("RAII%d\n", ++InstanceCount); };
int incr() { return ++(*I); }
int get() { return *I; }
~RAII() { delete I; printf("~RAII%d\n", InstanceCount--); }
private:
RAII(RAII&);
RAII& operator=(RAII);
int* I;
static int InstanceCount; // will notice object copy
};
int RAII::InstanceCount = 0;
.rawInput
// This works because each line ends up in a separate wrapper
RAII R(12); // CHECK: RAII1
R.get();
int res = R.incr() // CHECK: 13
// This does not work because the decls and their inits are run before the
// call to R2.incr(), i.e. the second statement in the line.
// Savannah #99210 https://savannah.cern.ch/bugs/index.php?99210
RAII R2(42);R2.incr();int res2 = R2.get()
// CHECK: RAII2
// CHECK: 43
.q
// CHECK: ~RAII2
// CHECK: ~RAII1
// Enforce that only two objects got ever constructed:
// CHECK-NOT: ~RAII0
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2014 Alexander Rössler
** License: LGPL version 2.1
**
** This file is part of QtQuickVcp.
**
** All rights reserved. This program and the accompanying materials
** are made available under the terms of the GNU Lesser General Public License
** (LGPL) version 2.1 which accompanies this distribution, and is available at
** http://www.gnu.org/licenses/lgpl-2.1.html
**
** This library is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
** Lesser General Public License for more details.
**
** Contributors:
** Alexander Rössler @ The Cool Tool GmbH <mail DOT aroessler AT gmail DOT com>
**
****************************************************************************/
#include "qapplicationfile.h"
QApplicationFile::QApplicationFile(QObject *parent) :
AbstractServiceImplementation(parent),
m_uri(""),
m_localFilePath(""),
m_remoteFilePath(""),
m_localPath(""),
m_remotePath(""),
m_transferState(NoTransfer),
m_error(NoError),
m_errorString(""),
m_progress(0.0),
m_networkReady(false),
m_model(NULL),
m_networkManager(NULL),
m_file(NULL),
m_ftp(NULL)
{
m_localPath = generateTempPath();
m_model = new QApplicationFileModel(this);
m_networkManager = new QNetworkAccessManager(this);
connect(m_networkManager, SIGNAL(networkAccessibleChanged(QNetworkAccessManager::NetworkAccessibility)),
this, SLOT(networkAccessibleChanged(QNetworkAccessManager::NetworkAccessibility)));
if (m_networkManager->networkAccessible() == QNetworkAccessManager::Accessible)
{
initializeFtp();
}
}
QApplicationFile::~QApplicationFile()
{
cleanupTempPath();
cleanupFtp();
cleanupFile();
m_networkManager->deleteLater();
m_model->deleteLater();
}
void QApplicationFile::startUpload()
{
QUrl url;
QFileInfo fileInfo(QUrl(m_localFilePath).toLocalFile());
QString remotePath;
if (!ready() || (m_transferState != NoTransfer))
{
return;
}
url.setUrl(m_uri + "/" + fileInfo.fileName());
remotePath = QUrl(m_remotePath).toLocalFile();
m_remoteFilePath = QUrl::fromLocalFile(QDir(remotePath).filePath(fileInfo.fileName())).toString();
emit remoteFilePathChanged(m_remoteFilePath);
m_file = new QFile(fileInfo.filePath(), this);
if (m_file->open(QIODevice::ReadOnly))
{
m_ftp->connectToHost(url.host(), url.port());
m_ftp->login();
m_ftp->put(m_file, fileInfo.fileName(), QFtp::Binary);
m_ftp->close();
m_progress = 0.0;
emit progressChanged(m_progress);
updateState(UploadRunning);
updateError(NoError, "");
}
else
{
updateState(Error);
updateError(FileError, m_file->errorString());
}
}
void QApplicationFile::startDownload()
{
QUrl url;
QDir dir;
QString localFilePath;
QString remoteFilePath;
QString remotePath;
QString fileName;
if (!ready() || (m_transferState != NoTransfer))
{
return;
}
remoteFilePath = QUrl(m_remoteFilePath).toLocalFile();
remotePath = QUrl(m_remotePath).toLocalFile();
fileName = remoteFilePath.mid(remotePath.length() + 1);
url.setUrl(m_uri + "/" + fileName);
localFilePath = applicationFilePath(fileName);
m_localFilePath = QUrl::fromLocalFile(localFilePath).toString();
emit localFilePathChanged(m_localFilePath);
QFileInfo fileInfo(localFilePath);
if (!dir.mkpath(fileInfo.absolutePath()))
{
updateState(Error);
updateError(FileError, tr("Cannot create directory"));
return;
}
m_file = new QFile(localFilePath, this);
if (m_file->open(QIODevice::WriteOnly))
{
m_ftp->connectToHost(url.host(), url.port());
m_ftp->login();
m_ftp->get(fileName, m_file, QFtp::Binary);
m_ftp->close();
m_progress = 0.0;
emit progressChanged(m_progress);
updateState(DownloadRunning);
updateError(NoError, "");
}
else
{
updateState(Error);
updateError(FileError, m_file->errorString());
}
}
void QApplicationFile::refreshFiles()
{
QUrl url(m_uri);
if (!ready() || (m_transferState != NoTransfer))
{
return;
}
m_model->clear();
m_ftp->connectToHost(url.host(), url.port());
m_ftp->login();
m_ftp->list();
m_ftp->close();
updateState(RefreshRunning);
}
void QApplicationFile::removeFile(QString name)
{
QUrl url(m_uri);
if (!ready() || (m_transferState != NoTransfer))
{
return;
}
m_ftp->connectToHost(url.host(), url.port());
m_ftp->login();
m_ftp->remove(name);
m_ftp->close();
updateState(RemoveRunning);
}
void QApplicationFile::abort()
{
if (!m_ftp)
{
return;
}
updateState(NoTransfer);
m_ftp->abort();
m_ftp->close();
}
void QApplicationFile::clearError()
{
updateState(NoTransfer);
updateError(NoError, "");
}
void QApplicationFile::updateState(QApplicationFile::TransferState state)
{
if (state != m_transferState)
{
m_transferState = state;
emit transferStateChanged(m_transferState);
}
}
void QApplicationFile::updateError(QApplicationFile::TransferError error, const QString &errorString)
{
if (m_errorString != errorString)
{
m_errorString = errorString;
emit errorStringChanged(m_errorString);
}
if (m_error != error)
{
m_error = error;
emit errorChanged(m_error);
}
}
QString QApplicationFile::generateTempPath()
{
return QUrl::fromLocalFile(QString("%1/machinekit-%2").arg(QDir::tempPath())
.arg(QCoreApplication::applicationPid())).toString();
}
void QApplicationFile::cleanupTempPath()
{
QDir dir(m_localPath);
dir.removeRecursively();
}
QString QApplicationFile::applicationFilePath(const QString &fileName)
{
return QDir(QUrl(m_localPath).toLocalFile()).filePath(fileName);
}
void QApplicationFile::initializeFtp()
{
m_ftp = new QFtp(this);
connect(m_ftp, SIGNAL(commandFinished(int,bool)),
this, SLOT(ftpCommandFinished(int,bool)));
connect(m_ftp, SIGNAL(listInfo(QUrlInfo)),
this, SLOT(addToList(QUrlInfo)));
connect(m_ftp, SIGNAL(dataTransferProgress(qint64,qint64)),
this, SLOT(transferProgress(qint64,qint64)));
m_networkReady = true;
emit readyChanged(m_networkReady);
}
void QApplicationFile::cleanupFtp()
{
if (m_ftp == NULL)
{
return;
}
m_ftp->abort();
m_ftp->deleteLater();
m_ftp = NULL;
m_networkReady = false;
emit readyChanged(m_networkReady);
}
void QApplicationFile::cleanupFile()
{
if (m_file == NULL)
{
return;
}
m_file->close();
m_file->deleteLater();
m_file = NULL;
}
void QApplicationFile::transferProgress(qint64 bytesSent, qint64 bytesTotal)
{
m_progress = (double)bytesSent / (double)bytesTotal;
emit progressChanged(m_progress);
}
void QApplicationFile::networkAccessibleChanged(QNetworkAccessManager::NetworkAccessibility accesible)
{
if (accesible == QNetworkAccessManager::Accessible)
{
initializeFtp();
}
else
{
cleanupFtp();
}
}
void QApplicationFile::addToList(const QUrlInfo &urlInfo)
{
QApplicationFileItem *item;
if (!urlInfo.isDir()) // for now disable folders
{
item = new QApplicationFileItem();
item->setName(urlInfo.name());
item->setSize(urlInfo.size());
item->setOwner(urlInfo.owner());
item->setGroup(urlInfo.group());
item->setLastModified(urlInfo.lastModified());
item->setDir(urlInfo.isDir());
m_model->addItem(item);
}
}
void QApplicationFile::ftpCommandFinished(int, bool error)
{
if (error)
{
cleanupFile();
m_ftp->close();
if (m_transferState != NoTransfer) // may be a user abort operation
{
updateState(Error);
updateError(FtpError, m_ftp->errorString());
}
return;
}
if (m_ftp->currentCommand() == QFtp::Get)
{
cleanupFile();
emit downloadFinished();
updateState(NoTransfer);
return;
}
if (m_ftp->currentCommand() == QFtp::Put)
{
cleanupFile();
emit uploadFinished();
updateState(NoTransfer);
refreshFiles();
return;
}
if (m_ftp->currentCommand() == QFtp::List)
{
emit refreshFinished();
updateState(NoTransfer);
return;
}
if (m_ftp->currentCommand() == QFtp::Remove)
{
emit removeFinished();
updateState(NoTransfer);
refreshFiles();
}
}
<commit_msg>ApplicationFile: fix ftp urls<commit_after>/****************************************************************************
**
** Copyright (C) 2014 Alexander Rössler
** License: LGPL version 2.1
**
** This file is part of QtQuickVcp.
**
** All rights reserved. This program and the accompanying materials
** are made available under the terms of the GNU Lesser General Public License
** (LGPL) version 2.1 which accompanies this distribution, and is available at
** http://www.gnu.org/licenses/lgpl-2.1.html
**
** This library is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
** Lesser General Public License for more details.
**
** Contributors:
** Alexander Rössler @ The Cool Tool GmbH <mail DOT aroessler AT gmail DOT com>
**
****************************************************************************/
#include "qapplicationfile.h"
QApplicationFile::QApplicationFile(QObject *parent) :
AbstractServiceImplementation(parent),
m_uri(""),
m_localFilePath(""),
m_remoteFilePath(""),
m_localPath(""),
m_remotePath(""),
m_transferState(NoTransfer),
m_error(NoError),
m_errorString(""),
m_progress(0.0),
m_networkReady(false),
m_model(NULL),
m_networkManager(NULL),
m_file(NULL),
m_ftp(NULL)
{
m_localPath = generateTempPath();
m_model = new QApplicationFileModel(this);
m_networkManager = new QNetworkAccessManager(this);
connect(m_networkManager, SIGNAL(networkAccessibleChanged(QNetworkAccessManager::NetworkAccessibility)),
this, SLOT(networkAccessibleChanged(QNetworkAccessManager::NetworkAccessibility)));
if (m_networkManager->networkAccessible() == QNetworkAccessManager::Accessible)
{
initializeFtp();
}
}
QApplicationFile::~QApplicationFile()
{
cleanupTempPath();
cleanupFtp();
cleanupFile();
m_networkManager->deleteLater();
m_model->deleteLater();
}
void QApplicationFile::startUpload()
{
QUrl url;
QFileInfo fileInfo(QUrl(m_localFilePath).toLocalFile());
QString remotePath;
if (!ready() || (m_transferState != NoTransfer))
{
return;
}
url.setUrl(m_uri);
remotePath = QUrl(m_remotePath).toLocalFile();
m_remoteFilePath = QUrl::fromLocalFile(QDir(remotePath).filePath(fileInfo.fileName())).toString();
emit remoteFilePathChanged(m_remoteFilePath);
m_file = new QFile(fileInfo.filePath(), this);
if (m_file->open(QIODevice::ReadOnly))
{
m_ftp->connectToHost(url.host(), url.port());
m_ftp->login();
m_ftp->put(m_file, fileInfo.fileName(), QFtp::Binary);
m_ftp->close();
m_progress = 0.0;
emit progressChanged(m_progress);
updateState(UploadRunning);
updateError(NoError, "");
}
else
{
updateState(Error);
updateError(FileError, m_file->errorString());
}
}
void QApplicationFile::startDownload()
{
QUrl url;
QDir dir;
QString localFilePath;
QString remoteFilePath;
QString remotePath;
QString fileName;
if (!ready() || (m_transferState != NoTransfer))
{
return;
}
remoteFilePath = QUrl(m_remoteFilePath).toLocalFile();
remotePath = QUrl(m_remotePath).toLocalFile();
fileName = remoteFilePath.mid(remotePath.length() + 1);
url.setUrl(m_uri);
localFilePath = applicationFilePath(fileName);
m_localFilePath = QUrl::fromLocalFile(localFilePath).toString();
emit localFilePathChanged(m_localFilePath);
QFileInfo fileInfo(localFilePath);
if (!dir.mkpath(fileInfo.absolutePath()))
{
updateState(Error);
updateError(FileError, tr("Cannot create directory"));
return;
}
m_file = new QFile(localFilePath, this);
if (m_file->open(QIODevice::WriteOnly))
{
m_ftp->connectToHost(url.host(), url.port());
m_ftp->login();
m_ftp->get(fileName, m_file, QFtp::Binary);
m_ftp->close();
m_progress = 0.0;
emit progressChanged(m_progress);
updateState(DownloadRunning);
updateError(NoError, "");
}
else
{
updateState(Error);
updateError(FileError, m_file->errorString());
}
}
void QApplicationFile::refreshFiles()
{
QUrl url(m_uri);
if (!ready() || (m_transferState != NoTransfer))
{
return;
}
m_model->clear();
m_ftp->connectToHost(url.host(), url.port());
m_ftp->login();
m_ftp->list();
m_ftp->close();
updateState(RefreshRunning);
}
void QApplicationFile::removeFile(QString name)
{
QUrl url(m_uri);
if (!ready() || (m_transferState != NoTransfer))
{
return;
}
m_ftp->connectToHost(url.host(), url.port());
m_ftp->login();
m_ftp->remove(name);
m_ftp->close();
updateState(RemoveRunning);
}
void QApplicationFile::abort()
{
if (!m_ftp)
{
return;
}
updateState(NoTransfer);
m_ftp->abort();
m_ftp->close();
}
void QApplicationFile::clearError()
{
updateState(NoTransfer);
updateError(NoError, "");
}
void QApplicationFile::updateState(QApplicationFile::TransferState state)
{
if (state != m_transferState)
{
m_transferState = state;
emit transferStateChanged(m_transferState);
}
}
void QApplicationFile::updateError(QApplicationFile::TransferError error, const QString &errorString)
{
if (m_errorString != errorString)
{
m_errorString = errorString;
emit errorStringChanged(m_errorString);
}
if (m_error != error)
{
m_error = error;
emit errorChanged(m_error);
}
}
QString QApplicationFile::generateTempPath()
{
return QUrl::fromLocalFile(QString("%1/machinekit-%2").arg(QDir::tempPath())
.arg(QCoreApplication::applicationPid())).toString();
}
void QApplicationFile::cleanupTempPath()
{
QDir dir(m_localPath);
dir.removeRecursively();
}
QString QApplicationFile::applicationFilePath(const QString &fileName)
{
return QDir(QUrl(m_localPath).toLocalFile()).filePath(fileName);
}
void QApplicationFile::initializeFtp()
{
m_ftp = new QFtp(this);
connect(m_ftp, SIGNAL(commandFinished(int,bool)),
this, SLOT(ftpCommandFinished(int,bool)));
connect(m_ftp, SIGNAL(listInfo(QUrlInfo)),
this, SLOT(addToList(QUrlInfo)));
connect(m_ftp, SIGNAL(dataTransferProgress(qint64,qint64)),
this, SLOT(transferProgress(qint64,qint64)));
m_networkReady = true;
emit readyChanged(m_networkReady);
}
void QApplicationFile::cleanupFtp()
{
if (m_ftp == NULL)
{
return;
}
m_ftp->abort();
m_ftp->deleteLater();
m_ftp = NULL;
m_networkReady = false;
emit readyChanged(m_networkReady);
}
void QApplicationFile::cleanupFile()
{
if (m_file == NULL)
{
return;
}
m_file->close();
m_file->deleteLater();
m_file = NULL;
}
void QApplicationFile::transferProgress(qint64 bytesSent, qint64 bytesTotal)
{
m_progress = (double)bytesSent / (double)bytesTotal;
emit progressChanged(m_progress);
}
void QApplicationFile::networkAccessibleChanged(QNetworkAccessManager::NetworkAccessibility accesible)
{
if (accesible == QNetworkAccessManager::Accessible)
{
initializeFtp();
}
else
{
cleanupFtp();
}
}
void QApplicationFile::addToList(const QUrlInfo &urlInfo)
{
QApplicationFileItem *item;
if (!urlInfo.isDir()) // for now disable folders
{
item = new QApplicationFileItem();
item->setName(urlInfo.name());
item->setSize(urlInfo.size());
item->setOwner(urlInfo.owner());
item->setGroup(urlInfo.group());
item->setLastModified(urlInfo.lastModified());
item->setDir(urlInfo.isDir());
m_model->addItem(item);
}
}
void QApplicationFile::ftpCommandFinished(int, bool error)
{
if (error)
{
cleanupFile();
m_ftp->close();
if (m_transferState != NoTransfer) // may be a user abort operation
{
updateState(Error);
updateError(FtpError, m_ftp->errorString());
}
return;
}
if (m_ftp->currentCommand() == QFtp::Get)
{
cleanupFile();
emit downloadFinished();
updateState(NoTransfer);
return;
}
if (m_ftp->currentCommand() == QFtp::Put)
{
cleanupFile();
emit uploadFinished();
updateState(NoTransfer);
refreshFiles();
return;
}
if (m_ftp->currentCommand() == QFtp::List)
{
emit refreshFinished();
updateState(NoTransfer);
return;
}
if (m_ftp->currentCommand() == QFtp::Remove)
{
emit removeFinished();
updateState(NoTransfer);
refreshFiles();
}
}
<|endoftext|>
|
<commit_before>/*
* thread.hpp
*
* Created on: Oct 04, 2013
* Author: philip
*/
/*
#include "irrlight/scene/thread.hpp"
*/
//TODO KILL BOOST
#ifndef _IRRLIGHT_SCENE_THREAD_HPP_
#define _IRRLIGHT_SCENE_THREAD_HPP_
#include "irrlicht.h"
#include "kul/except.hpp"
#include "kul/threads.hpp"
#include "irrlight/scene.hpp"
using namespace irr;
namespace irrlight{
class SceneThreadException : public kul::Exception{
public:
SceneThreadException(const char*f, const int l, std::string s) : kul::Exception(f, l, s){}
};
class SceneThread {
public:
SceneThread(AScene& aScene) throw(SceneThreadException)
: aScene(aScene), device(irr::createDevice(video::EDT_NULL, core::dimension2d<u32>(512, 384))), ref(*this), thread(ref){
this->check();
thread.run();
}
~SceneThread() {
thread.interrupt();
}
IrrlichtDevice * getDevice(){ return this->device.get();}
AScene * getScene() { return &this->aScene;}
bool isFinished(){
return thread.finished();
}
void operator()() { go(); }
protected:
AScene& aScene;
std::shared_ptr<IrrlichtDevice> device;
kul::Ref<SceneThread> ref;
kul::Thread thread;
void go(){
KLOG(INFO);
thread.sleep(1000);
this->aScene.setUp(this->getDevice());
}
SceneThread();
void check() throw(SceneThreadException){
if (!&aScene || !&device){
throw SceneThreadException(__FILE__, __LINE__, "Scene or device cannot be null");
}
}
// prevent copying and assignment; not implemented
SceneThread& operator=(const AScene &);
SceneThread& operator=(IrrlichtDevice &);
};
class GUISceneThread : public SceneThread{
public:
GUISceneThread(AGUIScene & aGUIScene): SceneThread (aGUIScene){}
~GUISceneThread(){}
void operator()(){
go();
}
protected:
void go(){
((AGUIScene*)this->getScene())->setUpUI(this->getDevice()->getGUIEnvironment());
}
};
};
#endif /* _IRRLIGHT_SCENE_THREAD_HPP_ */
<commit_msg>Update thread.hpp<commit_after>/**
./inc/irrlight/scene/thread.hpp
Created on: 16 May 2013
Copyright (c) 2013, Philip Deegan
This file is part of irrlight.
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, see <http://www.gnu.org/licenses/>.
*/
#ifndef _IRRLIGHT_SCENE_THREAD_HPP_
#define _IRRLIGHT_SCENE_THREAD_HPP_
#include "irrlicht.h"
#include "kul/except.hpp"
#include "kul/threads.hpp"
#include "irrlight/scene.hpp"
using namespace irr;
namespace irrlight{
class SceneThreadException : public kul::Exception{
public:
SceneThreadException(const char*f, const int l, std::string s) : kul::Exception(f, l, s){}
};
class SceneThread {
public:
SceneThread(AScene& aScene) throw(SceneThreadException)
: aScene(aScene), device(irr::createDevice(video::EDT_NULL, core::dimension2d<u32>(512, 384))), ref(*this), thread(ref){
this->check();
thread.run();
}
~SceneThread() {
thread.interrupt();
}
IrrlichtDevice * getDevice(){ return this->device.get();}
AScene * getScene() { return &this->aScene;}
bool isFinished(){
return thread.finished();
}
void operator()() { go(); }
protected:
AScene& aScene;
std::shared_ptr<IrrlichtDevice> device;
kul::Ref<SceneThread> ref;
kul::Thread thread;
void go(){
KLOG(INFO);
thread.sleep(1000);
this->aScene.setUp(this->getDevice());
}
SceneThread();
void check() throw(SceneThreadException){
if (!&aScene || !&device){
throw SceneThreadException(__FILE__, __LINE__, "Scene or device cannot be null");
}
}
// prevent copying and assignment; not implemented
SceneThread& operator=(const AScene &);
SceneThread& operator=(IrrlichtDevice &);
};
class GUISceneThread : public SceneThread{
public:
GUISceneThread(AGUIScene & aGUIScene): SceneThread (aGUIScene){}
~GUISceneThread(){}
void operator()(){
go();
}
protected:
void go(){
((AGUIScene*)this->getScene())->setUpUI(this->getDevice()->getGUIEnvironment());
}
};
};
#endif /* _IRRLIGHT_SCENE_THREAD_HPP_ */
<|endoftext|>
|
<commit_before>/*******************************************************************************
*
* MIT License
*
* Copyright (c) 2017 Advanced Micro Devices, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*******************************************************************************/
#ifndef GUARD_MIOPEN_LOCK_FILE_HPP_
#define GUARD_MIOPEN_LOCK_FILE_HPP_
#include <boost/filesystem.hpp>
#include <boost/interprocess/sync/file_lock.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <chrono>
#include <fstream>
#include <shared_mutex>
#include <mutex>
namespace miopen {
// LockFile class is a wrapper around boost::interprocess::file_lock providing MT-safety.
// One process should never have more than one instance of this class with same path at the same
// time. It may lead to undefined behaviour on Windows.
// Also on windows mutex can be removed because file locks are MT-safe there.
class LockFile
{
private:
class PassKey
{
};
public:
LockFile(const char* path, PassKey)
{
std::ofstream{path};
flock = path;
}
LockFile(const LockFile&) = delete;
LockFile operator=(const LockFile&) = delete;
void lock()
{
std::lock(access_mutex, flock);
}
void lock_shared()
{
access_mutex.lock_shared();
flock.lock_sharable();
}
bool try_lock()
{
return std::try_lock(access_mutex, flock);
}
bool try_lock_shared()
{
if(!access_mutex.try_lock_shared())
return false;
if(!flock.try_lock_sharable())
{
access_mutex.unlock_shared();
return false;
}
return true;
}
void unlock()
{
flock.unlock();
access_mutex.unlock();
}
void unlock_shared()
{
flock.unlock_sharable();
access_mutex.unlock_shared();
}
static LockFile& Get(const char* path);
template <class TDuration>
bool try_lock_for(TDuration duration)
{
if(!access_mutex.try_lock_for(duration))
return false;
if(!flock.timed_lock(ToPTime(duration)))
{
access_mutex.unlock();
return false;
}
return true;
}
template <class TDuration>
bool try_lock_shared_for(TDuration duration)
{
if(!access_mutex.try_lock_shared_for(duration))
return false;
if(!flock.timed_lock_sharable(ToPTime(duration)))
{
access_mutex.unlock();
return false;
}
return true;
}
template <class TPoint>
bool try_lock_until(TPoint point)
{
return try_lock_for(point - std::chrono::system_clock::now());
}
template <class TPoint>
bool try_lock_shared_until(TPoint point)
{
return try_lock_shared_for(point - std::chrono::system_clock::now());
}
private:
std::shared_timed_mutex access_mutex;
boost::interprocess::file_lock flock;
static std::map<std::string, LockFile>& LockFiles()
{
static std::map<std::string, LockFile> lock_files;
return lock_files;
}
template <class TDuration>
static boost::posix_time::ptime ToPTime(TDuration duration)
{
return boost::posix_time::second_clock::universal_time() +
boost::posix_time::milliseconds(
std::chrono::duration_cast<std::chrono::milliseconds>(duration).count());
}
};
} // namespace miopen
#endif // GUARD_MIOPEN_LOCK_FILE_HPP_
<commit_msg>Formatting<commit_after>/*******************************************************************************
*
* MIT License
*
* Copyright (c) 2017 Advanced Micro Devices, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*******************************************************************************/
#ifndef GUARD_MIOPEN_LOCK_FILE_HPP_
#define GUARD_MIOPEN_LOCK_FILE_HPP_
#include <boost/filesystem.hpp>
#include <boost/interprocess/sync/file_lock.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <chrono>
#include <fstream>
#include <shared_mutex>
#include <mutex>
namespace miopen {
// LockFile class is a wrapper around boost::interprocess::file_lock providing MT-safety.
// One process should never have more than one instance of this class with same path at the same
// time. It may lead to undefined behaviour on Windows.
// Also on windows mutex can be removed because file locks are MT-safe there.
class LockFile
{
private:
class PassKey
{
};
public:
LockFile(const char* path, PassKey)
{
std::ofstream{path};
flock = path;
}
LockFile(const LockFile&) = delete;
LockFile operator=(const LockFile&) = delete;
void lock() { std::lock(access_mutex, flock); }
void lock_shared()
{
access_mutex.lock_shared();
flock.lock_sharable();
}
bool try_lock() { return std::try_lock(access_mutex, flock); }
bool try_lock_shared()
{
if(!access_mutex.try_lock_shared())
return false;
if(!flock.try_lock_sharable())
{
access_mutex.unlock_shared();
return false;
}
return true;
}
void unlock()
{
flock.unlock();
access_mutex.unlock();
}
void unlock_shared()
{
flock.unlock_sharable();
access_mutex.unlock_shared();
}
static LockFile& Get(const char* path);
template <class TDuration>
bool try_lock_for(TDuration duration)
{
if(!access_mutex.try_lock_for(duration))
return false;
if(!flock.timed_lock(ToPTime(duration)))
{
access_mutex.unlock();
return false;
}
return true;
}
template <class TDuration>
bool try_lock_shared_for(TDuration duration)
{
if(!access_mutex.try_lock_shared_for(duration))
return false;
if(!flock.timed_lock_sharable(ToPTime(duration)))
{
access_mutex.unlock();
return false;
}
return true;
}
template <class TPoint>
bool try_lock_until(TPoint point)
{
return try_lock_for(point - std::chrono::system_clock::now());
}
template <class TPoint>
bool try_lock_shared_until(TPoint point)
{
return try_lock_shared_for(point - std::chrono::system_clock::now());
}
private:
std::shared_timed_mutex access_mutex;
boost::interprocess::file_lock flock;
static std::map<std::string, LockFile>& LockFiles()
{
static std::map<std::string, LockFile> lock_files;
return lock_files;
}
template <class TDuration>
static boost::posix_time::ptime ToPTime(TDuration duration)
{
return boost::posix_time::second_clock::universal_time() +
boost::posix_time::milliseconds(
std::chrono::duration_cast<std::chrono::milliseconds>(duration).count());
}
};
} // namespace miopen
#endif // GUARD_MIOPEN_LOCK_FILE_HPP_
<|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.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svl.hxx"
#include "ddemlimp.hxx"
#ifdef OV_DEBUG
#include <svgen.hxx>
#endif
#if defined(OV_DEBUG)
void ImpAddHSZ( HSZ hszString, String& rStr )
{
char aBuf[ 128 ];
ImpDdeMgr::DdeQueryString( hszString,aBuf,sizeof(aBuf),850);
rStr += " (\""; rStr += aBuf; rStr += "\",";
HATOMTBL hAtomTable = WinQuerySystemAtomTable();
ULONG nRefCount = 0;
if( hszString )
nRefCount = WinQueryAtomUsage(hAtomTable, (ATOM)hszString );
rStr += nRefCount; rStr += ')';
}
void ImpWriteDdeStatus(char* aFilename, char* pAppContext)
{
char aBuf[ 128 ];
USHORT nCtr;
HWND* pAppPtr;
ImpHCONV* pConvPtr;
Transaction* pTransPtr;
ImpDdeMgrData* pData = ImpDdeMgr::AccessMgrData();
if( !pData )
return;
SvFileStream aStrm(aFilename, STREAM_READWRITE );
String aLine;
aStrm.Seek( STREAM_SEEK_TO_END );
aStrm << endl;
aStrm.WriteLine("********************** DDEML-Log ***********************");
aStrm << endl;
if( pAppContext )
{
aLine = Application::GetAppName();
aLine += ':';
aLine += "App-Context:"; aLine += pAppContext;
aStrm.WriteLine( aLine ); aStrm << endl;
}
aStrm.WriteLine("----------------- ImpDdeMgrData -------------------");
aStrm << endl;
aLine= "TotalSize :"; aLine+= pData->nTotalSize; aStrm.WriteLine(aLine);
aLine= "nOffsAppTable :"; aLine+= pData->nOffsAppTable; aStrm.WriteLine(aLine);
aLine= "nOffsConvTable :"; aLine+= pData->nOffsConvTable; aStrm.WriteLine(aLine);
aLine= "nOffsTransTable:"; aLine+= pData->nOffsTransTable; aStrm.WriteLine(aLine);
aLine= "nMaxAppCount :"; aLine+= pData->nMaxAppCount; aStrm.WriteLine(aLine);
aLine= "nMaxConvCount :"; aLine+= pData->nMaxConvCount; aStrm.WriteLine(aLine);
aLine= "nMaxTransCount :"; aLine+= pData->nMaxTransCount; aStrm.WriteLine(aLine);
aLine= "nLastErr :"; aLine+= pData->nLastErr; aStrm.WriteLine(aLine);
aLine= "nCurConvCount :"; aLine+= pData->nCurConvCount; aStrm.WriteLine(aLine);
aLine= "nCurTransCount :"; aLine+= pData->nCurTransCount; aStrm.WriteLine(aLine);
aStrm << endl;
aStrm.WriteLine("---------- Registered DDEML-Applications -----------");
aStrm << endl;
pAppPtr = ImpDdeMgr::GetAppTable( pData );
for( nCtr = 0; nCtr < pData->nMaxAppCount; nCtr++, pAppPtr++ )
{
if( *pAppPtr )
{
aLine = "App."; aLine += nCtr; aLine += " HWND:";
aLine += (ULONG)*pAppPtr; aStrm.WriteLine(aLine);
}
}
aStrm << endl;
aStrm.WriteLine("-------------- Conversation handles ----------------");
aStrm << endl;
USHORT nCurCount = pData->nCurConvCount;
if( nCurCount )
{
pConvPtr = ImpDdeMgr::GetConvTable( pData );
for( nCtr = 0; nCtr < pData->nMaxConvCount; nCtr++, pConvPtr++ )
{
if( pConvPtr->hWndThis )
{
aLine = "HCONV:"; aLine += nCtr;
aLine += " HCONVpartner: "; aLine += (USHORT)pConvPtr->hConvPartner;
if( !pConvPtr->hConvPartner ) aLine += "(Non-DDEML-App)";
aLine += " hszPartner: "; aLine += (USHORT)pConvPtr->hszPartner;
ImpAddHSZ( pConvPtr->hszPartner, aLine );
aStrm.WriteLine( aLine );
aLine = "hszService: "; aLine += (USHORT)pConvPtr->hszServiceReq;
ImpAddHSZ( pConvPtr->hszServiceReq, aLine );
aLine += " hszTopic: "; aLine += (USHORT)pConvPtr->hszTopic;
ImpAddHSZ( pConvPtr->hszTopic, aLine );
aStrm.WriteLine( aLine );
aLine= "Status: "; aLine+= pConvPtr->nStatus;
if( pConvPtr->nStatus & ST_CLIENT ) aLine += " (Client)";
if( pConvPtr->nStatus & ST_INLIST ) aLine += " (Inlist)";
aStrm.WriteLine(aLine);
aLine = "pidOwner: "; aLine += (ULONG)pConvPtr->pidOwner;
aStrm.WriteLine( aLine );
aLine = "hWndThis: "; aLine += (ULONG)pConvPtr->hWndThis;
aStrm.WriteLine( aLine );
aLine = "hWndPartner: "; aLine += (ULONG)pConvPtr->hWndPartner;
aStrm.WriteLine( aLine );
aLine = "hConvList: "; aLine += (ULONG)pConvPtr->hConvList;
aLine += " Prev: "; aLine += pConvPtr->nPrevHCONV;
aLine += " Next: "; aLine += pConvPtr->nNextHCONV;
aStrm.WriteLine( aLine );
aStrm.WriteLine("----------------------------------------------------");
nCurCount--;
if( !nCurCount )
break;
}
}
}
aStrm.WriteLine("----------------- Transaction Ids ------------------");
nCurCount = pData->nCurTransCount;
if( nCurCount )
{
pTransPtr = ImpDdeMgr::GetTransTable( pData );
for( nCtr = 0; nCtr < pData->nMaxTransCount; nCtr++, pTransPtr++ )
{
if( pTransPtr->hConvOwner )
{
aLine = "TransactionId:"; aLine += nCtr;
aLine += " hConvOwner: "; aLine += (USHORT)pTransPtr->hConvOwner;
aStrm.WriteLine( aLine );
aLine = "Item: "; aLine += (USHORT)pTransPtr->hszItem;
ImpAddHSZ( pTransPtr->hszItem, aLine );
aLine += " Format: "; aLine += pTransPtr->nFormat;
aStrm.WriteLine( aLine );
aLine = "TransactionType: "; aLine += pTransPtr->nType;
aLine += " Convst: "; aLine += pTransPtr->nConvst;
aLine += " LastErr: "; aLine += pTransPtr->nLastError;
aLine += " Userhandle: "; aLine += pTransPtr->nUser;
aStrm.WriteLine( aLine );
aStrm.WriteLine("--------------------------------------------------");
nCurCount--;
if( !nCurCount )
break;
}
}
}
aStrm << endl;
aStrm.WriteLine("******************* End of DDEML-Log *******************");
}
void ImpWriteDdeData(char* aFilename, DDESTRUCT* pData)
{
char aBuf[ 128 ];
USHORT nCtr;
SvFileStream aStrm(aFilename, STREAM_READWRITE );
aStrm.Seek( STREAM_SEEK_TO_END );
String aLine;
aStrm << endl;
aLine = "cbData:"; aLine += pData->cbData; aStrm.WriteLine( aLine );
aLine = "fsStatus:"; aLine += pData->fsStatus; aStrm.WriteLine( aLine );
aLine = "usFormat:"; aLine += pData->usFormat; aStrm.WriteLine( aLine );
aLine = "ItemName:"; aLine += (char*)((char*)pData+pData->offszItemName);
aStrm.WriteLine( aLine );
aLine = "offabData:"; aLine += pData->offabData; aStrm.WriteLine(aLine);
char* pBuf = (char*)pData+pData->offabData;
USHORT nLen = pData->cbData; // - pData->offabData;
while( nLen )
{
aStrm << *pBuf;
nLen--;
pBuf++;
}
aStrm << endl;
}
void ImpWriteLogFile(char* pFilename, char* pStr)
{
SvFileStream aStrm(pFilename, STREAM_READWRITE );
aStrm.Seek( STREAM_SEEK_TO_END );
String aStr( Application::GetAppName() );
aStr += ':'; aStr += pStr;
aStrm.WriteLine( (char*)aStr.GetStr() );
}
#else
void ImpWriteDdeStatus(char*, char* ) {}
void ImpWriteDdeData(char*, DDESTRUCT*) {}
void ImpWriteLogFile(char*, char*) {}
#endif
APIRET MyDosAllocSharedMem(void** ppBaseAddress, char* pszName, unsigned long ulObjectSize,
unsigned long ulFlags, char* pContextStr )
{
APIRET nRet = DosAllocSharedMem(ppBaseAddress,pszName,ulObjectSize,ulFlags );
#if 0 && defined(OV_DEBUG) && defined(LOGFILE)
String aStr("DosAllocSharedMem:");
aStr += pContextStr;
aStr += ": ";
aStr += ulObjectSize;
aStr += " (";
aStr += (ULONG)*((char**)ppBaseAddress);
aStr += ')';
ImpWriteLogFile("\\ddeml.mem", (char*)aStr.GetStr() );
#endif
return nRet;
}
APIRET MyDosAllocMem(void** ppBaseAddress, unsigned long ulObjectSize,
unsigned long ulFlags, char* pContextStr )
{
APIRET nRet = DosAllocMem(ppBaseAddress, ulObjectSize,ulFlags );
#if 0 && defined(OV_DEBUG) && defined(LOGFILE)
String aStr("DosAllocMem:");
aStr += pContextStr;
aStr += ": ";
aStr += ulObjectSize;
aStr += " (";
aStr += (ULONG)*((char**)ppBaseAddress);
aStr += ')';
ImpWriteLogFile("\\ddeml.mem", (char*)aStr.GetStr() );
#endif
return nRet;
}
APIRET MyDosFreeMem( void* pBaseAddress, char* pContextStr )
{
APIRET nRet = DosFreeMem( pBaseAddress );
#if 0 && defined(OV_DEBUG) && defined(LOGFILE)
String aStr("DosFreeMem:");
aStr += pContextStr;
aStr += ": ";
aStr += (ULONG)pBaseAddress;
ImpWriteLogFile("\\ddeml.mem", (char*)aStr.GetStr());
#endif
return nRet;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>cppcheck: remove unused variable aBuf.<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.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svl.hxx"
#include "ddemlimp.hxx"
#ifdef OV_DEBUG
#include <svgen.hxx>
#endif
#if defined(OV_DEBUG)
void ImpAddHSZ( HSZ hszString, String& rStr )
{
char aBuf[ 128 ];
ImpDdeMgr::DdeQueryString( hszString,aBuf,sizeof(aBuf),850);
rStr += " (\""; rStr += aBuf; rStr += "\",";
HATOMTBL hAtomTable = WinQuerySystemAtomTable();
ULONG nRefCount = 0;
if( hszString )
nRefCount = WinQueryAtomUsage(hAtomTable, (ATOM)hszString );
rStr += nRefCount; rStr += ')';
}
void ImpWriteDdeStatus(char* aFilename, char* pAppContext)
{
USHORT nCtr;
HWND* pAppPtr;
ImpHCONV* pConvPtr;
Transaction* pTransPtr;
ImpDdeMgrData* pData = ImpDdeMgr::AccessMgrData();
if( !pData )
return;
SvFileStream aStrm(aFilename, STREAM_READWRITE );
String aLine;
aStrm.Seek( STREAM_SEEK_TO_END );
aStrm << endl;
aStrm.WriteLine("********************** DDEML-Log ***********************");
aStrm << endl;
if( pAppContext )
{
aLine = Application::GetAppName();
aLine += ':';
aLine += "App-Context:"; aLine += pAppContext;
aStrm.WriteLine( aLine ); aStrm << endl;
}
aStrm.WriteLine("----------------- ImpDdeMgrData -------------------");
aStrm << endl;
aLine= "TotalSize :"; aLine+= pData->nTotalSize; aStrm.WriteLine(aLine);
aLine= "nOffsAppTable :"; aLine+= pData->nOffsAppTable; aStrm.WriteLine(aLine);
aLine= "nOffsConvTable :"; aLine+= pData->nOffsConvTable; aStrm.WriteLine(aLine);
aLine= "nOffsTransTable:"; aLine+= pData->nOffsTransTable; aStrm.WriteLine(aLine);
aLine= "nMaxAppCount :"; aLine+= pData->nMaxAppCount; aStrm.WriteLine(aLine);
aLine= "nMaxConvCount :"; aLine+= pData->nMaxConvCount; aStrm.WriteLine(aLine);
aLine= "nMaxTransCount :"; aLine+= pData->nMaxTransCount; aStrm.WriteLine(aLine);
aLine= "nLastErr :"; aLine+= pData->nLastErr; aStrm.WriteLine(aLine);
aLine= "nCurConvCount :"; aLine+= pData->nCurConvCount; aStrm.WriteLine(aLine);
aLine= "nCurTransCount :"; aLine+= pData->nCurTransCount; aStrm.WriteLine(aLine);
aStrm << endl;
aStrm.WriteLine("---------- Registered DDEML-Applications -----------");
aStrm << endl;
pAppPtr = ImpDdeMgr::GetAppTable( pData );
for( nCtr = 0; nCtr < pData->nMaxAppCount; nCtr++, pAppPtr++ )
{
if( *pAppPtr )
{
aLine = "App."; aLine += nCtr; aLine += " HWND:";
aLine += (ULONG)*pAppPtr; aStrm.WriteLine(aLine);
}
}
aStrm << endl;
aStrm.WriteLine("-------------- Conversation handles ----------------");
aStrm << endl;
USHORT nCurCount = pData->nCurConvCount;
if( nCurCount )
{
pConvPtr = ImpDdeMgr::GetConvTable( pData );
for( nCtr = 0; nCtr < pData->nMaxConvCount; nCtr++, pConvPtr++ )
{
if( pConvPtr->hWndThis )
{
aLine = "HCONV:"; aLine += nCtr;
aLine += " HCONVpartner: "; aLine += (USHORT)pConvPtr->hConvPartner;
if( !pConvPtr->hConvPartner ) aLine += "(Non-DDEML-App)";
aLine += " hszPartner: "; aLine += (USHORT)pConvPtr->hszPartner;
ImpAddHSZ( pConvPtr->hszPartner, aLine );
aStrm.WriteLine( aLine );
aLine = "hszService: "; aLine += (USHORT)pConvPtr->hszServiceReq;
ImpAddHSZ( pConvPtr->hszServiceReq, aLine );
aLine += " hszTopic: "; aLine += (USHORT)pConvPtr->hszTopic;
ImpAddHSZ( pConvPtr->hszTopic, aLine );
aStrm.WriteLine( aLine );
aLine= "Status: "; aLine+= pConvPtr->nStatus;
if( pConvPtr->nStatus & ST_CLIENT ) aLine += " (Client)";
if( pConvPtr->nStatus & ST_INLIST ) aLine += " (Inlist)";
aStrm.WriteLine(aLine);
aLine = "pidOwner: "; aLine += (ULONG)pConvPtr->pidOwner;
aStrm.WriteLine( aLine );
aLine = "hWndThis: "; aLine += (ULONG)pConvPtr->hWndThis;
aStrm.WriteLine( aLine );
aLine = "hWndPartner: "; aLine += (ULONG)pConvPtr->hWndPartner;
aStrm.WriteLine( aLine );
aLine = "hConvList: "; aLine += (ULONG)pConvPtr->hConvList;
aLine += " Prev: "; aLine += pConvPtr->nPrevHCONV;
aLine += " Next: "; aLine += pConvPtr->nNextHCONV;
aStrm.WriteLine( aLine );
aStrm.WriteLine("----------------------------------------------------");
nCurCount--;
if( !nCurCount )
break;
}
}
}
aStrm.WriteLine("----------------- Transaction Ids ------------------");
nCurCount = pData->nCurTransCount;
if( nCurCount )
{
pTransPtr = ImpDdeMgr::GetTransTable( pData );
for( nCtr = 0; nCtr < pData->nMaxTransCount; nCtr++, pTransPtr++ )
{
if( pTransPtr->hConvOwner )
{
aLine = "TransactionId:"; aLine += nCtr;
aLine += " hConvOwner: "; aLine += (USHORT)pTransPtr->hConvOwner;
aStrm.WriteLine( aLine );
aLine = "Item: "; aLine += (USHORT)pTransPtr->hszItem;
ImpAddHSZ( pTransPtr->hszItem, aLine );
aLine += " Format: "; aLine += pTransPtr->nFormat;
aStrm.WriteLine( aLine );
aLine = "TransactionType: "; aLine += pTransPtr->nType;
aLine += " Convst: "; aLine += pTransPtr->nConvst;
aLine += " LastErr: "; aLine += pTransPtr->nLastError;
aLine += " Userhandle: "; aLine += pTransPtr->nUser;
aStrm.WriteLine( aLine );
aStrm.WriteLine("--------------------------------------------------");
nCurCount--;
if( !nCurCount )
break;
}
}
}
aStrm << endl;
aStrm.WriteLine("******************* End of DDEML-Log *******************");
}
void ImpWriteDdeData(char* aFilename, DDESTRUCT* pData)
{
USHORT nCtr;
SvFileStream aStrm(aFilename, STREAM_READWRITE );
aStrm.Seek( STREAM_SEEK_TO_END );
String aLine;
aStrm << endl;
aLine = "cbData:"; aLine += pData->cbData; aStrm.WriteLine( aLine );
aLine = "fsStatus:"; aLine += pData->fsStatus; aStrm.WriteLine( aLine );
aLine = "usFormat:"; aLine += pData->usFormat; aStrm.WriteLine( aLine );
aLine = "ItemName:"; aLine += (char*)((char*)pData+pData->offszItemName);
aStrm.WriteLine( aLine );
aLine = "offabData:"; aLine += pData->offabData; aStrm.WriteLine(aLine);
char* pBuf = (char*)pData+pData->offabData;
USHORT nLen = pData->cbData; // - pData->offabData;
while( nLen )
{
aStrm << *pBuf;
nLen--;
pBuf++;
}
aStrm << endl;
}
void ImpWriteLogFile(char* pFilename, char* pStr)
{
SvFileStream aStrm(pFilename, STREAM_READWRITE );
aStrm.Seek( STREAM_SEEK_TO_END );
String aStr( Application::GetAppName() );
aStr += ':'; aStr += pStr;
aStrm.WriteLine( (char*)aStr.GetStr() );
}
#else
void ImpWriteDdeStatus(char*, char* ) {}
void ImpWriteDdeData(char*, DDESTRUCT*) {}
void ImpWriteLogFile(char*, char*) {}
#endif
APIRET MyDosAllocSharedMem(void** ppBaseAddress, char* pszName, unsigned long ulObjectSize,
unsigned long ulFlags, char* pContextStr )
{
APIRET nRet = DosAllocSharedMem(ppBaseAddress,pszName,ulObjectSize,ulFlags );
#if 0 && defined(OV_DEBUG) && defined(LOGFILE)
String aStr("DosAllocSharedMem:");
aStr += pContextStr;
aStr += ": ";
aStr += ulObjectSize;
aStr += " (";
aStr += (ULONG)*((char**)ppBaseAddress);
aStr += ')';
ImpWriteLogFile("\\ddeml.mem", (char*)aStr.GetStr() );
#endif
return nRet;
}
APIRET MyDosAllocMem(void** ppBaseAddress, unsigned long ulObjectSize,
unsigned long ulFlags, char* pContextStr )
{
APIRET nRet = DosAllocMem(ppBaseAddress, ulObjectSize,ulFlags );
#if 0 && defined(OV_DEBUG) && defined(LOGFILE)
String aStr("DosAllocMem:");
aStr += pContextStr;
aStr += ": ";
aStr += ulObjectSize;
aStr += " (";
aStr += (ULONG)*((char**)ppBaseAddress);
aStr += ')';
ImpWriteLogFile("\\ddeml.mem", (char*)aStr.GetStr() );
#endif
return nRet;
}
APIRET MyDosFreeMem( void* pBaseAddress, char* pContextStr )
{
APIRET nRet = DosFreeMem( pBaseAddress );
#if 0 && defined(OV_DEBUG) && defined(LOGFILE)
String aStr("DosFreeMem:");
aStr += pContextStr;
aStr += ": ";
aStr += (ULONG)pBaseAddress;
ImpWriteLogFile("\\ddeml.mem", (char*)aStr.GetStr());
#endif
return nRet;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|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.
*
************************************************************************/
#ifndef _SDRPAGEWINDOW_HXX
#define _SDRPAGEWINDOW_HXX
#include <com/sun/star/awt/XWindowListener.hpp>
#include <com/sun/star/beans/XPropertyChangeListener.hpp>
#include <com/sun/star/awt/XControlContainer.hpp>
#include <com/sun/star/util/XModeChangeListener.hpp>
#include <cppuhelper/implbase4.hxx>
#include <svx/sdr/overlay/overlaymanager.hxx>
#include <svx/svdtypes.hxx> // for SdrLayerID
#include <tools/contnr.hxx>
#include <svx/sdrpagewindow.hxx>
#include "svx/svxdllapi.h"
#include <vector>
////////////////////////////////////////////////////////////////////////////////////////////////////
// predeclarations
class Region;
class SdrUnoObj;
class SdrPageView;
// #110094#
namespace sdr
{
namespace contact
{
class ObjectContact;
class ViewObjectContactRedirector;
} // end of namespace contact
namespace overlay
{
class OverlayManager;
} // end of namespace overlay
} // end of namespace sdr
namespace basegfx
{
class B2DRange;
} // end of namespace basegfx
class SdrPaintWindow;
class Link;
////////////////////////////////////////////////////////////////////////////////////////////////////
class SVX_DLLPUBLIC SdrPageWindow
{
// #110094# ObjectContact section
sdr::contact::ObjectContact* mpObjectContact;
// the SdrPageView this window belongs to
SdrPageView& mrPageView;
// the PaintWindow to paint on. Here is access to OutDev etc.
// #i72752# change to pointer to allow patcing it in DrawLayer() if necessary
SdrPaintWindow* mpPaintWindow;
SdrPaintWindow* mpOriginalPaintWindow;
// UNO stuff for xControls
::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlContainer > mxControlContainer;
sdr::contact::ObjectContact* CreateViewSpecificObjectContact();
public:
SdrPageWindow(SdrPageView& rNewPageView, SdrPaintWindow& rPaintWindow);
~SdrPageWindow();
// data read accesses
SdrPageView& GetPageView() const { return mrPageView; }
SdrPaintWindow& GetPaintWindow() const { return *mpPaintWindow; }
const SdrPaintWindow* GetOriginalPaintWindow() const { return mpOriginalPaintWindow; }
::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlContainer > GetControlContainer( bool _bCreateIfNecessary = true ) const;
// OVERLAYMANAGER
rtl::Reference< ::sdr::overlay::OverlayManager > GetOverlayManager() const;
// #i72752# allow patcing SdrPaintWindow from SdrPageView::DrawLayer if needed
void patchPaintWindow(SdrPaintWindow& rPaintWindow);
void unpatchPaintWindow();
// the repaint method. For migration from pPaintProc, use one more parameter
void PrePaint();
void PrepareRedraw(const Region& rReg);
void RedrawAll(sdr::contact::ViewObjectContactRedirector* pRedirector) const;
void RedrawLayer(const SdrLayerID* pId, sdr::contact::ViewObjectContactRedirector* pRedirector) const;
// Invalidate call, used from ObjectContact(OfPageView) in InvalidatePartOfView(...)
void InvalidatePageWindow(const basegfx::B2DRange& rRange);
// #110094# ObjectContact section
sdr::contact::ObjectContact& GetObjectContact() const;
/// determines whether there already exists an ObjectContact
bool HasObjectContact() const;
// #i26631#
void ResetObjectContact();
/** sets all elements in the view which support a design and a alive mode into the given mode
*/
void SetDesignMode( bool _bDesignMode ) const;
};
// typedefs for a list of SdrPageWindow
typedef ::std::vector< SdrPageWindow* > SdrPageWindowVector;
////////////////////////////////////////////////////////////////////////////////////////////////////
#endif //_SDRPAGEWINDOW_HXX
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Remove unnecessary include<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.
*
************************************************************************/
#ifndef _SDRPAGEWINDOW_HXX
#define _SDRPAGEWINDOW_HXX
#include <com/sun/star/awt/XWindowListener.hpp>
#include <com/sun/star/beans/XPropertyChangeListener.hpp>
#include <com/sun/star/awt/XControlContainer.hpp>
#include <com/sun/star/util/XModeChangeListener.hpp>
#include <cppuhelper/implbase4.hxx>
#include <svx/sdr/overlay/overlaymanager.hxx>
#include <svx/svdtypes.hxx> // for SdrLayerID
#include <svx/sdrpagewindow.hxx>
#include "svx/svxdllapi.h"
#include <vector>
////////////////////////////////////////////////////////////////////////////////////////////////////
// predeclarations
class Region;
class SdrUnoObj;
class SdrPageView;
// #110094#
namespace sdr
{
namespace contact
{
class ObjectContact;
class ViewObjectContactRedirector;
} // end of namespace contact
namespace overlay
{
class OverlayManager;
} // end of namespace overlay
} // end of namespace sdr
namespace basegfx
{
class B2DRange;
} // end of namespace basegfx
class SdrPaintWindow;
class Link;
////////////////////////////////////////////////////////////////////////////////////////////////////
class SVX_DLLPUBLIC SdrPageWindow
{
// #110094# ObjectContact section
sdr::contact::ObjectContact* mpObjectContact;
// the SdrPageView this window belongs to
SdrPageView& mrPageView;
// the PaintWindow to paint on. Here is access to OutDev etc.
// #i72752# change to pointer to allow patcing it in DrawLayer() if necessary
SdrPaintWindow* mpPaintWindow;
SdrPaintWindow* mpOriginalPaintWindow;
// UNO stuff for xControls
::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlContainer > mxControlContainer;
sdr::contact::ObjectContact* CreateViewSpecificObjectContact();
public:
SdrPageWindow(SdrPageView& rNewPageView, SdrPaintWindow& rPaintWindow);
~SdrPageWindow();
// data read accesses
SdrPageView& GetPageView() const { return mrPageView; }
SdrPaintWindow& GetPaintWindow() const { return *mpPaintWindow; }
const SdrPaintWindow* GetOriginalPaintWindow() const { return mpOriginalPaintWindow; }
::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlContainer > GetControlContainer( bool _bCreateIfNecessary = true ) const;
// OVERLAYMANAGER
rtl::Reference< ::sdr::overlay::OverlayManager > GetOverlayManager() const;
// #i72752# allow patcing SdrPaintWindow from SdrPageView::DrawLayer if needed
void patchPaintWindow(SdrPaintWindow& rPaintWindow);
void unpatchPaintWindow();
// the repaint method. For migration from pPaintProc, use one more parameter
void PrePaint();
void PrepareRedraw(const Region& rReg);
void RedrawAll(sdr::contact::ViewObjectContactRedirector* pRedirector) const;
void RedrawLayer(const SdrLayerID* pId, sdr::contact::ViewObjectContactRedirector* pRedirector) const;
// Invalidate call, used from ObjectContact(OfPageView) in InvalidatePartOfView(...)
void InvalidatePageWindow(const basegfx::B2DRange& rRange);
// #110094# ObjectContact section
sdr::contact::ObjectContact& GetObjectContact() const;
/// determines whether there already exists an ObjectContact
bool HasObjectContact() const;
// #i26631#
void ResetObjectContact();
/** sets all elements in the view which support a design and a alive mode into the given mode
*/
void SetDesignMode( bool _bDesignMode ) const;
};
// typedefs for a list of SdrPageWindow
typedef ::std::vector< SdrPageWindow* > SdrPageWindowVector;
////////////////////////////////////////////////////////////////////////////////////////////////////
#endif //_SDRPAGEWINDOW_HXX
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: contimp.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: obo $ $Date: 2006-10-12 12:08:15 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _CONTIMP_HXX_
#define _CONTIMP_HXX_
#ifndef _CONTDLG_HXX
#include "contdlg.hxx"
#endif
#ifndef _CONTWND_HXX
#include "contwnd.hxx"
#endif
#ifndef _SV_TOOLBOX_HXX
#include <vcl/toolbox.hxx>
#endif
#ifndef _SV_STATUS_HXX
#include <vcl/status.hxx>
#endif
#define CONT_RESID(nId) ResId( nId, DIALOG_MGR() )
/*************************************************************************
|*
|*
|*
\************************************************************************/
class SvxSuperContourDlg : public SvxContourDlg
{
using SvxContourDlg::GetPolyPolygon;
Graphic aGraphic;
Graphic aUndoGraphic;
Graphic aRedoGraphic;
Graphic aUpdateGraphic;
PolyPolygon aUpdatePolyPoly;
Timer aUpdateTimer;
Timer aCreateTimer;
Size aLastSize;
void* pUpdateEditingObject;
void* pCheckObj;
SvxContourDlgItem aContourItem;
ToolBox aTbx1;
MetricField aMtfTolerance;
ContourWindow aContourWnd;
StatusBar aStbStatus;
ULONG nGrfChanged;
BOOL bExecState;
BOOL bPipetteMode;
BOOL bWorkplaceMode;
BOOL bUpdateGraphicLinked;
BOOL bGraphicLinked;
ImageList maImageList;
ImageList maImageListH;
virtual void Resize();
virtual BOOL Close();
void DoAutoCreate();
void ReducePoints( const long nTol = 8 );
DECL_LINK( Tbx1ClickHdl, ToolBox* );
DECL_LINK( MousePosHdl, ContourWindow* );
DECL_LINK( GraphSizeHdl, ContourWindow* );
DECL_LINK( UpdateHdl, Timer* );
DECL_LINK( CreateHdl, Timer* );
DECL_LINK( StateHdl, ContourWindow* );
DECL_LINK( PipetteHdl, ContourWindow* );
DECL_LINK( PipetteClickHdl, ContourWindow* );
DECL_LINK( WorkplaceClickHdl, ContourWindow* );
DECL_LINK( MiscHdl, void* );
public:
SvxSuperContourDlg( SfxBindings *pBindings, SfxChildWindow *pCW,
Window* pParent, const ResId& rResId );
~SvxSuperContourDlg();
void SetExecState( BOOL bEnable );
void SetGraphic( const Graphic& rGraphic );
void SetGraphicLinked( BOOL bLinked ) { bGraphicLinked = bLinked; }
const Graphic& GetGraphic() const { return aGraphic; }
BOOL IsGraphicChanged() const { return nGrfChanged > 0UL; }
void SetPolyPolygon( const PolyPolygon& rPolyPoly );
PolyPolygon GetPolyPolygon( BOOL bRescaleToGraphic = TRUE );
void SetEditingObject( void* pObj ) { pCheckObj = pObj; }
const void* GetEditingObject() const { return pCheckObj; }
BOOL IsUndoPossible() const;
BOOL IsRedoPossible() const;
void UpdateGraphic( const Graphic& rGraphic, BOOL bGraphicLinked,
const PolyPolygon* pPolyPoly = NULL,
void* pEditingObj = NULL );
/** switches the toolbox images depending on the actuall high contrast display mode state */
void ApplyImageList();
/** virtual method from Window is used to detect change in high contrast display mode
to switch the toolbox images */
virtual void DataChanged( const DataChangedEvent& rDCEvt );
};
#endif // _CONTIMP_HXX_
<commit_msg>INTEGRATION: CWS vgbugs07 (1.5.322); FILE MERGED 2007/06/04 13:26:14 vg 1.5.322.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: contimp.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: hr $ $Date: 2007-06-27 16:56:01 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _CONTIMP_HXX_
#define _CONTIMP_HXX_
#ifndef _CONTDLG_HXX
#include <svx/contdlg.hxx>
#endif
#ifndef _CONTWND_HXX
#include "contwnd.hxx"
#endif
#ifndef _SV_TOOLBOX_HXX
#include <vcl/toolbox.hxx>
#endif
#ifndef _SV_STATUS_HXX
#include <vcl/status.hxx>
#endif
#define CONT_RESID(nId) ResId( nId, DIALOG_MGR() )
/*************************************************************************
|*
|*
|*
\************************************************************************/
class SvxSuperContourDlg : public SvxContourDlg
{
using SvxContourDlg::GetPolyPolygon;
Graphic aGraphic;
Graphic aUndoGraphic;
Graphic aRedoGraphic;
Graphic aUpdateGraphic;
PolyPolygon aUpdatePolyPoly;
Timer aUpdateTimer;
Timer aCreateTimer;
Size aLastSize;
void* pUpdateEditingObject;
void* pCheckObj;
SvxContourDlgItem aContourItem;
ToolBox aTbx1;
MetricField aMtfTolerance;
ContourWindow aContourWnd;
StatusBar aStbStatus;
ULONG nGrfChanged;
BOOL bExecState;
BOOL bPipetteMode;
BOOL bWorkplaceMode;
BOOL bUpdateGraphicLinked;
BOOL bGraphicLinked;
ImageList maImageList;
ImageList maImageListH;
virtual void Resize();
virtual BOOL Close();
void DoAutoCreate();
void ReducePoints( const long nTol = 8 );
DECL_LINK( Tbx1ClickHdl, ToolBox* );
DECL_LINK( MousePosHdl, ContourWindow* );
DECL_LINK( GraphSizeHdl, ContourWindow* );
DECL_LINK( UpdateHdl, Timer* );
DECL_LINK( CreateHdl, Timer* );
DECL_LINK( StateHdl, ContourWindow* );
DECL_LINK( PipetteHdl, ContourWindow* );
DECL_LINK( PipetteClickHdl, ContourWindow* );
DECL_LINK( WorkplaceClickHdl, ContourWindow* );
DECL_LINK( MiscHdl, void* );
public:
SvxSuperContourDlg( SfxBindings *pBindings, SfxChildWindow *pCW,
Window* pParent, const ResId& rResId );
~SvxSuperContourDlg();
void SetExecState( BOOL bEnable );
void SetGraphic( const Graphic& rGraphic );
void SetGraphicLinked( BOOL bLinked ) { bGraphicLinked = bLinked; }
const Graphic& GetGraphic() const { return aGraphic; }
BOOL IsGraphicChanged() const { return nGrfChanged > 0UL; }
void SetPolyPolygon( const PolyPolygon& rPolyPoly );
PolyPolygon GetPolyPolygon( BOOL bRescaleToGraphic = TRUE );
void SetEditingObject( void* pObj ) { pCheckObj = pObj; }
const void* GetEditingObject() const { return pCheckObj; }
BOOL IsUndoPossible() const;
BOOL IsRedoPossible() const;
void UpdateGraphic( const Graphic& rGraphic, BOOL bGraphicLinked,
const PolyPolygon* pPolyPoly = NULL,
void* pEditingObj = NULL );
/** switches the toolbox images depending on the actuall high contrast display mode state */
void ApplyImageList();
/** virtual method from Window is used to detect change in high contrast display mode
to switch the toolbox images */
virtual void DataChanged( const DataChangedEvent& rDCEvt );
};
#endif // _CONTIMP_HXX_
<|endoftext|>
|
<commit_before>/*
Пример применения генератора псевдослучайных чисел (ГПЧ) из
стандартной библиотеки C++
*/
#include <iostream>
#include <ctime> // Библиотека работы со временем
#include <random> // Библиотека с различными генераторами
using namespace std;
/*
Функция для получения действительного случайного числа,
равномерно распределённого в диапазоне [0.0; 1.0].
Пока только объявление.
*/
double real_rnd_0_1();
int main()
{
/*
Используем тип mt19937_64 для создания переменной,
которая и будет создавать случайные числа.
При создании переменной-генератора ей передаётся
количество секунд, прошедших с 01.01.1970 00:00:00,
которое используется в качестве зерна ГПЧ. Это число
возращается функцией time, определённой в <ctime>.
Данная функция ожидает адрес некоторой библиотечной
структуры, но вместо него можно передать и специальный
нулевой адрес. Этот нулевой адрес представлен ключевым
словом - nullptr
*/
mt19937_64 gnr( time(nullptr) );
/*
Случайное число создаётся с помощью вызова специального оператора -
пары круглых скобок. Очень похоже на вызов функции, но применяется
к переменным некоторых составных (сложных) типов данных.
Каждое случайное число является беззнаковым целым из
диапазона [0; MAX], где MAX - величина относящаяся
к алгоритму ГПЧ. Случайные числа выбираются из указанного
интервала равномерно.
*/
cout << "Случайное число: " << gnr() << "\n";
cout << "ещё одно: " << gnr() << "\n";
// Получить максимально возможное случайно число:
cout << "Максимальное число, доступное ГПЧ: " << gnr.max() << "\n";
cout << "Случайное число от 0 до 1: " << real_rnd_0_1() << "\n";
}
double real_rnd_0_1()
{
/*
Пример статической переменной: данная переменная создаётся
при начале работы программы один раз и не меняется/удаляется
при любом количестве вызовов данной функции.
*/
static mt19937_64 gener( time(nullptr) );
static unsigned long long max_num = gener.max();
/*
Что ниже происходит?
gener() - возращает целое число, max_num - тоже целое.
Для того, чтобы результат деления был действительным,
а не целочисленным (при таком делении результат выражения -
всегда нуль), нужно сделать явное приведение хотя бы
одного целочисленного значения к действительному типу данных.
Это делайтся в C++ с помощью специального оператора: static_cast.
Он работает следующим образом: в треугольных скобках указан тип,
к которому нужно привести значение, в круглых скобках - само значение.
После его выполнения, деление проходит по правилам действительных чисел
и мы получаем число от 0.0 до 1.0
*/
return static_cast<double>( gener() ) / max_num;
}
<commit_msg>c++, fp: extend third practice example<commit_after>/*
Пример применения генератора псевдослучайных чисел (ГПЧ) из
стандартной библиотеки C++
*/
#include <iostream>
#include <ctime> // Библиотека работы со временем
#include <random> // Библиотека с различными генераторами
using namespace std;
/*
Функция для получения действительного случайного числа,
равномерно распределённого в диапазоне [0.0; 1.0].
Пока только объявление.
*/
double real_rnd_0_1();
/*
Функция для получнния случайного действительного числа
в интервале [a; b]. Значения правого и левого краёв
передаются через 2 аргумента. Внутри используется функция
real_rnd_0_1
*/
double real_rnd_a_b(double a, double b);
int main()
{
/*
Используем тип mt19937_64 для создания переменной,
которая и будет создавать случайные числа.
При создании переменной-генератора ей передаётся
количество секунд, прошедших с 01.01.1970 00:00:00,
которое используется в качестве зерна ГПЧ. Это число
возращается функцией time, определённой в <ctime>.
Данная функция ожидает адрес некоторой библиотечной
структуры, но вместо него можно передать и специальный
нулевой адрес. Этот нулевой адрес представлен ключевым
словом - nullptr
*/
mt19937_64 gnr( time(nullptr) );
/*
Случайное число создаётся с помощью вызова специального оператора -
пары круглых скобок. Очень похоже на вызов функции, но применяется
к переменным некоторых составных (сложных) типов данных.
Каждое случайное число является беззнаковым целым из
диапазона [0; MAX], где MAX - величина относящаяся
к алгоритму ГПЧ. Случайные числа выбираются из указанного
интервала равномерно.
*/
cout << "Случайное число: " << gnr() << "\n";
cout << "ещё одно: " << gnr() << "\n";
// Получить максимально возможное случайно число:
cout << "Максимальное число, доступное ГПЧ: " << gnr.max() << "\n";
cout << "Случайное число от 0 до 1: " << real_rnd_0_1() << "\n";
// Пример заполнения статического массива числами из заданного интервала: [-1.5; 7.8]
double arr_2D[11][7];
for (unsigned i = 0; i < 11; ++i) {
for (unsigned j = 0; j < 7; ++j) {
arr_2D[i][j] = real_rnd_a_b(-1.5, 7.8);
}
}
cout << "Созданный массив:\n";
// Используем специальный цикл for (for-range) для печати элементов
// двумерного массива
for (const auto& row : arr_2D) { // Этот цикл переберает все строчки
for (double elem : row) { // Этот - все элементы в конкретной строке
cout << elem << " ";
}
cout << "\n";
}
cout << "\n";
}
double real_rnd_0_1()
{
/*
Пример статической переменной: данная переменная создаётся
при начале работы программы один раз и не меняется/удаляется
при любом количестве вызовов данной функции.
*/
static mt19937_64 gener( time(nullptr) );
static unsigned long long max_num = gener.max();
/*
Что ниже происходит?
gener() - возращает целое число, max_num - тоже целое.
Для того, чтобы результат деления был действительным,
а не целочисленным (при таком делении результат выражения -
всегда нуль), нужно сделать явное приведение хотя бы
одного целочисленного значения к действительному типу данных.
Это делайтся в C++ с помощью специального оператора: static_cast.
Он работает следующим образом: в треугольных скобках указан тип,
к которому нужно привести значение, в круглых скобках - само значение.
После его выполнения, деление проходит по правилам действительных чисел
и мы получаем число от 0.0 до 1.0.
Дополнение: альтернативным способом для задания явного приведения между
численными типами данных является следующий синтаксис:
double( gener() )
, где указывается тип данных, к которому нужно привести значение, а затем
- само значение.
*/
return static_cast<double>( gener() ) / max_num;
}
double real_rnd_a_b(double a, double b)
{
return (b - a) * real_rnd_0_1() + a;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2012 The WebM project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "third_party/googletest/src/include/gtest/gtest.h"
#include "test/codec_factory.h"
#include "test/encode_test_driver.h"
#include "test/i420_video_source.h"
#include "test/util.h"
namespace {
class AqSegmentTest
: public ::libvpx_test::EncoderTest,
public ::libvpx_test::CodecTestWith2Params<libvpx_test::TestMode, int> {
protected:
AqSegmentTest() : EncoderTest(GET_PARAM(0)) {}
virtual ~AqSegmentTest() {}
virtual void SetUp() {
InitializeConfig();
SetMode(GET_PARAM(1));
set_cpu_used_ = GET_PARAM(2);
aq_mode_ = 0;
}
virtual void PreEncodeFrameHook(::libvpx_test::VideoSource *video,
::libvpx_test::Encoder *encoder) {
if (video->frame() == 1) {
encoder->Control(VP8E_SET_CPUUSED, set_cpu_used_);
encoder->Control(VP9E_SET_AQ_MODE, aq_mode_);
encoder->Control(VP8E_SET_MAX_INTRA_BITRATE_PCT, 100);
}
}
int set_cpu_used_;
int aq_mode_;
};
// Validate that this AQ segmentation mode (AQ=1, variance_ap)
// encodes and decodes without a mismatch.
TEST_P(AqSegmentTest, TestNoMisMatchAQ1) {
cfg_.rc_min_quantizer = 8;
cfg_.rc_max_quantizer = 56;
cfg_.rc_end_usage = VPX_CBR;
cfg_.g_lag_in_frames = 0;
cfg_.rc_buf_initial_sz = 500;
cfg_.rc_buf_optimal_sz = 500;
cfg_.rc_buf_sz = 1000;
cfg_.rc_target_bitrate = 300;
aq_mode_ = 1;
::libvpx_test::I420VideoSource video("hantro_collage_w352h288.yuv", 352, 288,
30, 1, 0, 100);
ASSERT_NO_FATAL_FAILURE(RunLoop(&video));
}
// Validate that this AQ segmentation mode (AQ=2, complexity_aq)
// encodes and decodes without a mismatch.
TEST_P(AqSegmentTest, TestNoMisMatchAQ2) {
cfg_.rc_min_quantizer = 8;
cfg_.rc_max_quantizer = 56;
cfg_.rc_end_usage = VPX_CBR;
cfg_.g_lag_in_frames = 0;
cfg_.rc_buf_initial_sz = 500;
cfg_.rc_buf_optimal_sz = 500;
cfg_.rc_buf_sz = 1000;
cfg_.rc_target_bitrate = 300;
aq_mode_ = 2;
::libvpx_test::I420VideoSource video("hantro_collage_w352h288.yuv", 352, 288,
30, 1, 0, 100);
ASSERT_NO_FATAL_FAILURE(RunLoop(&video));
}
// Validate that this AQ segmentation mode (AQ=3, cyclic_refresh_aq)
// encodes and decodes without a mismatch.
TEST_P(AqSegmentTest, TestNoMisMatchAQ3) {
cfg_.rc_min_quantizer = 8;
cfg_.rc_max_quantizer = 56;
cfg_.rc_end_usage = VPX_CBR;
cfg_.g_lag_in_frames = 0;
cfg_.rc_buf_initial_sz = 500;
cfg_.rc_buf_optimal_sz = 500;
cfg_.rc_buf_sz = 1000;
cfg_.rc_target_bitrate = 300;
aq_mode_ = 3;
::libvpx_test::I420VideoSource video("hantro_collage_w352h288.yuv", 352, 288,
30, 1, 0, 100);
ASSERT_NO_FATAL_FAILURE(RunLoop(&video));
}
VP9_INSTANTIATE_TEST_CASE(AqSegmentTest,
::testing::Values(::libvpx_test::kRealTime,
::libvpx_test::kOnePassGood),
::testing::Range(3, 9));
} // namespace
<commit_msg>Turn on AqSegment tests for VP10<commit_after>/*
* Copyright (c) 2012 The WebM project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "third_party/googletest/src/include/gtest/gtest.h"
#include "test/codec_factory.h"
#include "test/encode_test_driver.h"
#include "test/i420_video_source.h"
#include "test/util.h"
namespace {
class AqSegmentTest
: public ::libvpx_test::EncoderTest,
public ::libvpx_test::CodecTestWith2Params<libvpx_test::TestMode, int> {
protected:
AqSegmentTest() : EncoderTest(GET_PARAM(0)) {}
virtual ~AqSegmentTest() {}
virtual void SetUp() {
InitializeConfig();
SetMode(GET_PARAM(1));
set_cpu_used_ = GET_PARAM(2);
aq_mode_ = 0;
}
virtual void PreEncodeFrameHook(::libvpx_test::VideoSource *video,
::libvpx_test::Encoder *encoder) {
if (video->frame() == 1) {
encoder->Control(VP8E_SET_CPUUSED, set_cpu_used_);
encoder->Control(VP9E_SET_AQ_MODE, aq_mode_);
encoder->Control(VP8E_SET_MAX_INTRA_BITRATE_PCT, 100);
}
}
void DoTest(int aq_mode) {
aq_mode_ = aq_mode;
cfg_.kf_max_dist = 12;
cfg_.rc_min_quantizer = 8;
cfg_.rc_max_quantizer = 56;
cfg_.rc_end_usage = VPX_CBR;
cfg_.g_lag_in_frames = 6;
cfg_.rc_buf_initial_sz = 500;
cfg_.rc_buf_optimal_sz = 500;
cfg_.rc_buf_sz = 1000;
cfg_.rc_target_bitrate = 300;
::libvpx_test::I420VideoSource video("hantro_collage_w352h288.yuv",
352, 288, 30, 1, 0, 15);
ASSERT_NO_FATAL_FAILURE(RunLoop(&video));
}
int set_cpu_used_;
int aq_mode_;
};
// Validate that this AQ segmentation mode (AQ=1, variance_ap)
// encodes and decodes without a mismatch.
TEST_P(AqSegmentTest, TestNoMisMatchAQ1) {
DoTest(1);
}
// Validate that this AQ segmentation mode (AQ=2, complexity_aq)
// encodes and decodes without a mismatch.
TEST_P(AqSegmentTest, TestNoMisMatchAQ2) {
DoTest(2);
}
// Validate that this AQ segmentation mode (AQ=3, cyclic_refresh_aq)
// encodes and decodes without a mismatch.
TEST_P(AqSegmentTest, TestNoMisMatchAQ3) {
DoTest(3);
}
class AqSegmentTestLarge : public AqSegmentTest {};
TEST_P(AqSegmentTestLarge, TestNoMisMatchAQ1) {
DoTest(1);
}
TEST_P(AqSegmentTestLarge, TestNoMisMatchAQ2) {
DoTest(2);
}
TEST_P(AqSegmentTestLarge, TestNoMisMatchAQ3) {
DoTest(3);
}
VP9_INSTANTIATE_TEST_CASE(AqSegmentTest,
::testing::Values(::libvpx_test::kRealTime,
::libvpx_test::kOnePassGood),
::testing::Range(3, 9));
VP10_INSTANTIATE_TEST_CASE(AqSegmentTest,
::testing::Values(::libvpx_test::kRealTime,
::libvpx_test::kOnePassGood),
::testing::Range(5, 9));
VP10_INSTANTIATE_TEST_CASE(AqSegmentTestLarge,
::testing::Values(::libvpx_test::kRealTime,
::libvpx_test::kOnePassGood),
::testing::Range(3, 5));
} // namespace
<|endoftext|>
|
<commit_before>/*
AtlasProtocolDecoder.cpp
----------------
begin : 1999.11.29
copyright : (C) 1999 by John Barrett (ZW)
email : jbarrett@box100.com
*/
#include "AtlasObject.h"
#include "AtlasProtocol.h"
#include "AtlasPackedAsciiDecoder.h"
#include <memory.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string>
void APackedAsciiDecoder::newStream()
{
// reset decoder
state = 1;
nestd = 0;
token = 0;
}
void APackedAsciiDecoder::feedStream(string& data)
{
buffer.append(data);
}
int APackedAsciiDecoder::getToken()
{
int tmp = token;
token = 0;
return tmp;
}
int APackedAsciiDecoder::hasTokens()
{
int pos;
//int pos1;
//int ndx;
int chk;
string typ;
//printf("BEG TOKEN=%i\n", token);
if (token == -1) return-1; // buffer overflow !!!
do {
chk = 0;
//printf("BEG STATE=%i\n", state);
//printf("BEG BUFFR=%s\n", buffer.c_str());
// this is where we are gonna put the state machine
switch (state) {
case 1:// start of message
if((pos=buffer.find('{')) == -1) break;
buffer = buffer.substr(pos+1);
// change states
token = AProtocol::atlasMSGBEG;
state = 2;
chk = 1;
break;
case 2:
pos = buffer.find_first_of("[(%$#])}");
if (pos == -1) break;
if (pos != 0)
{
// bad protcol character
token = AProtocol::atlasERRTOK;
state = 1;
break;
}
typ = buffer.substr(0,1);
if (typ == ")") {
// end of list
buffer = buffer.substr(1);
token = AProtocol::atlasATREND;
type = AProtocol::atlasLST;
state = 2;
break;
}
if (typ == ">") {
// end of typed list
buffer = buffer.substr(1);
token = AProtocol::atlasATREND;
type = AProtocol::atlasLST;
state = 2;
break;
}
if (typ == "]") {
// end of map
buffer = buffer.substr(1);
token = AProtocol::atlasATREND;
type = AProtocol::atlasMAP;
state = 2;
break;
}
if (typ == "}") {
// end of message
buffer = buffer.substr(1);
token = AProtocol::atlasMSGEND;
state = 1;
break;
}
// must be an attribute == wait until we got the name
if ((pos=buffer.find('=')) == -1) break;
// get the name out before proc
name = buffer.substr(1,pos-1);
buffer = buffer.substr(pos+1);
// got an attribute name
if (typ == "<") {
typ = buffer.substr(0,1);
if (typ == "!") type = AProtocol::atlasLSTURI;
if (typ == "@") type = AProtocol::atlasLSTINT;
if (typ == "#") type = AProtocol::atlasLSTFLT;
if (typ == "$") type = AProtocol::atlasLSTSTR;
if (typ == "%") type = AProtocol::atlasLSTLNG;
}
if (typ == "(") type = AProtocol::atlasLST;
if (typ == "[") type = AProtocol::atlasMAP;
if (typ == "@") type = AProtocol::atlasINT;
if (typ == "%") type = AProtocol::atlasLNG;
if (typ == "#") type = AProtocol::atlasFLT;
if (typ == "$") type = AProtocol::atlasSTR;
// change states, wait for value
token = AProtocol::atlasATRBEG;
if (type==AProtocol::atlasLST || type==AProtocol::atlasMAP) {
state = 2;
} else {
state = 3;
}
chk = 1;
break;
case 3:
pos = buffer.find_first_of("[(%$#])}");
if (pos == -1) break;
// got an end marker, pull the data
sval = buffer.substr(0,pos);
if (type == AProtocol::atlasINT) ival = atoi(sval.c_str());
if (type == AProtocol::atlasFLT) fval = atof(sval.c_str());
// strip up to token
buffer = buffer.substr(pos);
token = AProtocol::atlasATRVAL;
state = 4;
chk = 1;
break;
case 4: // special state to end attributes
token = AProtocol::atlasATREND;
state = 2;
chk = 1;
break;
default:
// invalid state
token =-1;
state =1;
break;
}
} while (chk == 1 && token == 0);
// see if we have a token to return
//printf("END TOKEN=%i\n", token);
//printf("END STATE=%i\n", state);
//printf("END BUFFR=%s\n\n\n", buffer.c_str());
if (token != 0) {
return 1;
}
return 0;
}
<commit_msg>Stream parser changes for typed lists and uris completed<commit_after>/*
AtlasProtocolDecoder.cpp
----------------
begin : 1999.11.29
copyright : (C) 1999 by John Barrett (ZW)
email : jbarrett@box100.com
*/
#include "AtlasObject.h"
#include "AtlasProtocol.h"
#include "AtlasPackedAsciiDecoder.h"
#include <memory.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string>
void APackedAsciiDecoder::newStream()
{
// reset decoder
state = 1;
nestd = 0;
token = 0;
}
void APackedAsciiDecoder::feedStream(string& data)
{
buffer.append(data);
}
int APackedAsciiDecoder::getToken()
{
int tmp = token;
token = 0;
return tmp;
}
int APackedAsciiDecoder::hasTokens()
{
int pos;
//int pos1;
//int ndx;
int chk;
string typ;
//printf("BEG TOKEN=%i\n", token);
if (token == -1) return-1; // buffer overflow !!!
do {
chk = 0;
//printf("BEG STATE=%i\n", state);
//printf("BEG BUFFR=%s\n", buffer.c_str());
// this is where we are gonna put the state machine
switch (state) {
case 1:// start of message
if((pos=buffer.find('{')) == -1) break;
buffer = buffer.substr(pos+1);
// change states
token = AProtocol::atlasMSGBEG;
state = 2;
chk = 1;
break;
case 2:
pos = buffer.find_first_of("[<(%$#])>}");
if (pos == -1) break;
if (pos != 0)
{
// bad protcol character
token = AProtocol::atlasERRTOK;
state = 1;
break;
}
typ = buffer.substr(0,1);
if (typ == ")") {
// end of list
buffer = buffer.substr(1);
token = AProtocol::atlasATREND;
type = AProtocol::atlasLST;
state = 2;
break;
}
if (typ == ">") {
// end of typed list
buffer = buffer.substr(1);
token = AProtocol::atlasATREND;
type = AProtocol::atlasLST;
state = 2;
break;
}
if (typ == "]") {
// end of map
buffer = buffer.substr(1);
token = AProtocol::atlasATREND;
type = AProtocol::atlasMAP;
state = 2;
break;
}
if (typ == "}") {
// end of message
buffer = buffer.substr(1);
token = AProtocol::atlasMSGEND;
state = 1;
break;
}
// must be an attribute == wait until we got the name
if ((pos=buffer.find('=')) == -1) break;
// get the name out before proc
name = buffer.substr(1,pos-1);
buffer = buffer.substr(pos+1);
// got an attribute name
if (typ == "<") {
typ = buffer.substr(0,1);
if (typ == "!") type = AProtocol::atlasLSTURI;
if (typ == "@") type = AProtocol::atlasLSTINT;
if (typ == "#") type = AProtocol::atlasLSTFLT;
if (typ == "$") type = AProtocol::atlasLSTSTR;
if (typ == "%") type = AProtocol::atlasLSTLNG;
}
if (typ == "(") type = AProtocol::atlasLST;
if (typ == "[") type = AProtocol::atlasMAP;
if (typ == "@") type = AProtocol::atlasINT;
if (typ == "%") type = AProtocol::atlasLNG;
if (typ == "#") type = AProtocol::atlasFLT;
if (typ == "$") type = AProtocol::atlasSTR;
// change states, wait for value
token = AProtocol::atlasATRBEG;
if (type==AProtocol::atlasLST || type==AProtocol::atlasMAP) {
state = 2;
} else {
state = 3;
}
chk = 1;
break;
case 3:
pos = buffer.find_first_of("[(<%$#]>)}");
if (pos == -1) break;
// got an end marker, pull the data
sval = buffer.substr(0,pos);
if (type == AProtocol::atlasINT) ival = atoi(sval.c_str());
if (type == AProtocol::atlasFLT) fval = atof(sval.c_str());
// strip up to token
buffer = buffer.substr(pos);
token = AProtocol::atlasATRVAL;
state = 4;
chk = 1;
break;
case 4: // special state to end attributes
token = AProtocol::atlasATREND;
state = 2;
chk = 1;
break;
default:
// invalid state
token =-1;
state =1;
break;
}
} while (chk == 1 && token == 0);
// see if we have a token to return
//printf("END TOKEN=%i\n", token);
//printf("END STATE=%i\n", state);
//printf("END BUFFR=%s\n\n\n", buffer.c_str());
if (token != 0) {
return 1;
}
return 0;
}
<|endoftext|>
|
<commit_before>/**
@file common_types.hpp
@brief Common types.
@author Tim Howard
@copyright 2013 Tim Howard under the MIT license;
see @ref index or the accompanying LICENSE file for full text.
*/
#ifndef HORD_COMMON_TYPES_HPP_
#define HORD_COMMON_TYPES_HPP_
#include "./config.hpp"
namespace Hord {
/** Generic object ID. */
typedef uint32_t ObjectID;
enum : ObjectID {
/** Null object. */
OBJECT_NULL
};
/**
@addtogroup metadata
@{
*/
/** MetaField type. */
typedef uint8_t MetaFieldType;
/** @} */ // end of doc-group metadata
/**
@addtogroup node
@{
*/
/** Node ID. */
typedef ObjectID NodeID;
/**
@addtogroup rule
@{
*/
/** Rule ID. */
typedef ObjectID RuleID;
/** Rule type. */
typedef uint32_t RuleType;
/** @} */ // end of doc-group rule
/** @} */ // end of doc-group node
} // namespace Hord
#endif // HORD_COMMON_TYPES_HPP_
<commit_msg>common_types: added HiveID typedef and note for specialized ID types.<commit_after>/**
@file common_types.hpp
@brief Common types.
@author Tim Howard
@copyright 2013 Tim Howard under the MIT license;
see @ref index or the accompanying LICENSE file for full text.
*/
#ifndef HORD_COMMON_TYPES_HPP_
#define HORD_COMMON_TYPES_HPP_
#include "./config.hpp"
namespace Hord {
/**
@addtogroup object
@{
*/
/** Generic object ID. */
typedef uint32_t ObjectID;
enum : ObjectID {
/** Null object. */
OBJECT_NULL=0
};
/** @} */ // end of doc-group object
/**
@addtogroup metadata
@{
*/
/** MetaField type. */
typedef uint8_t MetaFieldType;
/** @} */ // end of doc-group metadata
/**
@addtogroup driver
@{
*/
/**
@addtogroup hive
@{
*/
/**
Hive ID.
@note This type is only to telegraph intent in functions;
it is entirely equivalent to ObjectID.
*/
typedef ObjectID HiveID;
/** @} */ // end of doc-group hive
/** @} */ // end of doc-group driver
/**
@addtogroup node
@{
*/
/**
Node ID.
@note This type is only to telegraph intent in functions;
it is entirely equivalent to ObjectID.
*/
typedef ObjectID NodeID;
/**
@addtogroup rule
@{
*/
/**
Rule ID.
@note This type is only to telegraph intent in functions;
it is entirely equivalent to ObjectID.
*/
typedef ObjectID RuleID;
/** Rule type. */
typedef uint32_t RuleType;
/** @} */ // end of doc-group rule
/** @} */ // end of doc-group node
} // namespace Hord
#endif // HORD_COMMON_TYPES_HPP_
<|endoftext|>
|
<commit_before><commit_msg>wait 10 sec before trying to resync clock again<commit_after><|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: layact.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: hr $ $Date: 2003-04-28 15:17:17 $
*
* 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 _LAYACT_HXX
#define _LAYACT_HXX
#include "swtypes.hxx"
#include "swrect.hxx"
class SwRootFrm;
class SwLayoutFrm;
class SwPageFrm;
class SwFlyFrm;
class SwFlyInCntFrm;
class SwCntntFrm;
class SwTabFrm;
class SwViewImp;
class SwCntntNode;
class SwWait;
//Die Verwendung der LayAction laeuft immer gleich ab:
//
// 1. Erzeugen des LayAction-Objektes.
// 2. Einstellen des gewuenschten Verhaltens mittels der Set-Methoden
// 3. Aufruf von Action()
// 4. Baldiges Zerstoeren des Objektes.
//
// Das Objekt meldet sich im CTor beim SwViewImp an und erst im DTor
// wieder ab! Es handelt sich mithin um ein typisches Stackobjekt.
class SwLayAction
{
SwRootFrm *pRoot;
SwViewImp *pImp; //Hier Meldet sich die Action an und ab.
//Zur Optimierung, damit die Tabellen etwas besser am Crsr kleben beim
//Return/Backspace davor.
//Wenn der erste TabFrm, der sich Paintet (pro Seite) traegt sich im
//Pointer ein. Die CntntFrms unterhalb der Seite brauchen sich
//dann nicht mehr bei der Shell zum Painten anmelden.
const SwTabFrm *pOptTab;
SwWait *pWait;
SfxProgress * pProgress;
//Wenn ein Absatz - oder was auch immer - bei der Formatierung mehr
//als eine Seite rueckwaerts floss traegt er seine neue Seitennummer
//hier ein. Die Steuerung der InternalAction kann dann geeignet reagieren.
USHORT nPreInvaPage;
ULONG nStartTicks; //Startzeitpunkt der Aktion, vergeht zu viel Zeit kann
//der WaitCrsr per CheckWaitCrsr() eingeschaltet werden.
USHORT nInputType; //Bei welchem Input soll die Verarbeitung abgebrochen
//werden?
USHORT nEndPage; //StatBar Steuerung.
USHORT nCheckPageNum; //CheckPageDesc() wurde verzoegert wenn != USHRT_MAX
//ab dieser Seite Checken.
BOOL bPaint; //Painten oder nur Formatieren?
BOOL bComplete; //Alles bis zum sichtbaren Bereich Formatieren oder
//oder nur den sichtbaren Bereich?
BOOL bCalcLayout; //Vollstaendige Reformatierung?
BOOL bAgain; //Zur automatisch wiederholten Action wenn Seiten
//geloscht werden.
BOOL bNextCycle; //Wiederaufsetzen bei der ersten Ungueltigen Seite.
BOOL bInput; //Zum Abbrechen der Verarbeitung wenn ein Input anliegt.
BOOL bIdle; //True wenn die Layaction vom Idler ausgeloest wurde.
BOOL bReschedule; //Soll das Reschedule - abhaengig vom Progress -
//gerufen werden?
BOOL bCheckPages; //CheckPageDescs() ausfuehren oder verzoegern.
BOOL bUpdateExpFlds;//Wird gesetzt wenn nach dem Formatierien noch eine
//Runde fuer den ExpFld laufen muss.
BOOL bBrowseActionStop; //Action fruehzeitig beenden (per bInput) und den
//Rest dem Idler ueberlassen.
BOOL bWaitAllowed; //Wartecursor erlaubt?
BOOL bPaintExtraData; //Anzeige von Zeilennumerierung o. ae. eingeschaltet?
BOOL bActionInProgress; // wird in Action() anfangs gesetzt und zum Schluss geloescht
// OD 14.04.2003 #106346# - new flag for content formatting on interrupt.
sal_Bool mbFormatCntntOnInterrupt;
#ifdef _LAYACT_CXX
void _AddScrollRect( const SwCntntFrm *, const SwPageFrm *,
const SwTwips, const SwTwips );
void PaintCntnt( const SwCntntFrm *, const SwPageFrm *,
const SwRect &rOldRect, long nOldBottom );
BOOL PaintWithoutFlys( const SwRect &, const SwCntntFrm *,
const SwPageFrm * );
inline BOOL _PaintCntnt( const SwCntntFrm *, const SwPageFrm *,
const SwRect & );
void ChkFlyAnchor( SwFlyFrm *, const SwPageFrm * );
void FormatFlyLayout( const SwPageFrm * );
BOOL FormatFlyCntnt( const SwPageFrm *, sal_Bool bDontShrink );
BOOL _FormatFlyCntnt( const SwFlyFrm * );
BOOL __FormatFlyCntnt( const SwCntntFrm * );
void FormatFlyInCnt( SwFlyInCntFrm* );
BOOL FormatLayout( SwLayoutFrm *, BOOL bAddRect = TRUE );
BOOL FormatLayoutTab( SwTabFrm *, BOOL bAddRect = TRUE );
BOOL FormatLayoutFly( SwFlyFrm *, BOOL bAddRect = TRUE );
BOOL FormatCntnt( const SwPageFrm* pPage );
void _FormatCntnt( const SwCntntFrm* pCntnt,
const SwPageFrm* pPage );
BOOL IsShortCut( SwPageFrm *& );
BOOL TurboAction();
BOOL _TurboAction( const SwCntntFrm * );
void InternalAction();
SwPageFrm *CheckFirstVisPage( SwPageFrm *pPage );
BOOL RemoveEmptyBrowserPages();
inline void CheckIdleEnd();
inline ULONG GetStartTicks() { return nStartTicks; }
#endif
public:
SwLayAction( SwRootFrm *pRt, SwViewImp *pImp );
~SwLayAction();
#ifdef _LAYACT_CXX
void SetIdle ( BOOL bNew ) { bIdle = bNew; }
void SetCheckPages ( BOOL bNew ) { bCheckPages = bNew; }
void SetBrowseActionStop(BOOL bNew ) { bBrowseActionStop = bNew; }
void SetNextCycle ( BOOL bNew ) { bNextCycle = bNew; }
BOOL IsWaitAllowed() const { return bWaitAllowed; }
BOOL IsNextCycle() const { return bNextCycle; }
BOOL IsInput() const { return bInput; }
BOOL IsWait() const { return 0 != pWait; }
BOOL IsPaint() const { return bPaint; }
BOOL IsIdle() const { return bIdle; }
BOOL IsReschedule() const { return bReschedule; }
BOOL IsPaintExtraData() const { return bPaintExtraData;}
BOOL IsStopPrt() const;
BOOL IsInterrupt() const { return IsInput() || IsStopPrt(); }
USHORT GetInputType() const { return nInputType; }
#endif
//Einstellen der Action auf das gewuenschte Verhalten.
void SetPaint ( BOOL bNew ) { bPaint = bNew; }
void SetComplete ( BOOL bNew ) { bComplete = bNew; }
void SetStatBar ( BOOL bNew );
void SetInputType ( USHORT nNew ) { nInputType = nNew; }
void SetCalcLayout ( BOOL bNew ) { bCalcLayout = bNew; }
void SetReschedule ( BOOL bNew ) { bReschedule = bNew; }
void SetWaitAllowed ( BOOL bNew ) { bWaitAllowed = bNew; }
void SetAgain() { bAgain = TRUE; }
void SetUpdateExpFlds() {bUpdateExpFlds = TRUE; }
void SetProgress(SfxProgress * _pProgress = NULL)
{ pProgress = _pProgress; }
inline void SetCheckPageNum( USHORT nNew );
inline void SetCheckPageNumDirect( USHORT nNew ) { nCheckPageNum = nNew; }
void Action(); //Jetzt gehts loos...
void Reset(); //Zurueck auf CTor-Defaults.
BOOL IsAgain() const { return bAgain; }
BOOL IsComplete() const { return bComplete; }
BOOL IsExpFlds() const { return bUpdateExpFlds; }
BOOL IsCalcLayout() const { return bCalcLayout; }
BOOL IsCheckPages() const { return bCheckPages; }
BOOL IsBrowseActionStop() const { return bBrowseActionStop; }
BOOL IsActionInProgress() const { return bActionInProgress; }
USHORT GetCheckPageNum() const { return nCheckPageNum; }
//Auch andere sollen den Wartecrsr einschalten koennen.
void CheckWaitCrsr();
};
class SwLayIdle
{
SwRootFrm *pRoot;
SwViewImp *pImp; // Hier Meldet sich der Idler an und ab.
SwCntntNode *pCntntNode; // Hier wird die aktuelle Cursorposition
xub_StrLen nTxtPos; // zwischengespeichert.
BOOL bPageValid; // Konnte die Seite alles validiert werden?
BOOL bAllValid; // Konnte alles validiert werden?
#ifndef PRODUCT
BOOL bIndicator;
#endif
#ifdef _LAYACT_CXX
#ifndef PRODUCT
void ShowIdle( ColorData eName );
#endif
BOOL _FormatSpelling( const SwCntntFrm * );
BOOL FormatSpelling( BOOL );
BOOL _CollectAutoCmplWords( const SwCntntFrm *, BOOL bOnlyVisArea );
BOOL CollectAutoCmplWords( BOOL );
#endif
public:
SwLayIdle( SwRootFrm *pRt, SwViewImp *pImp );
~SwLayIdle();
};
inline void SwLayAction::SetCheckPageNum( USHORT nNew )
{
if ( nNew < nCheckPageNum )
nCheckPageNum = nNew;
}
#endif //_LAYACT_HXX
<commit_msg>INTEGRATION: CWS swobjpos04 (1.4.516); FILE MERGED 2004/06/30 14:58:56 od 1.4.516.3: #i28701# - merge changes of cws swdrawpositioning - further adjustments for the new object positioning 2004/06/14 13:27:05 od 1.4.516.2: #i28701# - further adjustments for the new positioning of floating screen objects. 2004/05/24 13:00:57 od 1.4.516.1: #i28701# - usage of new class <SwSortedObjs> - adjustments for the new positioning of floating screen objects<commit_after>/*************************************************************************
*
* $RCSfile: layact.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: kz $ $Date: 2004-08-02 14:05:30 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER 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 _LAYACT_HXX
#define _LAYACT_HXX
#include "swtypes.hxx"
#include "swrect.hxx"
class SwRootFrm;
class SwLayoutFrm;
class SwPageFrm;
class SwFlyFrm;
class SwFlyInCntFrm;
class SwCntntFrm;
class SwTabFrm;
class SwViewImp;
class SwCntntNode;
class SwWait;
// --> OD 2004-06-28 #i28701#
class SfxProgress;
//Die Verwendung der LayAction laeuft immer gleich ab:
//
// 1. Erzeugen des LayAction-Objektes.
// 2. Einstellen des gewuenschten Verhaltens mittels der Set-Methoden
// 3. Aufruf von Action()
// 4. Baldiges Zerstoeren des Objektes.
//
// Das Objekt meldet sich im CTor beim SwViewImp an und erst im DTor
// wieder ab! Es handelt sich mithin um ein typisches Stackobjekt.
class SwLayAction
{
SwRootFrm *pRoot;
SwViewImp *pImp; //Hier Meldet sich die Action an und ab.
//Zur Optimierung, damit die Tabellen etwas besser am Crsr kleben beim
//Return/Backspace davor.
//Wenn der erste TabFrm, der sich Paintet (pro Seite) traegt sich im
//Pointer ein. Die CntntFrms unterhalb der Seite brauchen sich
//dann nicht mehr bei der Shell zum Painten anmelden.
const SwTabFrm *pOptTab;
SwWait *pWait;
SfxProgress * pProgress;
//Wenn ein Absatz - oder was auch immer - bei der Formatierung mehr
//als eine Seite rueckwaerts floss traegt er seine neue Seitennummer
//hier ein. Die Steuerung der InternalAction kann dann geeignet reagieren.
USHORT nPreInvaPage;
ULONG nStartTicks; //Startzeitpunkt der Aktion, vergeht zu viel Zeit kann
//der WaitCrsr per CheckWaitCrsr() eingeschaltet werden.
USHORT nInputType; //Bei welchem Input soll die Verarbeitung abgebrochen
//werden?
USHORT nEndPage; //StatBar Steuerung.
USHORT nCheckPageNum; //CheckPageDesc() wurde verzoegert wenn != USHRT_MAX
//ab dieser Seite Checken.
BOOL bPaint; //Painten oder nur Formatieren?
BOOL bComplete; //Alles bis zum sichtbaren Bereich Formatieren oder
//oder nur den sichtbaren Bereich?
BOOL bCalcLayout; //Vollstaendige Reformatierung?
BOOL bAgain; //Zur automatisch wiederholten Action wenn Seiten
//geloscht werden.
BOOL bNextCycle; //Wiederaufsetzen bei der ersten Ungueltigen Seite.
BOOL bInput; //Zum Abbrechen der Verarbeitung wenn ein Input anliegt.
BOOL bIdle; //True wenn die Layaction vom Idler ausgeloest wurde.
BOOL bReschedule; //Soll das Reschedule - abhaengig vom Progress -
//gerufen werden?
BOOL bCheckPages; //CheckPageDescs() ausfuehren oder verzoegern.
BOOL bUpdateExpFlds;//Wird gesetzt wenn nach dem Formatierien noch eine
//Runde fuer den ExpFld laufen muss.
BOOL bBrowseActionStop; //Action fruehzeitig beenden (per bInput) und den
//Rest dem Idler ueberlassen.
BOOL bWaitAllowed; //Wartecursor erlaubt?
BOOL bPaintExtraData; //Anzeige von Zeilennumerierung o. ae. eingeschaltet?
BOOL bActionInProgress; // wird in Action() anfangs gesetzt und zum Schluss geloescht
// OD 14.04.2003 #106346# - new flag for content formatting on interrupt.
sal_Bool mbFormatCntntOnInterrupt;
// --> OD 2004-06-14 #i28701# - new flag, indicating, if scrolling is
// allowed during page format
bool mbScrollingAllowed;
#ifdef _LAYACT_CXX
void _AddScrollRect( const SwCntntFrm *, const SwPageFrm *,
const SwTwips, const SwTwips );
void PaintCntnt( const SwCntntFrm *, const SwPageFrm *,
const SwRect &rOldRect, long nOldBottom );
BOOL PaintWithoutFlys( const SwRect &, const SwCntntFrm *,
const SwPageFrm * );
inline BOOL _PaintCntnt( const SwCntntFrm *, const SwPageFrm *,
const SwRect & );
BOOL FormatLayout( SwLayoutFrm *, BOOL bAddRect = TRUE );
BOOL FormatLayoutTab( SwTabFrm *, BOOL bAddRect = TRUE );
BOOL FormatCntnt( const SwPageFrm* pPage );
void _FormatCntnt( const SwCntntFrm* pCntnt,
const SwPageFrm* pPage );
BOOL IsShortCut( SwPageFrm *& );
BOOL TurboAction();
BOOL _TurboAction( const SwCntntFrm * );
void InternalAction();
SwPageFrm *CheckFirstVisPage( SwPageFrm *pPage );
BOOL RemoveEmptyBrowserPages();
inline void CheckIdleEnd();
inline ULONG GetStartTicks() { return nStartTicks; }
#endif
public:
SwLayAction( SwRootFrm *pRt, SwViewImp *pImp );
~SwLayAction();
#ifdef _LAYACT_CXX
void SetIdle ( BOOL bNew ) { bIdle = bNew; }
void SetCheckPages ( BOOL bNew ) { bCheckPages = bNew; }
void SetBrowseActionStop(BOOL bNew ) { bBrowseActionStop = bNew; }
void SetNextCycle ( BOOL bNew ) { bNextCycle = bNew; }
BOOL IsWaitAllowed() const { return bWaitAllowed; }
BOOL IsNextCycle() const { return bNextCycle; }
BOOL IsInput() const { return bInput; }
BOOL IsWait() const { return 0 != pWait; }
BOOL IsPaint() const { return bPaint; }
BOOL IsIdle() const { return bIdle; }
BOOL IsReschedule() const { return bReschedule; }
BOOL IsPaintExtraData() const { return bPaintExtraData;}
BOOL IsStopPrt() const;
BOOL IsInterrupt() const { return IsInput() || IsStopPrt(); }
USHORT GetInputType() const { return nInputType; }
#endif
//Einstellen der Action auf das gewuenschte Verhalten.
void SetPaint ( BOOL bNew ) { bPaint = bNew; }
void SetComplete ( BOOL bNew ) { bComplete = bNew; }
void SetStatBar ( BOOL bNew );
void SetInputType ( USHORT nNew ) { nInputType = nNew; }
void SetCalcLayout ( BOOL bNew ) { bCalcLayout = bNew; }
void SetReschedule ( BOOL bNew ) { bReschedule = bNew; }
void SetWaitAllowed ( BOOL bNew ) { bWaitAllowed = bNew; }
void SetAgain() { bAgain = TRUE; }
void SetUpdateExpFlds() {bUpdateExpFlds = TRUE; }
void SetProgress(SfxProgress * _pProgress = NULL)
{ pProgress = _pProgress; }
inline void SetCheckPageNum( USHORT nNew );
inline void SetCheckPageNumDirect( USHORT nNew ) { nCheckPageNum = nNew; }
void Action(); //Jetzt gehts loos...
void Reset(); //Zurueck auf CTor-Defaults.
BOOL IsAgain() const { return bAgain; }
BOOL IsComplete() const { return bComplete; }
BOOL IsExpFlds() const { return bUpdateExpFlds; }
BOOL IsCalcLayout() const { return bCalcLayout; }
BOOL IsCheckPages() const { return bCheckPages; }
BOOL IsBrowseActionStop() const { return bBrowseActionStop; }
BOOL IsActionInProgress() const { return bActionInProgress; }
USHORT GetCheckPageNum() const { return nCheckPageNum; }
//Auch andere sollen den Wartecrsr einschalten koennen.
void CheckWaitCrsr();
// --> OD 2004-06-09 #i28701# - method is now public;
// delete 2nd parameter, because its not used;
BOOL FormatLayoutFly( SwFlyFrm * );
// --> OD 2004-06-09 #i28701# - method is now public
BOOL _FormatFlyCntnt( const SwFlyFrm * );
};
class SwLayIdle
{
SwRootFrm *pRoot;
SwViewImp *pImp; // Hier Meldet sich der Idler an und ab.
SwCntntNode *pCntntNode; // Hier wird die aktuelle Cursorposition
xub_StrLen nTxtPos; // zwischengespeichert.
BOOL bPageValid; // Konnte die Seite alles validiert werden?
BOOL bAllValid; // Konnte alles validiert werden?
#ifndef PRODUCT
BOOL bIndicator;
#endif
#ifdef _LAYACT_CXX
#ifndef PRODUCT
void ShowIdle( ColorData eName );
#endif
BOOL _FormatSpelling( const SwCntntFrm * );
BOOL FormatSpelling( BOOL );
BOOL _CollectAutoCmplWords( const SwCntntFrm *, BOOL bOnlyVisArea );
BOOL CollectAutoCmplWords( BOOL );
#endif
public:
SwLayIdle( SwRootFrm *pRt, SwViewImp *pImp );
~SwLayIdle();
};
inline void SwLayAction::SetCheckPageNum( USHORT nNew )
{
if ( nNew < nCheckPageNum )
nCheckPageNum = nNew;
}
#endif //_LAYACT_HXX
<|endoftext|>
|
<commit_before>/*
Copyright (C) 2011-2014 Yubico AB. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "yubikeyutil.h"
#include <yubikey.h>
#include <QDebug>
#ifdef Q_OS_WIN
#include "crandom.h"
#endif
YubiKeyUtil::~YubiKeyUtil() {
}
int YubiKeyUtil::hexModhexDecode(unsigned char *result, size_t *resultLen,
const char *str, size_t strLen,
size_t minSize, size_t maxSize,
bool modhex)
{
if ((strLen % 2 != 0) || (strLen < minSize) || (strLen > maxSize)) {
return -1;
}
*resultLen = strLen / 2;
if (modhex) {
if (yubikey_modhex_p(str)) {
yubikey_modhex_decode((char *)result, str, strLen);
return 1;
}
} else {
if (yubikey_hex_p(str)) {
yubikey_hex_decode((char *)result, str, strLen);
return 1;
}
}
return 0;
}
int YubiKeyUtil::hexModhexEncode(char *result, size_t *resultLen,
const unsigned char *str, size_t strLen,
bool modhex)
{
*resultLen = strLen * 2;
if (modhex) {
yubikey_modhex_encode((char *)result, (char *)str, strLen);
return 1;
} else {
yubikey_hex_encode((char *)result, (char *)str, strLen);
return 1;
}
return 0;
}
QString YubiKeyUtil::qstrHexEncode(const unsigned char *str, size_t strLen) {
char result[strLen * 2 + 1];
size_t resultLen = 0;
memset(&result, 0, sizeof(result));
int rc = hexModhexEncode(result, &resultLen, str, strLen, false);
if(rc > 0) {
qDebug() << "hex encoded string: " << QString(result) << sizeof(result);
return QString::fromLocal8Bit(result);
}
return QString("");
}
void YubiKeyUtil::qstrHexDecode(unsigned char *result, size_t *resultLen,
const QString &str) {
if(str.size() % 2 != 0) {
return;
}
char hex[MAX_SIZE];
YubiKeyUtil::qstrToRaw(hex, sizeof(hex), str);
size_t hexLen = strlen(hex);
//Hex decode
hexModhexDecode(result, resultLen,
hex, hexLen,
0, MAX_SIZE,
false);
}
QString YubiKeyUtil::qstrModhexEncode(const unsigned char *str, size_t strLen) {
char result[strLen * 2 + 1];
size_t resultLen = 0;
memset(&result, 0, sizeof(result));
int rc = hexModhexEncode(result, &resultLen, str, strLen, true);
if(rc > 0) {
qDebug() << "modhex encoded string: " << QString(result) << sizeof(result);
return QString::fromLocal8Bit(result);
}
return QString("");
}
void YubiKeyUtil::qstrModhexDecode(unsigned char *result, size_t *resultLen,
const QString &str) {
if(str.size() % 2 != 0) {
return;
}
char modhex[MAX_SIZE];
YubiKeyUtil::qstrToRaw(modhex, sizeof(modhex), str);
size_t modhexLen = strlen(modhex);
//Hex decode
hexModhexDecode(result, resultLen,
modhex, modhexLen,
0, MAX_SIZE,
true);
}
void YubiKeyUtil::qstrDecDecode(unsigned char *result, size_t *resultLen,
const QString &str) {
if(str.size() % 2 != 0) {
return;
}
*resultLen = str.size() / 2;
for(size_t i = 0; i < *resultLen; i++) {
unsigned char val = str.mid(i * 2, 2).toInt();
result[i] = ((val / 10) << 4) | (val % 10);
}
}
void YubiKeyUtil::qstrToRaw(char *result, size_t resultLen,
const QString &str) {
QByteArray strByteArr = str.toLocal8Bit();
size_t strLen = strByteArr.size() + 1;
strLen = (resultLen < strLen)? resultLen : strLen;
memset(result, 0, strLen);
strncpy(result, (char *) strByteArr.data(), strLen);
}
void YubiKeyUtil::qstrClean(QString *str, size_t maxSize, bool reverse) {
*str = str->toLower();
QRegExp rx("[^0-9a-f]");
*str = str->replace(rx, QString(""));
if(maxSize > 0) {
if(reverse) {
*str = str->rightJustified(maxSize, '0', true);
} else {
*str = str->leftJustified(maxSize, '0', true);
}
}
}
void YubiKeyUtil::qstrModhexClean(QString *str, size_t maxSize, bool reverse) {
*str = str->toLower();
QRegExp rx("[^b-lnrt-v]");
*str = str->replace(rx, QString(""));
if(maxSize > 0) {
if(reverse) {
*str = str->rightJustified(maxSize, 'c', true);
} else {
*str = str->leftJustified(maxSize, 'c', true);
}
}
}
int YubiKeyUtil::generateRandom(unsigned char *result, size_t resultLen) {
size_t bufSize = resultLen;
unsigned char buf[bufSize];
memset(&buf, 0, sizeof(buf));
size_t bufLen = 0;
#ifdef Q_OS_WIN
CRandom random;
random.getRand(buf, bufSize);
bufLen = sizeof(buf);
#else
const char *random_places[] = {
"/dev/srandom",
"/dev/urandom",
"/dev/random",
0
};
const char **random_place;
for (random_place = random_places; *random_place; random_place++) {
FILE *random_file = fopen(*random_place, "r");
if (random_file) {
size_t read_bytes = 0;
while (read_bytes < bufSize) {
size_t n = fread(&buf[read_bytes],
1, bufSize - read_bytes,
random_file);
read_bytes += n;
}
fclose(random_file);
bufLen = sizeof(buf);
break; /* from for loop */
}
}
#endif
if(bufLen > 0) {
memcpy(result, buf, bufLen);
return 1;
}
return 0;
}
QString YubiKeyUtil::generateRandomHex(size_t resultLen) {
QString result("");
if (resultLen % 2 != 0) {
return result;
}
size_t bufSize = resultLen / 2;
unsigned char buf[bufSize];
memset(&buf, 0, sizeof(buf));
if(generateRandom(buf, bufSize) > 0) {
result = qstrHexEncode(buf, bufSize);
}
return result;
}
QString YubiKeyUtil::generateRandomModhex(size_t resultLen) {
QString result("");
if (resultLen % 2 != 0) {
return result;
}
size_t bufSize = resultLen / 2;
unsigned char buf[bufSize];
memset(&buf, 0, sizeof(buf));
if(generateRandom(buf, bufSize) > 0) {
result = qstrModhexEncode(buf, bufSize);
}
return result;
}
QString YubiKeyUtil::getNextHex(size_t resultLen,
const QString &str, int scheme) {
QString result("");
qDebug() << "str = " << str
<< " len = " << str.length();
switch(scheme) {
case GEN_SCHEME_FIXED:
result = str;
break;
case GEN_SCHEME_INCR:
{
//Hex clean
QString hexStr(str);
qstrClean(&hexStr, resultLen);
//Hex decode
unsigned char hexDecoded[MAX_SIZE];
size_t hexDecodedLen = 0;
memset(&hexDecoded, 0, sizeof(hexDecoded));
qstrHexDecode(hexDecoded, &hexDecodedLen, hexStr);
if(hexDecodedLen <= 0) {
break;
}
qDebug() << "hexDecoded = " << QString((char*)hexDecoded)
<< " len = " << hexDecodedLen;
//Increment
for (int i = hexDecodedLen; i--; ) {
if (++hexDecoded[i]) {
break;
}
}
//Hex encode
result = qstrHexEncode(hexDecoded, hexDecodedLen);
qDebug() << "hexEncoded = " << result
<< " len = " << result.size();
}
break;
case GEN_SCHEME_RAND:
result = generateRandomHex(resultLen);
break;
}
return result;
}
QString YubiKeyUtil::getNextModhex(size_t resultLen,
const QString &str, int scheme) {
QString result("");
qDebug() << "str = " << str
<< " len = " << str.length();
switch(scheme) {
case GEN_SCHEME_FIXED:
result = str;
break;
case GEN_SCHEME_INCR:
{
//Modhex clean
QString modhexStr(str);
qstrModhexClean(&modhexStr, resultLen);
//Modhex decode
unsigned char modhexDecoded[MAX_SIZE];
size_t modhexDecodedLen = 0;
memset(&modhexDecoded, 0, sizeof(modhexDecoded));
qstrModhexDecode(modhexDecoded, &modhexDecodedLen, modhexStr);
if(modhexDecodedLen <= 0) {
break;
}
qDebug() << "modhexDecoded = " << QString((char*)modhexDecoded)
<< " len = " << modhexDecodedLen;
//Increment
for (int i = modhexDecodedLen; i--; ) {
if (++modhexDecoded[i]) {
break;
}
}
//Modhex encode
result = qstrModhexEncode(modhexDecoded, modhexDecodedLen);
qDebug() << "modhexEncoded = " << result
<< " len = " << result.size();
}
break;
case GEN_SCHEME_RAND:
result = generateRandomModhex(resultLen);
break;
}
return result;
}
void YubiKeyUtil::hexdump(void *buffer, int size) {
unsigned char *p = (unsigned char *)buffer;
int i;
for (i = 0; i < size; i++) {
fprintf(stderr, "\\x%02x", *p);
p++;
}
fprintf(stderr, "\n");
fflush(stderr);
}
<commit_msg>include QRegExp<commit_after>/*
Copyright (C) 2011-2014 Yubico AB. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "yubikeyutil.h"
#include <yubikey.h>
#include <QDebug>
#include <QRegExp>
#ifdef Q_OS_WIN
#include "crandom.h"
#endif
YubiKeyUtil::~YubiKeyUtil() {
}
int YubiKeyUtil::hexModhexDecode(unsigned char *result, size_t *resultLen,
const char *str, size_t strLen,
size_t minSize, size_t maxSize,
bool modhex)
{
if ((strLen % 2 != 0) || (strLen < minSize) || (strLen > maxSize)) {
return -1;
}
*resultLen = strLen / 2;
if (modhex) {
if (yubikey_modhex_p(str)) {
yubikey_modhex_decode((char *)result, str, strLen);
return 1;
}
} else {
if (yubikey_hex_p(str)) {
yubikey_hex_decode((char *)result, str, strLen);
return 1;
}
}
return 0;
}
int YubiKeyUtil::hexModhexEncode(char *result, size_t *resultLen,
const unsigned char *str, size_t strLen,
bool modhex)
{
*resultLen = strLen * 2;
if (modhex) {
yubikey_modhex_encode((char *)result, (char *)str, strLen);
return 1;
} else {
yubikey_hex_encode((char *)result, (char *)str, strLen);
return 1;
}
return 0;
}
QString YubiKeyUtil::qstrHexEncode(const unsigned char *str, size_t strLen) {
char result[strLen * 2 + 1];
size_t resultLen = 0;
memset(&result, 0, sizeof(result));
int rc = hexModhexEncode(result, &resultLen, str, strLen, false);
if(rc > 0) {
qDebug() << "hex encoded string: " << QString(result) << sizeof(result);
return QString::fromLocal8Bit(result);
}
return QString("");
}
void YubiKeyUtil::qstrHexDecode(unsigned char *result, size_t *resultLen,
const QString &str) {
if(str.size() % 2 != 0) {
return;
}
char hex[MAX_SIZE];
YubiKeyUtil::qstrToRaw(hex, sizeof(hex), str);
size_t hexLen = strlen(hex);
//Hex decode
hexModhexDecode(result, resultLen,
hex, hexLen,
0, MAX_SIZE,
false);
}
QString YubiKeyUtil::qstrModhexEncode(const unsigned char *str, size_t strLen) {
char result[strLen * 2 + 1];
size_t resultLen = 0;
memset(&result, 0, sizeof(result));
int rc = hexModhexEncode(result, &resultLen, str, strLen, true);
if(rc > 0) {
qDebug() << "modhex encoded string: " << QString(result) << sizeof(result);
return QString::fromLocal8Bit(result);
}
return QString("");
}
void YubiKeyUtil::qstrModhexDecode(unsigned char *result, size_t *resultLen,
const QString &str) {
if(str.size() % 2 != 0) {
return;
}
char modhex[MAX_SIZE];
YubiKeyUtil::qstrToRaw(modhex, sizeof(modhex), str);
size_t modhexLen = strlen(modhex);
//Hex decode
hexModhexDecode(result, resultLen,
modhex, modhexLen,
0, MAX_SIZE,
true);
}
void YubiKeyUtil::qstrDecDecode(unsigned char *result, size_t *resultLen,
const QString &str) {
if(str.size() % 2 != 0) {
return;
}
*resultLen = str.size() / 2;
for(size_t i = 0; i < *resultLen; i++) {
unsigned char val = str.mid(i * 2, 2).toInt();
result[i] = ((val / 10) << 4) | (val % 10);
}
}
void YubiKeyUtil::qstrToRaw(char *result, size_t resultLen,
const QString &str) {
QByteArray strByteArr = str.toLocal8Bit();
size_t strLen = strByteArr.size() + 1;
strLen = (resultLen < strLen)? resultLen : strLen;
memset(result, 0, strLen);
strncpy(result, (char *) strByteArr.data(), strLen);
}
void YubiKeyUtil::qstrClean(QString *str, size_t maxSize, bool reverse) {
*str = str->toLower();
QRegExp rx("[^0-9a-f]");
*str = str->replace(rx, QString(""));
if(maxSize > 0) {
if(reverse) {
*str = str->rightJustified(maxSize, '0', true);
} else {
*str = str->leftJustified(maxSize, '0', true);
}
}
}
void YubiKeyUtil::qstrModhexClean(QString *str, size_t maxSize, bool reverse) {
*str = str->toLower();
QRegExp rx("[^b-lnrt-v]");
*str = str->replace(rx, QString(""));
if(maxSize > 0) {
if(reverse) {
*str = str->rightJustified(maxSize, 'c', true);
} else {
*str = str->leftJustified(maxSize, 'c', true);
}
}
}
int YubiKeyUtil::generateRandom(unsigned char *result, size_t resultLen) {
size_t bufSize = resultLen;
unsigned char buf[bufSize];
memset(&buf, 0, sizeof(buf));
size_t bufLen = 0;
#ifdef Q_OS_WIN
CRandom random;
random.getRand(buf, bufSize);
bufLen = sizeof(buf);
#else
const char *random_places[] = {
"/dev/srandom",
"/dev/urandom",
"/dev/random",
0
};
const char **random_place;
for (random_place = random_places; *random_place; random_place++) {
FILE *random_file = fopen(*random_place, "r");
if (random_file) {
size_t read_bytes = 0;
while (read_bytes < bufSize) {
size_t n = fread(&buf[read_bytes],
1, bufSize - read_bytes,
random_file);
read_bytes += n;
}
fclose(random_file);
bufLen = sizeof(buf);
break; /* from for loop */
}
}
#endif
if(bufLen > 0) {
memcpy(result, buf, bufLen);
return 1;
}
return 0;
}
QString YubiKeyUtil::generateRandomHex(size_t resultLen) {
QString result("");
if (resultLen % 2 != 0) {
return result;
}
size_t bufSize = resultLen / 2;
unsigned char buf[bufSize];
memset(&buf, 0, sizeof(buf));
if(generateRandom(buf, bufSize) > 0) {
result = qstrHexEncode(buf, bufSize);
}
return result;
}
QString YubiKeyUtil::generateRandomModhex(size_t resultLen) {
QString result("");
if (resultLen % 2 != 0) {
return result;
}
size_t bufSize = resultLen / 2;
unsigned char buf[bufSize];
memset(&buf, 0, sizeof(buf));
if(generateRandom(buf, bufSize) > 0) {
result = qstrModhexEncode(buf, bufSize);
}
return result;
}
QString YubiKeyUtil::getNextHex(size_t resultLen,
const QString &str, int scheme) {
QString result("");
qDebug() << "str = " << str
<< " len = " << str.length();
switch(scheme) {
case GEN_SCHEME_FIXED:
result = str;
break;
case GEN_SCHEME_INCR:
{
//Hex clean
QString hexStr(str);
qstrClean(&hexStr, resultLen);
//Hex decode
unsigned char hexDecoded[MAX_SIZE];
size_t hexDecodedLen = 0;
memset(&hexDecoded, 0, sizeof(hexDecoded));
qstrHexDecode(hexDecoded, &hexDecodedLen, hexStr);
if(hexDecodedLen <= 0) {
break;
}
qDebug() << "hexDecoded = " << QString((char*)hexDecoded)
<< " len = " << hexDecodedLen;
//Increment
for (int i = hexDecodedLen; i--; ) {
if (++hexDecoded[i]) {
break;
}
}
//Hex encode
result = qstrHexEncode(hexDecoded, hexDecodedLen);
qDebug() << "hexEncoded = " << result
<< " len = " << result.size();
}
break;
case GEN_SCHEME_RAND:
result = generateRandomHex(resultLen);
break;
}
return result;
}
QString YubiKeyUtil::getNextModhex(size_t resultLen,
const QString &str, int scheme) {
QString result("");
qDebug() << "str = " << str
<< " len = " << str.length();
switch(scheme) {
case GEN_SCHEME_FIXED:
result = str;
break;
case GEN_SCHEME_INCR:
{
//Modhex clean
QString modhexStr(str);
qstrModhexClean(&modhexStr, resultLen);
//Modhex decode
unsigned char modhexDecoded[MAX_SIZE];
size_t modhexDecodedLen = 0;
memset(&modhexDecoded, 0, sizeof(modhexDecoded));
qstrModhexDecode(modhexDecoded, &modhexDecodedLen, modhexStr);
if(modhexDecodedLen <= 0) {
break;
}
qDebug() << "modhexDecoded = " << QString((char*)modhexDecoded)
<< " len = " << modhexDecodedLen;
//Increment
for (int i = modhexDecodedLen; i--; ) {
if (++modhexDecoded[i]) {
break;
}
}
//Modhex encode
result = qstrModhexEncode(modhexDecoded, modhexDecodedLen);
qDebug() << "modhexEncoded = " << result
<< " len = " << result.size();
}
break;
case GEN_SCHEME_RAND:
result = generateRandomModhex(resultLen);
break;
}
return result;
}
void YubiKeyUtil::hexdump(void *buffer, int size) {
unsigned char *p = (unsigned char *)buffer;
int i;
for (i = 0; i < size; i++) {
fprintf(stderr, "\\x%02x", *p);
p++;
}
fprintf(stderr, "\n");
fflush(stderr);
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: toxhlp.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: vg $ $Date: 2003-04-17 14:32:43 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#ifndef _COM_SUN_STAR_I18N_XINDEXENTRYSUPPLIER_HPP_
#include <drafts/com/sun/star/i18n/XExtendedIndexEntrySupplier.hpp>
#endif
#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif
#ifndef _DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _TOXWRAP_HXX
#include <toxwrap.hxx>
#endif
IndexEntrySupplierWrapper::IndexEntrySupplierWrapper()
{
::com::sun::star::uno::Reference<
::com::sun::star::lang::XMultiServiceFactory > rxMSF =
::comphelper::getProcessServiceFactory();
try {
STAR_REFERENCE( uno::XInterface ) xI =
rxMSF->createInstance( ::rtl::OUString::createFromAscii(
"com.sun.star.i18n.IndexEntrySupplier" ) );
if( xI.is() )
{
UNO_NMSPC::Any x = xI->queryInterface( ::getCppuType(
(const com::sun::star::uno::Reference< drafts::com::sun::star::i18n::XExtendedIndexEntrySupplier>*)0) );
x >>= xIES;
}
}
catch ( UNO_NMSPC::Exception& e )
{
#ifndef PRODUCT
ByteString aMsg( "IndexEntrySupplierWrapper: Exception caught\n" );
aMsg += ByteString( String( e.Message ), RTL_TEXTENCODING_UTF8 );
DBG_ERRORFILE( aMsg.GetBuffer() );
#endif
}
}
IndexEntrySupplierWrapper::~IndexEntrySupplierWrapper()
{
}
String IndexEntrySupplierWrapper::GetIndexKey( const String& rTxt,
const String& rTxtReading,
const STAR_NMSPC::lang::Locale& rLocale ) const
{
String sRet;
try {
sRet = xIES->getIndexKey( rTxt, rTxtReading, rLocale );
}
catch ( UNO_NMSPC::Exception& e )
{
#ifndef PRODUCT
ByteString aMsg( "getIndexKey: Exception caught\n" );
aMsg += ByteString( String( e.Message ), RTL_TEXTENCODING_UTF8 );
DBG_ERRORFILE( aMsg.GetBuffer() );
#endif
}
return sRet;
}
String IndexEntrySupplierWrapper::GetFollowingText( BOOL bMorePages ) const
{
String sRet;
try {
sRet = xIES->getIndexFollowPageWord( bMorePages, aLcl );
}
catch ( UNO_NMSPC::Exception& e )
{
#ifndef PRODUCT
ByteString aMsg( "getIndexFollowPageWord: Exception caught\n" );
aMsg += ByteString( String( e.Message ), RTL_TEXTENCODING_UTF8 );
DBG_ERRORFILE( aMsg.GetBuffer() );
#endif
}
return sRet;
}
STAR_NMSPC::uno::Sequence< ::rtl::OUString >
IndexEntrySupplierWrapper::GetAlgorithmList( const STAR_NMSPC::lang::Locale& rLcl ) const
{
::com::sun::star::uno::Sequence< ::rtl::OUString > sRet;
try {
sRet = xIES->getAlgorithmList( rLcl );
}
catch ( UNO_NMSPC::Exception& e )
{
#ifndef PRODUCT
ByteString aMsg( "getAlgorithmList: Exception caught\n" );
aMsg += ByteString( String( e.Message ), RTL_TEXTENCODING_UTF8 );
DBG_ERRORFILE( aMsg.GetBuffer() );
#endif
}
return sRet;
}
STAR_NMSPC::uno::Sequence < com::sun::star::lang::Locale >
IndexEntrySupplierWrapper::GetLocaleList() const
{
::com::sun::star::uno::Sequence< com::sun::star::lang::Locale > sRet;
try {
sRet = xIES->getLocaleList();
}
catch ( UNO_NMSPC::Exception& e )
{
#ifndef PRODUCT
ByteString aMsg( "getLocaleList: Exception caught\n" );
aMsg += ByteString( String( e.Message ), RTL_TEXTENCODING_UTF8 );
DBG_ERRORFILE( aMsg.GetBuffer() );
#endif
}
return sRet;
}
sal_Bool IndexEntrySupplierWrapper::LoadAlgorithm(
const STAR_NMSPC::lang::Locale& rLcl,
const String& sSortAlgorithm, long nOptions ) const
{
sal_Bool bRet = sal_False;
try {
bRet = xIES->loadAlgorithm( rLcl, sSortAlgorithm, nOptions );
}
catch ( UNO_NMSPC::Exception& e )
{
#ifndef PRODUCT
ByteString aMsg( "loadAlgorithm: Exception caught\n" );
aMsg += ByteString( String( e.Message ), RTL_TEXTENCODING_UTF8 );
DBG_ERRORFILE( aMsg.GetBuffer() );
#endif
}
return bRet;
}
sal_Int16 IndexEntrySupplierWrapper::CompareIndexEntry(
const String& rTxt1, const String& rTxtReading1,
const STAR_NMSPC::lang::Locale& rLocale1,
const String& rTxt2, const String& rTxtReading2,
const STAR_NMSPC::lang::Locale& rLocale2 ) const
{
sal_Int16 nRet = 0;
try {
nRet = xIES->compareIndexEntry( rTxt1, rTxtReading1, rLocale1,
rTxt2, rTxtReading2, rLocale2 );
}
catch ( UNO_NMSPC::Exception& e )
{
#ifndef PRODUCT
ByteString aMsg( "compareIndexEntry: Exception caught\n" );
aMsg += ByteString( String( e.Message ), RTL_TEXTENCODING_UTF8 );
DBG_ERRORFILE( aMsg.GetBuffer() );
#endif
}
return nRet;
}
<commit_msg>INTEGRATION: CWS i18napi (1.4.164); FILE MERGED 2003/04/19 20:27:01 er 1.4.164.1: #107686# move drafts.com.sun.star.i18n to com.sun.star.i18n<commit_after>/*************************************************************************
*
* $RCSfile: toxhlp.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: vg $ $Date: 2003-04-24 10:54: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): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#ifndef _COM_SUN_STAR_I18N_XINDEXENTRYSUPPLIER_HPP_
#include <com/sun/star/i18n/XExtendedIndexEntrySupplier.hpp>
#endif
#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif
#ifndef _DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _TOXWRAP_HXX
#include <toxwrap.hxx>
#endif
IndexEntrySupplierWrapper::IndexEntrySupplierWrapper()
{
::com::sun::star::uno::Reference<
::com::sun::star::lang::XMultiServiceFactory > rxMSF =
::comphelper::getProcessServiceFactory();
try {
STAR_REFERENCE( uno::XInterface ) xI =
rxMSF->createInstance( ::rtl::OUString::createFromAscii(
"com.sun.star.i18n.IndexEntrySupplier" ) );
if( xI.is() )
{
UNO_NMSPC::Any x = xI->queryInterface( ::getCppuType(
(const com::sun::star::uno::Reference< com::sun::star::i18n::XExtendedIndexEntrySupplier>*)0) );
x >>= xIES;
}
}
catch ( UNO_NMSPC::Exception& e )
{
#ifndef PRODUCT
ByteString aMsg( "IndexEntrySupplierWrapper: Exception caught\n" );
aMsg += ByteString( String( e.Message ), RTL_TEXTENCODING_UTF8 );
DBG_ERRORFILE( aMsg.GetBuffer() );
#endif
}
}
IndexEntrySupplierWrapper::~IndexEntrySupplierWrapper()
{
}
String IndexEntrySupplierWrapper::GetIndexKey( const String& rTxt,
const String& rTxtReading,
const STAR_NMSPC::lang::Locale& rLocale ) const
{
String sRet;
try {
sRet = xIES->getIndexKey( rTxt, rTxtReading, rLocale );
}
catch ( UNO_NMSPC::Exception& e )
{
#ifndef PRODUCT
ByteString aMsg( "getIndexKey: Exception caught\n" );
aMsg += ByteString( String( e.Message ), RTL_TEXTENCODING_UTF8 );
DBG_ERRORFILE( aMsg.GetBuffer() );
#endif
}
return sRet;
}
String IndexEntrySupplierWrapper::GetFollowingText( BOOL bMorePages ) const
{
String sRet;
try {
sRet = xIES->getIndexFollowPageWord( bMorePages, aLcl );
}
catch ( UNO_NMSPC::Exception& e )
{
#ifndef PRODUCT
ByteString aMsg( "getIndexFollowPageWord: Exception caught\n" );
aMsg += ByteString( String( e.Message ), RTL_TEXTENCODING_UTF8 );
DBG_ERRORFILE( aMsg.GetBuffer() );
#endif
}
return sRet;
}
STAR_NMSPC::uno::Sequence< ::rtl::OUString >
IndexEntrySupplierWrapper::GetAlgorithmList( const STAR_NMSPC::lang::Locale& rLcl ) const
{
::com::sun::star::uno::Sequence< ::rtl::OUString > sRet;
try {
sRet = xIES->getAlgorithmList( rLcl );
}
catch ( UNO_NMSPC::Exception& e )
{
#ifndef PRODUCT
ByteString aMsg( "getAlgorithmList: Exception caught\n" );
aMsg += ByteString( String( e.Message ), RTL_TEXTENCODING_UTF8 );
DBG_ERRORFILE( aMsg.GetBuffer() );
#endif
}
return sRet;
}
STAR_NMSPC::uno::Sequence < com::sun::star::lang::Locale >
IndexEntrySupplierWrapper::GetLocaleList() const
{
::com::sun::star::uno::Sequence< com::sun::star::lang::Locale > sRet;
try {
sRet = xIES->getLocaleList();
}
catch ( UNO_NMSPC::Exception& e )
{
#ifndef PRODUCT
ByteString aMsg( "getLocaleList: Exception caught\n" );
aMsg += ByteString( String( e.Message ), RTL_TEXTENCODING_UTF8 );
DBG_ERRORFILE( aMsg.GetBuffer() );
#endif
}
return sRet;
}
sal_Bool IndexEntrySupplierWrapper::LoadAlgorithm(
const STAR_NMSPC::lang::Locale& rLcl,
const String& sSortAlgorithm, long nOptions ) const
{
sal_Bool bRet = sal_False;
try {
bRet = xIES->loadAlgorithm( rLcl, sSortAlgorithm, nOptions );
}
catch ( UNO_NMSPC::Exception& e )
{
#ifndef PRODUCT
ByteString aMsg( "loadAlgorithm: Exception caught\n" );
aMsg += ByteString( String( e.Message ), RTL_TEXTENCODING_UTF8 );
DBG_ERRORFILE( aMsg.GetBuffer() );
#endif
}
return bRet;
}
sal_Int16 IndexEntrySupplierWrapper::CompareIndexEntry(
const String& rTxt1, const String& rTxtReading1,
const STAR_NMSPC::lang::Locale& rLocale1,
const String& rTxt2, const String& rTxtReading2,
const STAR_NMSPC::lang::Locale& rLocale2 ) const
{
sal_Int16 nRet = 0;
try {
nRet = xIES->compareIndexEntry( rTxt1, rTxtReading1, rLocale1,
rTxt2, rTxtReading2, rLocale2 );
}
catch ( UNO_NMSPC::Exception& e )
{
#ifndef PRODUCT
ByteString aMsg( "compareIndexEntry: Exception caught\n" );
aMsg += ByteString( String( e.Message ), RTL_TEXTENCODING_UTF8 );
DBG_ERRORFILE( aMsg.GetBuffer() );
#endif
}
return nRet;
}
<|endoftext|>
|
<commit_before>#ifndef HYDRAULICACKUMULATOR_HPP_INCLUDED
#define HYDRAULICACKUMULATOR_HPP_INCLUDED
#include <iostream>
#include "ComponentEssentials.h"
#include "ComponentUtilities.h"
#include <math.h>
//!
//! @file HydraulicAckumulator.hpp
//! @author Petter Krus <petter.krus@liu.se>
//! @date Mon 12 Sep 2011 22:31:30
//! @brief Hydraulic lossless ackumulator
//! @ingroup HydraulicComponents
//!
//This component is generated by COMPGEN for HOPSAN-NG simulation
//from
/*{, C:, Documents and Settings, petkr14, My Documents, \
CompgenNG}/HydraulicComponentsNG.nb*/
using namespace hopsan;
class HydraulicAckumulator : public ComponentQ
{
private:
double mp0;
double mV0;
double mKca;
double mkappa;
Port *mpP1;
Port *mpPVa;
Port *mpPpa;
double delayParts1[9];
double delayParts2[9];
double delayParts3[9];
double delayParts4[9];
Matrix jacobianMatrix;
Vec systemEquations;
Matrix delayedPart;
int i;
int iter;
int mNoiter;
int jsyseqnweight[4];
int order[4];
int mNstep;
//Port P1 variable
double p1;
double q1;
double c1;
double Zc1;
//inputVariables
//outputVariables
double Va;
double pa;
//Port P1 pointer
double *mpND_p1;
double *mpND_q1;
double *mpND_c1;
double *mpND_Zc1;
//Delay declarations
//inputVariables pointers
//outputVariables pointers
double *mpND_Va;
double *mpND_pa;
Delay mDelayedPart10;
Delay mDelayedPart20;
Delay mDelayedPart21;
Delay mDelayedPart30;
EquationSystemSolver *pSolver;
public:
static Component *Creator()
{
return new HydraulicAckumulator();
}
HydraulicAckumulator(const double p0 = 1.e7
,const double V0 = 0.001
,const double Kca = 1.e-8
,const double kappa = 1.2
)
: ComponentQ()
{
mNstep=9;
jacobianMatrix.create(4,4);
systemEquations.create(4);
delayedPart.create(5,6);
mNoiter=2;
jsyseqnweight[0]=1;
jsyseqnweight[1]=0.67;
jsyseqnweight[2]=0.5;
jsyseqnweight[3]=0.5;
mp0 = p0;
mV0 = V0;
mKca = Kca;
mkappa = kappa;
//Add ports to the component
mpP1=addPowerPort("P1","NodeHydraulic");
//Add inputVariables ports to the component
//Add outputVariables ports to the component
mpPVa=addWritePort("PVa","NodeSignal", Port::NOTREQUIRED);
mpPpa=addWritePort("Ppa","NodeSignal", Port::NOTREQUIRED);
//Register changable parameters to the HOPSAN++ core
registerParameter("p0", "Preload pressure", "N/m^2", mp0);
registerParameter("V0", "Ack. Volume", "m^3", mV0);
registerParameter("Kca", "Flow coefficent", "m^3/Pa", mKca);
registerParameter("kappa", "polytropic exp. of gas", "", mkappa);
pSolver = new EquationSystemSolver(this, 4);
}
void initialize()
{
//Read port variable pointers from nodes
//Port P1
mpND_p1=getSafeNodeDataPtr(mpP1, NodeHydraulic::PRESSURE);
mpND_q1=getSafeNodeDataPtr(mpP1, NodeHydraulic::FLOW);
mpND_c1=getSafeNodeDataPtr(mpP1, NodeHydraulic::WAVEVARIABLE);
mpND_Zc1=getSafeNodeDataPtr(mpP1, NodeHydraulic::CHARIMP);
//Read inputVariables pointers from nodes
//Read outputVariable pointers from nodes
mpND_Va=getSafeNodeDataPtr(mpPVa, NodeSignal::VALUE);
mpND_pa=getSafeNodeDataPtr(mpPpa, NodeSignal::VALUE);
//Read variables from nodes
//Port P1
p1 = (*mpND_p1);
q1 = (*mpND_q1);
c1 = (*mpND_c1);
Zc1 = (*mpND_Zc1);
//Read inputVariables from nodes
//Read outputVariables from nodes
Va = mpPVa->getStartValue(NodeSignal::VALUE);
pa = mpPpa->getStartValue(NodeSignal::VALUE);
//Initialize delays
delayParts2[1] = (-2*Va - mKca*mTimestep*p1*limit(onPositive(p1 - pa) \
+ onPositive(Va),0.,1.) + mKca*mTimestep*pa*limit(onPositive(p1 - pa) + \
onPositive(Va),0.,1.))/2.;
mDelayedPart21.initialize(mNstep,delayParts2[1]);
delayedPart[1][1] = delayParts1[1];
delayedPart[2][1] = delayParts2[1];
delayedPart[3][1] = delayParts3[1];
delayedPart[4][1] = delayParts4[1];
}
void simulateOneTimestep()
{
Vec stateVar(4);
Vec stateVark(4);
Vec deltaStateVar(4);
//Read variables from nodes
//Port P1
c1 = (*mpND_c1);
Zc1 = (*mpND_Zc1);
//Read inputVariables from nodes
//LocalExpressions
//Initializing variable vector for Newton-Raphson
stateVark[0] = q1;
stateVark[1] = Va;
stateVark[2] = pa;
stateVark[3] = p1;
//Iterative solution using Newton-Rapshson
for(iter=1;iter<=mNoiter;iter++)
{
//Ackumulator
//Differential-algebraic system of equation parts
//Assemble differential-algebraic equations
systemEquations[0] =q1 + mKca*(p1 - pa)*limit(onPositive(p1 - pa) + onPositive(Va),0.,1.);
systemEquations[1] =Va - limit(-(mKca*mTimestep*(-p1 + pa)*limit(onPositive(p1 - pa) + onPositive(Va),0.,1.))/2. - delayedPart[2][1],0.,mV0);
systemEquations[2] =pa - (mp0*Power(mV0,mkappa))/Power(mV0 - Va,mkappa);
systemEquations[3] =p1 - (c1 + q1*Zc1)*onPositive(p1);
//Jacobian matrix
jacobianMatrix[0][0] = 1;
jacobianMatrix[0][1] = 0;
jacobianMatrix[0][2] = -(mKca*limit(onPositive(p1 - pa) + onPositive(Va),0.,1.));
jacobianMatrix[0][3] = mKca*limit(onPositive(p1 - pa) + onPositive(Va),0.,1.);
jacobianMatrix[1][0] = 0;
jacobianMatrix[1][1] = 1;
jacobianMatrix[1][2] = (mKca*mTimestep*dxLimit(-(mKca*mTimestep*(-p1 + pa)*limit(onPositive(p1 - pa) + onPositive(Va),0.,1.))/2. - delayedPart[2][1],0.,mV0)*limit(onPositive(p1 - pa) + onPositive(Va),0.,1.))/2.;
jacobianMatrix[1][3] = -(mKca*mTimestep*dxLimit(-(mKca*mTimestep*(-p1 + pa)*limit(onPositive(p1 - pa) + onPositive(Va),0.,1.))/2. - delayedPart[2][1],0.,mV0)*limit(onPositive(p1 - pa) + onPositive(Va),0.,1.))/2.;
jacobianMatrix[2][0] = 0;
jacobianMatrix[2][1] = -(mkappa*mp0*Power(mV0,mkappa)*Power(mV0 - Va,-1 - mkappa));
jacobianMatrix[2][2] = 1;
jacobianMatrix[2][3] = 0;
jacobianMatrix[3][0] = -(Zc1*onPositive(p1));
jacobianMatrix[3][1] = 0;
jacobianMatrix[3][2] = 0;
jacobianMatrix[3][3] = 1;
//Solving equation using LU-faktorisation
pSolver->solve(jacobianMatrix, systemEquations, stateVark, iter);
q1=stateVark[0];
Va=stateVark[1];
pa=stateVark[2];
p1=stateVark[3];
}
//Calculate the delayed parts
delayParts2[1] = (-2*Va - mKca*mTimestep*p1*limit(onPositive(p1 - pa) \
+ onPositive(Va),0.,1.) + mKca*mTimestep*pa*limit(onPositive(p1 - pa) + \
onPositive(Va),0.,1.))/2.;
delayedPart[1][1] = delayParts1[1];
delayedPart[2][1] = delayParts2[1];
delayedPart[3][1] = delayParts3[1];
delayedPart[4][1] = delayParts4[1];
//Write new values to nodes
//Port P1
(*mpND_p1)=p1;
(*mpND_q1)=q1;
//outputVariables
(*mpND_Va)=Va;
(*mpND_pa)=pa;
//Update the delayed variabels
mDelayedPart21.update(delayParts2[1]);
}
};
#endif // HYDRAULICACKUMULATOR_HPP_INCLUDED
<commit_msg>Hydraulic/HydraulicAckumulator.hpp is corrected. Behaviour when being empty was not correct before.<commit_after>#ifndef HYDRAULICACKUMULATOR_HPP_INCLUDED
#define HYDRAULICACKUMULATOR_HPP_INCLUDED
#include <iostream>
#include "ComponentEssentials.h"
#include "ComponentUtilities.h"
#include "math.h"
//!
//! @file HydraulicAckumulator.hpp
//! @author Petter Krus <petter.krus@liu.se>
//! @date Fri 13 Apr 2012 08:57:00
//! @brief Hydraulic lossless ackumulator
//! @ingroup HydraulicComponents
//!
//This component is generated by COMPGEN for HOPSAN-NG simulation
//from
/*{, C:, Documents and Settings, petkr14, My Documents, \
CompgenNG}/HydraulicComponentsNG.nb*/
using namespace hopsan;
class HydraulicAckumulator : public ComponentQ
{
private:
double mp0;
double mV0;
double mKca;
double mkappa;
Port *mpP1;
Port *mpPVa;
Port *mpPpa;
double delayParts1[9];
double delayParts2[9];
double delayParts3[9];
double delayParts4[9];
Matrix jacobianMatrix;
Vec systemEquations;
Matrix delayedPart;
int i;
int iter;
int mNoiter;
double jsyseqnweight[4];
int order[4];
int mNstep;
//Port P1 variable
double p1;
double q1;
double c1;
double Zc1;
//inputVariables
//outputVariables
double Va;
double pa;
//Port P1 pointer
double *mpND_p1;
double *mpND_q1;
double *mpND_c1;
double *mpND_Zc1;
//Delay declarations
//inputVariables pointers
//outputVariables pointers
double *mpND_Va;
double *mpND_pa;
Delay mDelayedPart10;
Delay mDelayedPart11;
Delay mDelayedPart20;
Delay mDelayedPart30;
EquationSystemSolver *mpSolver;
public:
static Component *Creator()
{
return new HydraulicAckumulator();
}
HydraulicAckumulator() : ComponentQ()
{
const double p0 = 1.e7;
const double V0 = 0.001;
const double Kca = 1.e-8;
const double kappa = 1.2;
mNstep=9;
jacobianMatrix.create(4,4);
systemEquations.create(4);
delayedPart.create(5,6);
mNoiter=2;
jsyseqnweight[0]=1;
jsyseqnweight[1]=0.67;
jsyseqnweight[2]=0.5;
jsyseqnweight[3]=0.5;
mp0 = p0;
mV0 = V0;
mKca = Kca;
mkappa = kappa;
//Add ports to the component
mpP1=addPowerPort("P1","NodeHydraulic");
//Add inputVariables ports to the component
//Add outputVariables ports to the component
mpPVa=addWritePort("PVa","NodeSignal", Port::NOTREQUIRED);
mpPpa=addWritePort("Ppa","NodeSignal", Port::NOTREQUIRED);
//Register changable parameters to the HOPSAN++ core
registerParameter("p0", "Preload pressure", "N/m^2", mp0);
registerParameter("V0", "Ack. Volume", "m^3", mV0);
registerParameter("Kca", "Flow coefficent", "m^3/Pa", mKca);
registerParameter("kappa", "polytropic exp. of gas", "", mkappa);
mpSolver = new EquationSystemSolver(this,4);
}
void initialize()
{
//Read port variable pointers from nodes
//Port P1
mpND_p1=getSafeNodeDataPtr(mpP1, NodeHydraulic::PRESSURE);
mpND_q1=getSafeNodeDataPtr(mpP1, NodeHydraulic::FLOW);
mpND_c1=getSafeNodeDataPtr(mpP1, NodeHydraulic::WAVEVARIABLE);
mpND_Zc1=getSafeNodeDataPtr(mpP1, NodeHydraulic::CHARIMP);
//Read inputVariables pointers from nodes
//Read outputVariable pointers from nodes
mpND_Va=getSafeNodeDataPtr(mpPVa, NodeSignal::VALUE);
mpND_pa=getSafeNodeDataPtr(mpPpa, NodeSignal::VALUE);
//Read variables from nodes
//Port P1
p1 = (*mpND_p1);
q1 = (*mpND_q1);
c1 = (*mpND_c1);
Zc1 = (*mpND_Zc1);
//Read inputVariables from nodes
//Read outputVariables from nodes
Va = mpPVa->getStartValue(NodeSignal::VALUE);
pa = mpPpa->getStartValue(NodeSignal::VALUE);
//Initialize delays
delayParts1[1] = (-(mKca*mTimestep*p1) + mKca*mTimestep*pa - \
2*Va)/2.;
mDelayedPart11.initialize(mNstep,delayParts1[1]);
delayedPart[1][1] = delayParts1[1];
delayedPart[2][1] = delayParts2[1];
delayedPart[3][1] = delayParts3[1];
delayedPart[4][1] = delayParts4[1];
}
void simulateOneTimestep()
{
Vec stateVar(4);
Vec stateVark(4);
Vec deltaStateVar(4);
//Read variables from nodes
//Port P1
c1 = (*mpND_c1);
Zc1 = (*mpND_Zc1);
//Read inputVariables from nodes
//LocalExpressions
//Initializing variable vector for Newton-Raphson
stateVark[0] = Va;
stateVark[1] = q1;
stateVark[2] = pa;
stateVark[3] = p1;
//Iterative solution using Newton-Rapshson
for(iter=1;iter<=mNoiter;iter++)
{
//Ackumulator
//Differential-algebraic system of equation parts
//Assemble differential-algebraic equations
systemEquations[0] =Va - limit((mKca*mTimestep*(p1 - pa))/2. - \
delayedPart[1][1],0.,1);
systemEquations[1] =q1 + mKca*(p1 - pa)*dxLimit((mKca*mTimestep*(p1 - pa))/2. - \
delayedPart[1][1],0.,1);
systemEquations[2] =pa - (mp0*Power(mV0,mkappa))/Power(mV0 - \
Va,mkappa);
systemEquations[3] =p1 - (c1 + q1*Zc1)*onPositive(p1);
//Jacobian matrix
jacobianMatrix[0][0] = 1;
jacobianMatrix[0][1] = 0;
jacobianMatrix[0][2] = (mKca*mTimestep*dxLimit((mKca*mTimestep*(p1 \
- pa))/2. - delayedPart[1][1],0.,1))/2.;
jacobianMatrix[0][3] = -(mKca*mTimestep*dxLimit((mKca*mTimestep*(p1 \
- pa))/2. - delayedPart[1][1],0.,1))/2.;
jacobianMatrix[1][0] = 0;
jacobianMatrix[1][1] = 1;
jacobianMatrix[1][2] = -(mKca*dxLimit((mKca*mTimestep*(p1 - pa))/2. - \
delayedPart[1][1],0.,1));
jacobianMatrix[1][3] = mKca*dxLimit((mKca*mTimestep*(p1 - pa))/2. - \
delayedPart[1][1],0.,1);
jacobianMatrix[2][0] = -(mkappa*mp0*Power(mV0,mkappa)*Power(mV0 - \
Va,-1 - mkappa));
jacobianMatrix[2][1] = 0;
jacobianMatrix[2][2] = 1;
jacobianMatrix[2][3] = 0;
jacobianMatrix[3][0] = 0;
jacobianMatrix[3][1] = -(Zc1*onPositive(p1));
jacobianMatrix[3][2] = 0;
jacobianMatrix[3][3] = 1;
//Solving equation using LU-faktorisation
mpSolver->solve(jacobianMatrix, systemEquations, stateVark, iter);
Va=stateVark[0];
q1=stateVark[1];
pa=stateVark[2];
p1=stateVark[3];
}
//Calculate the delayed parts
delayParts1[1] = (-(mKca*mTimestep*p1) + mKca*mTimestep*pa - \
2*Va)/2.;
delayedPart[1][1] = delayParts1[1];
delayedPart[2][1] = delayParts2[1];
delayedPart[3][1] = delayParts3[1];
delayedPart[4][1] = delayParts4[1];
//Write new values to nodes
//Port P1
(*mpND_p1)=p1*onPositive(p1);
(*mpND_q1)=q1;
//outputVariables
(*mpND_Va)=Va;
(*mpND_pa)=pa;
//Update the delayed variabels
mDelayedPart11.update(delayParts1[1]);
}
};
#endif // HYDRAULICACKUMULATOR_HPP_INCLUDED
<|endoftext|>
|
<commit_before>#include "Sniffer.hpp"
using namespace tin::network::sniffer;
void pcap_trampoline(u_char *param, const struct pcap_pkthdr *pkt_header, const u_char *pkt_data)
{
Sniffer* obj = reinterpret_cast<Sniffer*>(param);
obj->handlePacket(pkt_header, pkt_data);
}
Sniffer::Sniffer(const std::string& device, const std::string& expression):
device(device),
expression(expression)
{}
Sniffer::~Sniffer()
{
if (this->isSniffing())
{
this->stopSniffing();
}
else if (this->snifferThread.joinable())
{
this->snifferThread.join();
}
}
bool Sniffer::isSniffing() const
{
return this->pcapHandle != nullptr;
}
void Sniffer::stopSniffing()
{
if (!this->isSniffing())
{
return;
}
pcap_breakloop(this->pcapHandle);
this->snifferThread.join();
}
void Sniffer::changeConfig(const std::string& device, const std::string& expression)
{
if (this->isSniffing())
{
return;
}
this->device = device;
this->expression = expression;
}
void Sniffer::handlePacket(const struct pcap_pkthdr *header, const u_char *packet)
{
// declare pointers to packet headers
const struct ethernet_header *ethernet; // The ethernet header [1]
const struct ip_header *ip; // The IP header
const struct tcp_header *tcp; // The TCP header
const struct pcaprec_header *pcap; // The PCAP record header
int size_ip;
int size_tcp;
int size_payload;
this->packetCounter++;
// define ethernet header
ethernet = (struct ethernet_header*)(packet);
pcap = (struct pcaprec_header*)(packet);
long date = (long) pcap->ts_sec;
time_t timestamp = time(&date);
// define/compute ip header offset
ip = (struct ip_header*) (packet + SIZE_ETHERNET);
size_ip = IP_HL(ip)*4;
if (size_ip < 20)
{
// Throw an error (Invalid IP header length: $size_ip bytes)
return;
}
// if it is not TCP
if(ip->ip_pro != IPPROTO_TCP)
{
auto pac = std::make_shared<tin::utils::Packet>(
this->packetCounter,
timestamp,
ip->ip_src,
ip->ip_dst,
ip->ip_pro
);
this->runPacketReceivedHandlers(pac);
// pac->printData();
return;
}
// If it is TCP - we have some extra knowledge
// Tcp header offset
tcp = (struct tcp_header*)(packet + SIZE_ETHERNET + size_ip);
size_tcp = TH_OFF(tcp)*4;
if (size_tcp < 20)
{
// throw an error (Invalid TCP header length: $size_tcp bytes)
return;
}
// compute tcp payload (segment) size
size_payload = ntohs(ip->ip_len) + (size_ip + size_tcp);
// create new "Packet"
auto pac = std::make_shared<tin::utils::Packet>(
this->packetCounter,
timestamp,
ip->ip_src,
ip->ip_dst,
ip->ip_pro,
tcp->th_sport,
tcp->th_dport,
size_payload
);
this->runPacketReceivedHandlers(pac);
// pac->printData();
}
void Sniffer::run()
{
this->snifferThread = std::thread(
&Sniffer::sniff,
std::ref(*this)
);
}
unsigned int Sniffer::attachPacketReceivedHandler(std::function<void(const tin::utils::Packet::ptr&)>& handler)
{
return this->packetReceivedHandlers.insert(handler);
}
unsigned int Sniffer::attachPacketReceivedHandler(std::function<void(const tin::utils::Packet::ptr&)>&& handler)
{
return this->packetReceivedHandlers.insert(
std::forward<std::function<void(const tin::utils::Packet::ptr&)>>(handler)
);
}
void Sniffer::runPacketReceivedHandlers(const tin::utils::Packet::ptr& packetPtr)
{
for (auto iter: this->packetReceivedHandlers)
{
iter.second(packetPtr);
}
}
void Sniffer::sniff()
{
if (this->isSniffing())
{
return;
}
char errbuf[PCAP_ERRBUF_SIZE]; // error buffer
struct bpf_program fp; // compiled filter program (expression)
bpf_u_int32 mask; // subnet mask
bpf_u_int32 net; // ip
int num_packets = -1; // number of packets to capture (-1 means till error) */
// get device
auto dev = this->device.c_str();
if (dev == NULL)
{
// Throw an error (Couldn't find default device)
return;
}
// get network number and mask associated with capture device
if (pcap_lookupnet(dev, &net, &mask, errbuf) == -1)
{
// Throw an error (Couldn't get netmask for device: $device)
net = 0;
mask = 0;
}
// get an expression
auto filter = this->expression.c_str();
// open capture device
this->pcapHandle = pcap_open_live(dev, SNAP_LEN, 1, 1000, errbuf);
auto handle = this->pcapHandle;
if (handle == NULL)
{
// Throw an error (Couldn't open device: $device)
// errbuf contains error data
return;
}
// make sure we're capturing on an Ethernet device [2]
if (pcap_datalink(handle) != DLT_EN10MB)
{
// throw an error ($device is not an Ethernet)
return;
}
// compile the filter
if (pcap_compile(handle, &fp, filter, 0, net) == -1)
{
// throw an error (Could not parse filter: $expression)
// pcap_geterr(handle)
return;
}
// apply the filter
if (pcap_setfilter(handle, &fp) == -1)
{
// throw an error (Could not parse filter: $expression)
// pcap_geterr(handle)
return;
}
// capturing packets
pcap_loop(handle, num_packets, pcap_trampoline, reinterpret_cast<u_char*>(this));
// cleanup
pcap_freecode(&fp);
pcap_close(handle);
this->pcapHandle = nullptr;
}
<commit_msg>Make sure we are creating string copies<commit_after>#include "Sniffer.hpp"
using namespace tin::network::sniffer;
void pcap_trampoline(u_char *param, const struct pcap_pkthdr *pkt_header, const u_char *pkt_data)
{
Sniffer* obj = reinterpret_cast<Sniffer*>(param);
obj->handlePacket(pkt_header, pkt_data);
}
Sniffer::Sniffer(const std::string& device, const std::string& expression):
device(device.c_str()),
expression(expression.c_str())
{}
Sniffer::~Sniffer()
{
if (this->isSniffing())
{
this->stopSniffing();
}
else if (this->snifferThread.joinable())
{
this->snifferThread.join();
}
}
bool Sniffer::isSniffing() const
{
return this->pcapHandle != nullptr;
}
void Sniffer::stopSniffing()
{
if (!this->isSniffing())
{
return;
}
pcap_breakloop(this->pcapHandle);
this->snifferThread.join();
}
void Sniffer::changeConfig(const std::string& device, const std::string& expression)
{
if (this->isSniffing())
{
return;
}
this->device = std::string(device.c_str());
this->expression = std::string(expression.c_str());
}
void Sniffer::handlePacket(const struct pcap_pkthdr *header, const u_char *packet)
{
// declare pointers to packet headers
const struct ethernet_header *ethernet; // The ethernet header [1]
const struct ip_header *ip; // The IP header
const struct tcp_header *tcp; // The TCP header
const struct pcaprec_header *pcap; // The PCAP record header
int size_ip;
int size_tcp;
int size_payload;
this->packetCounter++;
// define ethernet header
ethernet = (struct ethernet_header*)(packet);
pcap = (struct pcaprec_header*)(packet);
long date = (long) pcap->ts_sec;
time_t timestamp = time(&date);
// define/compute ip header offset
ip = (struct ip_header*) (packet + SIZE_ETHERNET);
size_ip = IP_HL(ip)*4;
if (size_ip < 20)
{
// Throw an error (Invalid IP header length: $size_ip bytes)
return;
}
// if it is not TCP
if(ip->ip_pro != IPPROTO_TCP)
{
auto pac = std::make_shared<tin::utils::Packet>(
this->packetCounter,
timestamp,
ip->ip_src,
ip->ip_dst,
ip->ip_pro
);
this->runPacketReceivedHandlers(pac);
// pac->printData();
return;
}
// If it is TCP - we have some extra knowledge
// Tcp header offset
tcp = (struct tcp_header*)(packet + SIZE_ETHERNET + size_ip);
size_tcp = TH_OFF(tcp)*4;
if (size_tcp < 20)
{
// throw an error (Invalid TCP header length: $size_tcp bytes)
return;
}
// compute tcp payload (segment) size
size_payload = ntohs(ip->ip_len) + (size_ip + size_tcp);
// create new "Packet"
auto pac = std::make_shared<tin::utils::Packet>(
this->packetCounter,
timestamp,
ip->ip_src,
ip->ip_dst,
ip->ip_pro,
tcp->th_sport,
tcp->th_dport,
size_payload
);
this->runPacketReceivedHandlers(pac);
// pac->printData();
}
void Sniffer::run()
{
this->snifferThread = std::thread(
&Sniffer::sniff,
std::ref(*this)
);
}
unsigned int Sniffer::attachPacketReceivedHandler(std::function<void(const tin::utils::Packet::ptr&)>& handler)
{
return this->packetReceivedHandlers.insert(handler);
}
unsigned int Sniffer::attachPacketReceivedHandler(std::function<void(const tin::utils::Packet::ptr&)>&& handler)
{
return this->packetReceivedHandlers.insert(
std::forward<std::function<void(const tin::utils::Packet::ptr&)>>(handler)
);
}
void Sniffer::runPacketReceivedHandlers(const tin::utils::Packet::ptr& packetPtr)
{
for (auto iter: this->packetReceivedHandlers)
{
iter.second(packetPtr);
}
}
void Sniffer::sniff()
{
if (this->isSniffing())
{
return;
}
char errbuf[PCAP_ERRBUF_SIZE]; // error buffer
struct bpf_program fp; // compiled filter program (expression)
bpf_u_int32 mask; // subnet mask
bpf_u_int32 net; // ip
int num_packets = -1; // number of packets to capture (-1 means till error) */
// get device
auto dev = this->device.c_str();
if (dev == NULL)
{
// Throw an error (Couldn't find default device)
return;
}
// get network number and mask associated with capture device
if (pcap_lookupnet(dev, &net, &mask, errbuf) == -1)
{
// Throw an error (Couldn't get netmask for device: $device)
net = 0;
mask = 0;
}
// get an expression
auto filter = this->expression.c_str();
// open capture device
this->pcapHandle = pcap_open_live(dev, SNAP_LEN, 1, 1000, errbuf);
auto handle = this->pcapHandle;
if (handle == NULL)
{
// Throw an error (Couldn't open device: $device)
// errbuf contains error data
return;
}
// make sure we're capturing on an Ethernet device [2]
if (pcap_datalink(handle) != DLT_EN10MB)
{
// throw an error ($device is not an Ethernet)
return;
}
// compile the filter
if (pcap_compile(handle, &fp, filter, 0, net) == -1)
{
// throw an error (Could not parse filter: $expression)
// pcap_geterr(handle)
return;
}
// apply the filter
if (pcap_setfilter(handle, &fp) == -1)
{
// throw an error (Could not parse filter: $expression)
// pcap_geterr(handle)
return;
}
// capturing packets
pcap_loop(handle, num_packets, pcap_trampoline, reinterpret_cast<u_char*>(this));
// cleanup
pcap_freecode(&fp);
pcap_close(handle);
this->pcapHandle = nullptr;
}
<|endoftext|>
|
<commit_before>#include "CNNBallDetector.h"
#include "Tools/CameraGeometry.h"
#include "Tools/PatchWork.h"
#include "Tools/BlackSpotExtractor.h"
#include "Classifier/DortmundCNN/CNN_dortmund.h"
#include "Classifier/DortmundCNN/CNN_dortmund2018.h"
#include "Classifier/DortmundCNN/CNN_dortmund2018_keras.h"
using namespace std;
CNNBallDetector::CNNBallDetector()
{
DEBUG_REQUEST_REGISTER("Vision:CNNBallDetector:keyPoints", "draw key points extracted from integral image", false);
DEBUG_REQUEST_REGISTER("Vision:CNNBallDetector:drawCandidates", "draw ball candidates", false);
DEBUG_REQUEST_REGISTER("Vision:CNNBallDetector:drawCandidatesResizes", "draw ball candidates (resized)", false);
DEBUG_REQUEST_REGISTER("Vision:CNNBallDetector:refinePatches", "draw refined ball key points", false);
DEBUG_REQUEST_REGISTER("Vision:CNNBallDetector:drawPercepts", "draw ball percepts", false);
DEBUG_REQUEST_REGISTER("Vision:CNNBallDetector:drawPatchContrast", "draw patch contrast (only when contrast-check is in use!", false);
DEBUG_REQUEST_REGISTER("Vision:CNNBallDetector:extractPatches", "generate YUVC patches", false);
DEBUG_REQUEST_REGISTER("Vision:CNNBallDetector:keyPointsBlack", "draw black key points extracted from integral image", false);
DEBUG_REQUEST_REGISTER("Vision:CNNBallDetector:drawPatchInImage", "draw the gray-scale patch like it is passed to the CNN in the image", false);
theBallKeyPointExtractor = registerModule<BallKeyPointExtractor>("BallKeyPointExtractor", true);
getDebugParameterList().add(¶ms);
setClassifier("bottom.json", "bottom.json");
}
CNNBallDetector::~CNNBallDetector()
{
getDebugParameterList().remove(¶ms);
}
void CNNBallDetector::execute(CameraInfo::CameraID id)
{
cameraID = id;
getBallCandidates().reset();
best.clear();
// update parameter
theBallKeyPointExtractor->getModuleT()->setParameter(params.keyDetector);
theBallKeyPointExtractor->getModuleT()->setCameraId(cameraID);
//theBallKeyPointExtractor->getModuleT()->calculateKeyPoints(best);
theBallKeyPointExtractor->getModuleT()->calculateKeyPointsBetter(best);
// update selected classifier from parameters
// TODO: make it more efficient
setClassifier(params.classifier, params.classifierClose);
if(best.size() > 0) {
calculateCandidates();
}
DEBUG_REQUEST("Vision:CNNBallDetector:refinePatches",
for(BestPatchList::reverse_iterator i = best.rbegin(); i != best.rend(); ++i) {
//BestPatchList::Patch p = theBallKeyPointExtractor->getModuleT()->refineKeyPoint(*i);
RECT_PX(ColorClasses::red, (*i).min.x, (*i).min.y, (*i).max.x, (*i).max.y);
}
);
DEBUG_REQUEST("Vision:CNNBallDetector:drawPercepts",
for(MultiBallPercept::ConstABPIterator iter = getMultiBallPercept().begin(); iter != getMultiBallPercept().end(); iter++) {
if((*iter).cameraId == cameraID) {
CIRCLE_PX(ColorClasses::orange, (int)((*iter).centerInImage.x+0.5), (int)((*iter).centerInImage.y+0.5), (int)((*iter).radiusInImage+0.5));
}
}
);
DEBUG_REQUEST("Vision:CNNBallDetector:extractPatches",
extractPatches();
);
if(params.numberOfExportBestPatches > 0) {
extractPatches();
}
DEBUG_REQUEST("Vision:CNNBallDetector:keyPointsBlack",
BestPatchList bbest;
for(BestPatchList::reverse_iterator i = best.rbegin(); i != best.rend(); ++i) {
bbest.clear();
BlackSpotExtractor::calculateKeyPointsBlackBetter(getBallDetectorIntegralImage(), bbest, (*i).min.x, (*i).min.y, (*i).max.x, (*i).max.y);
int idx = 0;
for(BestPatchList::reverse_iterator j = bbest.rbegin(); j != bbest.rend(); ++j) {
RECT_PX(ColorClasses::red, (*j).min.x, (*j).min.y, (*j).max.x, (*j).max.y);
if(++idx > 3) {
break;
}
}
}
);
}
void CNNBallDetector::setClassifier(const std::string& name, const std::string& nameClose)
{
if(currentCNNName != name) {
currentCNN = std::make_shared<fdeep::model>(fdeep::load_model("Config/" + name));
currentCNNName = name;
}
if(currentCNNCloseName != nameClose) {
currentCNNClose = std::make_shared<fdeep::model>(fdeep::load_model("Config/" + nameClose));
currentCNNCloseName = nameClose;
}
}
void CNNBallDetector::calculateCandidates()
{
// the used patch size
const int patch_size = 16;
// NOTE: patches are sorted in the ascending order, so start from the end to get the best patches
int index = 0;
for(BestPatchList::reverse_iterator i = best.rbegin(); i != best.rend(); ++i)
{
if(getFieldPercept().getValidField().isInside((*i).min) && getFieldPercept().getValidField().isInside((*i).max))
{
// limit the max amount of evaluated keys
if(index > params.maxNumberOfKeys) {
break;
}
static BallCandidates::PatchYUVClassified patch((*i).min, (*i).max, patch_size);
patch.min = (*i).min;
patch.max = (*i).max;
if(!getImage().isInside(patch.min) || !getImage().isInside(patch.max)) {
continue;
}
//
// add an additional border as post-processing
int postBorder = (int)(patch.radius()*params.postBorderFactorFar);
double selectedCNNThreshold = params.cnn.threshold;
if(patch.width() >= params.postMaxCloseSize) // HACK: use patch size as estimate if close or far away
{
postBorder = (int)(patch.radius()*params.postBorderFactorClose);
selectedCNNThreshold = params.cnn.thresholdClose;
}
// resize the patch if possible
if(getImage().isInside(patch.min - postBorder) && getImage().isInside(patch.max + postBorder)) {
patch.min -= postBorder;
patch.max += postBorder;
}
// extract the pixels
PatchWork::subsampling(getImage(), getFieldColorPercept(), patch);
// (5) check contrast
if(params.checkContrast)
{
//double stddev = PatchWork::calculateContrastIterative2nd(getImage(),getFieldColorPercept(),min.x,min.y,max.x,max.y,patch_size);
double stddev = PatchWork::calculateContrastIterative2nd(patch);
DEBUG_REQUEST("Vision:CNNBallDetector:drawPatchContrast",
CANVAS(((cameraID == CameraInfo::Top)?"ImageTop":"ImageBottom"));
PEN("FF0000", 1); // red
Vector2i c = patch.center();
CIRCLE( c.x, c.y, stddev / 5.0);
);
// skip this patch, if contrast doesn't fullfill minimum
double selectedContrastMinimum = params.contrastMinimum;
if(patch.width() >= params.postMaxCloseSize) {
selectedContrastMinimum = params.contrastMinimumClose;
}
if(stddev <= selectedContrastMinimum) {
continue;
}
}
PatchWork::multiplyBrightness((cameraID == CameraInfo::Top) ?
params.brightnessMultiplierTop : params.brightnessMultiplierBottom, patch);
DEBUG_REQUEST("Vision:CNNBallDetector:drawPatchInImage",
unsigned int offsetX = patch.min.x;
unsigned int offsetY = patch.min.y;
unsigned int pixelWidth = (unsigned int) ((double) (patch.max.x - patch.min.x) / (double) patch.size() + 0.5);
for(unsigned int x = 0; x < patch.size(); x++) {
for(unsigned int y = 0; y < patch.size(); y++)
{
unsigned char pixelY = patch.data[x*patch_size + y].pixel.y;
// draw each image pixel this patch pixel occupies
for(unsigned int px=0; px < pixelWidth; px++) {
for(unsigned int py=0; py < pixelWidth; py++) {
getDebugImageDrawings().drawPointToImage(pixelY, 128, 128,
static_cast<int>(offsetX + (x*pixelWidth) + px), offsetY + (y*pixelWidth) + py);
}
}
}
}
);
// run CNN
stopwatch.start();
std::shared_ptr<fdeep::model> cnn = currentCNN;
if(patch.width() >= params.postMaxCloseSize) {
cnn = currentCNNClose;
}
// create input data from patch (TODO: why not use a Y-patch directly and save the copy operation?)
ASSERT(patch.size() == 16);
fdeep::tensor5 inputTensor = fdeep::tensor5(fdeep::shape5(1,1, 16, 16, 1), 0);
for(size_t x=0; x < patch.size(); x++) {
for(size_t y=0; y < patch.size(); y++) {
// TODO: check if x and y are correct
// The average brightness should have value 0.0
float value = (static_cast<float>((patch.data[patch.size() * x + y].pixel.y)) / 255.0f)
- static_cast<float>(params.cnn.meanBrightness);
inputTensor.set(0, 0, y, x, 0, value);
}
}
std::vector<fdeep::tensor5> result = cnn->predict({inputTensor});
bool found = false;
double radius = 0.0;
double x = 0.0;
double y = 0.0;
if(result.size() == 1) {
radius = result[0].get(0,0,0,0,0);
x = result[0].get(0,0,0,1,0);
y = result[0].get(0,0,0,2,0);
if(radius >= selectedCNNThreshold && x >= 0.0f && y >= 0.0f) {
found = true;
}
}
stopwatch.stop();
stopwatch_values.push_back(static_cast<double>(stopwatch.lastValue) * 0.001);
if (found /* && classifier->getBallConfidence() >= selectedCNNThreshold*/) {
// adjust the center and radius of the patch
Vector2i ballCenterInPatch(static_cast<int>(x * 16.0f), static_cast<int>(y*16.0f));
addBallPercept(Vector2i(patch.center() + ballCenterInPatch), patch.radius() * (radius/0.5f));
}
DEBUG_REQUEST("Vision:CNNBallDetector:drawCandidates",
// original patch
RECT_PX(ColorClasses::skyblue, (*i).min.x, (*i).min.y, (*i).max.x, (*i).max.y);
// possibly recised patch
RECT_PX(ColorClasses::orange, patch.min.x, patch.min.y, patch.max.x, patch.max.y);
);
index++;
} // end if in field
} // end for
} // end calculateCandidates
void CNNBallDetector::extractPatches()
{
int idx = 0;
for(BestPatchList::reverse_iterator i = best.rbegin(); i != best.rend(); ++i)
{
if(idx >= params.numberOfExportBestPatches) {
break;
}
int offset = ((*i).max.x - (*i).min.x)/4;
Vector2i min = (*i).min - offset;
Vector2i max = (*i).max + offset;
if(getFieldPercept().getValidField().isInside(min) && getFieldPercept().getValidField().isInside(max))
{
BallCandidates::PatchYUVClassified& q = getBallCandidates().nextFreePatchYUVClassified();
q.min = min;
q.max = max;
q.setSize(24);
PatchWork::subsampling(getImage(), getFieldColorPercept(), q);
idx++;
}
}
}
void CNNBallDetector::addBallPercept(const Vector2i& center, double radius)
{
const double ballRadius = 50.0;
MultiBallPercept::BallPercept ballPercept;
if(CameraGeometry::imagePixelToFieldCoord(
getCameraMatrix(),
getImage().cameraInfo,
center.x,
center.y,
ballRadius,
ballPercept.positionOnField))
{
ballPercept.cameraId = cameraID;
ballPercept.centerInImage = center;
ballPercept.radiusInImage = radius;
getMultiBallPercept().add(ballPercept);
getMultiBallPercept().frameInfoWhenBallWasSeen = getFrameInfo();
}
}
<commit_msg>Old values patch center values where always 0<commit_after>#include "CNNBallDetector.h"
#include "Tools/CameraGeometry.h"
#include "Tools/PatchWork.h"
#include "Tools/BlackSpotExtractor.h"
#include "Classifier/DortmundCNN/CNN_dortmund.h"
#include "Classifier/DortmundCNN/CNN_dortmund2018.h"
#include "Classifier/DortmundCNN/CNN_dortmund2018_keras.h"
using namespace std;
CNNBallDetector::CNNBallDetector()
{
DEBUG_REQUEST_REGISTER("Vision:CNNBallDetector:keyPoints", "draw key points extracted from integral image", false);
DEBUG_REQUEST_REGISTER("Vision:CNNBallDetector:drawCandidates", "draw ball candidates", false);
DEBUG_REQUEST_REGISTER("Vision:CNNBallDetector:drawCandidatesResizes", "draw ball candidates (resized)", false);
DEBUG_REQUEST_REGISTER("Vision:CNNBallDetector:refinePatches", "draw refined ball key points", false);
DEBUG_REQUEST_REGISTER("Vision:CNNBallDetector:drawPercepts", "draw ball percepts", false);
DEBUG_REQUEST_REGISTER("Vision:CNNBallDetector:drawPatchContrast", "draw patch contrast (only when contrast-check is in use!", false);
DEBUG_REQUEST_REGISTER("Vision:CNNBallDetector:extractPatches", "generate YUVC patches", false);
DEBUG_REQUEST_REGISTER("Vision:CNNBallDetector:keyPointsBlack", "draw black key points extracted from integral image", false);
DEBUG_REQUEST_REGISTER("Vision:CNNBallDetector:drawPatchInImage", "draw the gray-scale patch like it is passed to the CNN in the image", false);
theBallKeyPointExtractor = registerModule<BallKeyPointExtractor>("BallKeyPointExtractor", true);
getDebugParameterList().add(¶ms);
setClassifier("bottom.json", "bottom.json");
}
CNNBallDetector::~CNNBallDetector()
{
getDebugParameterList().remove(¶ms);
}
void CNNBallDetector::execute(CameraInfo::CameraID id)
{
cameraID = id;
getBallCandidates().reset();
best.clear();
// update parameter
theBallKeyPointExtractor->getModuleT()->setParameter(params.keyDetector);
theBallKeyPointExtractor->getModuleT()->setCameraId(cameraID);
//theBallKeyPointExtractor->getModuleT()->calculateKeyPoints(best);
theBallKeyPointExtractor->getModuleT()->calculateKeyPointsBetter(best);
// update selected classifier from parameters
// TODO: make it more efficient
setClassifier(params.classifier, params.classifierClose);
if(best.size() > 0) {
calculateCandidates();
}
DEBUG_REQUEST("Vision:CNNBallDetector:refinePatches",
for(BestPatchList::reverse_iterator i = best.rbegin(); i != best.rend(); ++i) {
//BestPatchList::Patch p = theBallKeyPointExtractor->getModuleT()->refineKeyPoint(*i);
RECT_PX(ColorClasses::red, (*i).min.x, (*i).min.y, (*i).max.x, (*i).max.y);
}
);
DEBUG_REQUEST("Vision:CNNBallDetector:drawPercepts",
for(MultiBallPercept::ConstABPIterator iter = getMultiBallPercept().begin(); iter != getMultiBallPercept().end(); iter++) {
if((*iter).cameraId == cameraID) {
CIRCLE_PX(ColorClasses::orange, (int)((*iter).centerInImage.x+0.5), (int)((*iter).centerInImage.y+0.5), (int)((*iter).radiusInImage+0.5));
}
}
);
DEBUG_REQUEST("Vision:CNNBallDetector:extractPatches",
extractPatches();
);
if(params.numberOfExportBestPatches > 0) {
extractPatches();
}
DEBUG_REQUEST("Vision:CNNBallDetector:keyPointsBlack",
BestPatchList bbest;
for(BestPatchList::reverse_iterator i = best.rbegin(); i != best.rend(); ++i) {
bbest.clear();
BlackSpotExtractor::calculateKeyPointsBlackBetter(getBallDetectorIntegralImage(), bbest, (*i).min.x, (*i).min.y, (*i).max.x, (*i).max.y);
int idx = 0;
for(BestPatchList::reverse_iterator j = bbest.rbegin(); j != bbest.rend(); ++j) {
RECT_PX(ColorClasses::red, (*j).min.x, (*j).min.y, (*j).max.x, (*j).max.y);
if(++idx > 3) {
break;
}
}
}
);
}
void CNNBallDetector::setClassifier(const std::string& name, const std::string& nameClose)
{
if(currentCNNName != name) {
currentCNN = std::make_shared<fdeep::model>(fdeep::load_model("Config/" + name));
currentCNNName = name;
}
if(currentCNNCloseName != nameClose) {
currentCNNClose = std::make_shared<fdeep::model>(fdeep::load_model("Config/" + nameClose));
currentCNNCloseName = nameClose;
}
}
void CNNBallDetector::calculateCandidates()
{
// the used patch size
const int patch_size = 16;
// NOTE: patches are sorted in the ascending order, so start from the end to get the best patches
int index = 0;
for(BestPatchList::reverse_iterator i = best.rbegin(); i != best.rend(); ++i)
{
if(getFieldPercept().getValidField().isInside((*i).min) && getFieldPercept().getValidField().isInside((*i).max))
{
// limit the max amount of evaluated keys
if(index > params.maxNumberOfKeys) {
break;
}
static BallCandidates::PatchYUVClassified patch((*i).min, (*i).max, patch_size);
patch.min = (*i).min;
patch.max = (*i).max;
if(!getImage().isInside(patch.min) || !getImage().isInside(patch.max)) {
continue;
}
//
// add an additional border as post-processing
int postBorder = (int)(patch.radius()*params.postBorderFactorFar);
double selectedCNNThreshold = params.cnn.threshold;
if(patch.width() >= params.postMaxCloseSize) // HACK: use patch size as estimate if close or far away
{
postBorder = (int)(patch.radius()*params.postBorderFactorClose);
selectedCNNThreshold = params.cnn.thresholdClose;
}
// resize the patch if possible
if(getImage().isInside(patch.min - postBorder) && getImage().isInside(patch.max + postBorder)) {
patch.min -= postBorder;
patch.max += postBorder;
}
// extract the pixels
PatchWork::subsampling(getImage(), getFieldColorPercept(), patch);
// (5) check contrast
if(params.checkContrast)
{
//double stddev = PatchWork::calculateContrastIterative2nd(getImage(),getFieldColorPercept(),min.x,min.y,max.x,max.y,patch_size);
double stddev = PatchWork::calculateContrastIterative2nd(patch);
DEBUG_REQUEST("Vision:CNNBallDetector:drawPatchContrast",
CANVAS(((cameraID == CameraInfo::Top)?"ImageTop":"ImageBottom"));
PEN("FF0000", 1); // red
Vector2i c = patch.center();
CIRCLE( c.x, c.y, stddev / 5.0);
);
// skip this patch, if contrast doesn't fullfill minimum
double selectedContrastMinimum = params.contrastMinimum;
if(patch.width() >= params.postMaxCloseSize) {
selectedContrastMinimum = params.contrastMinimumClose;
}
if(stddev <= selectedContrastMinimum) {
continue;
}
}
PatchWork::multiplyBrightness((cameraID == CameraInfo::Top) ?
params.brightnessMultiplierTop : params.brightnessMultiplierBottom, patch);
DEBUG_REQUEST("Vision:CNNBallDetector:drawPatchInImage",
unsigned int offsetX = patch.min.x;
unsigned int offsetY = patch.min.y;
unsigned int pixelWidth = (unsigned int) ((double) (patch.max.x - patch.min.x) / (double) patch.size() + 0.5);
for(unsigned int x = 0; x < patch.size(); x++) {
for(unsigned int y = 0; y < patch.size(); y++)
{
unsigned char pixelY = patch.data[x*patch_size + y].pixel.y;
// draw each image pixel this patch pixel occupies
for(unsigned int px=0; px < pixelWidth; px++) {
for(unsigned int py=0; py < pixelWidth; py++) {
getDebugImageDrawings().drawPointToImage(pixelY, 128, 128,
static_cast<int>(offsetX + (x*pixelWidth) + px), offsetY + (y*pixelWidth) + py);
}
}
}
}
);
// run CNN
stopwatch.start();
std::shared_ptr<fdeep::model> cnn = currentCNN;
if(patch.width() >= params.postMaxCloseSize) {
cnn = currentCNNClose;
}
// create input data from patch (TODO: why not use a Y-patch directly and save the copy operation?)
ASSERT(patch.size() == 16);
fdeep::tensor5 inputTensor = fdeep::tensor5(fdeep::shape5(1,1, 16, 16, 1), 0);
for(size_t x=0; x < patch.size(); x++) {
for(size_t y=0; y < patch.size(); y++) {
// TODO: check if x and y are correct
// The average brightness should have value 0.0
float value = (static_cast<float>((patch.data[patch.size() * x + y].pixel.y)) / 255.0f)
- static_cast<float>(params.cnn.meanBrightness);
inputTensor.set(0, 0, y, x, 0, value);
}
}
std::vector<fdeep::tensor5> result = cnn->predict({inputTensor});
bool found = false;
double radius = 0.0;
double x = 0.0;
double y = 0.0;
if(result.size() == 1) {
radius = result[0].get(0,0,0,0,0);
x = result[0].get(0,0,0,0,1);
y = result[0].get(0,0,0,0,2);
if(radius >= selectedCNNThreshold && x >= 0.0f && y >= 0.0f) {
found = true;
//std::cout << fdeep::show_tensor5s(result) << " (radius=" << radius << " x=" << x << " y=" << y << ")" << std::endl;
}
}
stopwatch.stop();
stopwatch_values.push_back(static_cast<double>(stopwatch.lastValue) * 0.001);
if (found /* && classifier->getBallConfidence() >= selectedCNNThreshold*/) {
// adjust the center and radius of the patch
Vector2i ballCenterInPatch(static_cast<int>(x * patch.width()), static_cast<int>(y*patch.width()));
addBallPercept(patch.min + ballCenterInPatch, radius*patch.width());
}
DEBUG_REQUEST("Vision:CNNBallDetector:drawCandidates",
// original patch
RECT_PX(ColorClasses::skyblue, (*i).min.x, (*i).min.y, (*i).max.x, (*i).max.y);
// possibly recised patch
RECT_PX(ColorClasses::orange, patch.min.x, patch.min.y, patch.max.x, patch.max.y);
);
index++;
} // end if in field
} // end for
} // end calculateCandidates
void CNNBallDetector::extractPatches()
{
int idx = 0;
for(BestPatchList::reverse_iterator i = best.rbegin(); i != best.rend(); ++i)
{
if(idx >= params.numberOfExportBestPatches) {
break;
}
int offset = ((*i).max.x - (*i).min.x)/4;
Vector2i min = (*i).min - offset;
Vector2i max = (*i).max + offset;
if(getFieldPercept().getValidField().isInside(min) && getFieldPercept().getValidField().isInside(max))
{
BallCandidates::PatchYUVClassified& q = getBallCandidates().nextFreePatchYUVClassified();
q.min = min;
q.max = max;
q.setSize(24);
PatchWork::subsampling(getImage(), getFieldColorPercept(), q);
idx++;
}
}
}
void CNNBallDetector::addBallPercept(const Vector2i& center, double radius)
{
const double ballRadius = 50.0;
MultiBallPercept::BallPercept ballPercept;
if(CameraGeometry::imagePixelToFieldCoord(
getCameraMatrix(),
getImage().cameraInfo,
center.x,
center.y,
ballRadius,
ballPercept.positionOnField))
{
ballPercept.cameraId = cameraID;
ballPercept.centerInImage = center;
ballPercept.radiusInImage = radius;
getMultiBallPercept().add(ballPercept);
getMultiBallPercept().frameInfoWhenBallWasSeen = getFrameInfo();
}
}
<|endoftext|>
|
<commit_before>#include <sstream>
#include <algorithm>
#include <set>
#include <memory>
#include <dlfcn.h>
#include "plugin-loader.hpp"
#include "output-layout.hpp"
#include "output.hpp"
#include "../core/wm.hpp"
#include "core.hpp"
#include "debug.hpp"
namespace
{
template<class A, class B> B union_cast(A object)
{
union {
A x;
B y;
} helper;
helper.x = object;
return helper.y;
}
}
static const std::string default_plugins = "viewport_impl move resize animate \
switcher vswitch cube expo command \
grid";
plugin_manager::plugin_manager(wf::output_t *o, wayfire_config *config)
{
this->config = config;
this->output = o;
auto section = config->get_section("core");
plugins_opt = section->get_option("plugins", "none");
reload_dynamic_plugins();
load_static_plugins();
list_updated = [=] ()
{
/* reload when config reload has finished */
idle_reaload_plugins.run_once([&] () {reload_dynamic_plugins(); });
};
plugins_opt->updated.push_back(&list_updated);
}
void plugin_manager::deinit_plugins(bool unloadable)
{
for (auto& p : loaded_plugins)
{
if (!p.second) // already destroyed on the previous iteration
continue;
if (p.second->is_unloadable() == unloadable)
destroy_plugin(p.second);
}
}
plugin_manager::~plugin_manager()
{
/* First remove unloadable plugins, then others */
deinit_plugins(true);
deinit_plugins(false);
loaded_plugins.clear();
plugins_opt->updated.erase(
std::remove(plugins_opt->updated.begin(), plugins_opt->updated.end(),
&list_updated), plugins_opt->updated.end());
}
void plugin_manager::init_plugin(wayfire_plugin& p)
{
p->grab_interface = std::make_unique<wf::plugin_grab_interface_t> (output);
p->output = output;
p->init(config);
}
void plugin_manager::destroy_plugin(wayfire_plugin& p)
{
p->grab_interface->ungrab();
output->deactivate_plugin(p->grab_interface);
p->fini();
/** dlopen()/dlclose() do reference counting */
if (p->handle)
dlclose(p->handle);
p.reset();
}
wayfire_plugin plugin_manager::load_plugin_from_file(std::string path)
{
// RTLD_GLOBAL is required for RTTI/dynamic_cast across plugins
void *handle = dlopen(path.c_str(), RTLD_NOW | RTLD_GLOBAL);
if(handle == NULL)
{
log_error("error loading plugin: %s", dlerror());
return nullptr;
}
/* Check plugin version */
auto version_func_ptr = dlsym(handle, "getWayfireVersion");
if (version_func_ptr == NULL)
{
log_error("%s: missing getWayfireVersion()", path.c_str());
dlclose(handle);
return nullptr;
}
auto version_func =
union_cast<void*, wayfire_plugin_version_func> (version_func_ptr);
int32_t plugin_abi_version = version_func();
if (version_func() != WAYFIRE_API_ABI_VERSION)
{
log_error("%s: API/ABI version mismatch: Wayfire is %d, plugin built "
"with %d", path.c_str(), WAYFIRE_API_ABI_VERSION, plugin_abi_version);
dlclose(handle);
return nullptr;
}
auto new_instance_func_ptr = dlsym(handle, "newInstance");
if(new_instance_func_ptr == NULL)
{
log_error("%s: missing newInstance(). %s", path.c_str(), dlerror());
return nullptr;
}
log_debug("loading plugin %s", path.c_str());
auto new_instance_func =
union_cast<void*, wayfire_plugin_load_func> (new_instance_func_ptr);
auto ptr = wayfire_plugin(new_instance_func());
ptr->handle = handle;
return ptr;
}
void plugin_manager::reload_dynamic_plugins()
{
auto plugin_list = plugins_opt->as_string();
if (plugin_list == "none")
{
log_error("No plugins specified in the config file, or config file is "
"missing. In this state the compositor is nearly unusable, please "
"ensure your configuration file is set up properly.");
plugin_list = default_plugins;
}
std::stringstream stream(plugin_list);
std::vector<std::string> next_plugins;
auto plugin_prefix = std::string(INSTALL_PREFIX "/lib/wayfire/");
std::string plugin_name;
while(stream >> plugin_name)
{
if (plugin_name.size())
{
if (plugin_name.at(0) == '/')
next_plugins.push_back(plugin_name);
else
next_plugins.push_back(plugin_prefix + "lib" + plugin_name + ".so");
}
}
/* erase plugins that have been removed from the config */
auto it = loaded_plugins.begin();
while(it != loaded_plugins.end())
{
/* skip built-in(static) plugins */
if (it->first.size() && it->first[0] == '_')
{
++it;
continue;
}
if (std::find(next_plugins.begin(), next_plugins.end(), it->first) == next_plugins.end() &&
it->second->is_unloadable())
{
log_debug("unload plugin %s", it->first.c_str());
destroy_plugin(it->second);
it = loaded_plugins.erase(it);
}
else
{
++it;
}
}
/* load new plugins */
for (auto plugin : next_plugins)
{
if (loaded_plugins.count(plugin))
continue;
auto ptr = load_plugin_from_file(plugin);
if (ptr)
{
init_plugin(ptr);
loaded_plugins[plugin] = std::move(ptr);
}
}
}
template<class T> static wayfire_plugin create_plugin()
{
return std::unique_ptr<wf::plugin_interface_t>(new T);
}
void plugin_manager::load_static_plugins()
{
loaded_plugins["_exit"] = create_plugin<wayfire_exit>();
loaded_plugins["_focus"] = create_plugin<wayfire_focus>();
loaded_plugins["_close"] = create_plugin<wayfire_close>();
loaded_plugins["_focus_parent"] = create_plugin<wayfire_handle_focus_parent>();
init_plugin(loaded_plugins["_exit"]);
init_plugin(loaded_plugins["_focus"]);
init_plugin(loaded_plugins["_close"]);
init_plugin(loaded_plugins["_focus_parent"]);
}
<commit_msg>plugin-loader: dlclose() after destroying the plugin entirely<commit_after>#include <sstream>
#include <algorithm>
#include <set>
#include <memory>
#include <dlfcn.h>
#include "plugin-loader.hpp"
#include "output-layout.hpp"
#include "output.hpp"
#include "../core/wm.hpp"
#include "core.hpp"
#include "debug.hpp"
namespace
{
template<class A, class B> B union_cast(A object)
{
union {
A x;
B y;
} helper;
helper.x = object;
return helper.y;
}
}
static const std::string default_plugins = "viewport_impl move resize animate \
switcher vswitch cube expo command \
grid";
plugin_manager::plugin_manager(wf::output_t *o, wayfire_config *config)
{
this->config = config;
this->output = o;
auto section = config->get_section("core");
plugins_opt = section->get_option("plugins", "none");
reload_dynamic_plugins();
load_static_plugins();
list_updated = [=] ()
{
/* reload when config reload has finished */
idle_reaload_plugins.run_once([&] () {reload_dynamic_plugins(); });
};
plugins_opt->updated.push_back(&list_updated);
}
void plugin_manager::deinit_plugins(bool unloadable)
{
for (auto& p : loaded_plugins)
{
if (!p.second) // already destroyed on the previous iteration
continue;
if (p.second->is_unloadable() == unloadable)
destroy_plugin(p.second);
}
}
plugin_manager::~plugin_manager()
{
/* First remove unloadable plugins, then others */
deinit_plugins(true);
deinit_plugins(false);
loaded_plugins.clear();
plugins_opt->updated.erase(
std::remove(plugins_opt->updated.begin(), plugins_opt->updated.end(),
&list_updated), plugins_opt->updated.end());
}
void plugin_manager::init_plugin(wayfire_plugin& p)
{
p->grab_interface = std::make_unique<wf::plugin_grab_interface_t> (output);
p->output = output;
p->init(config);
}
void plugin_manager::destroy_plugin(wayfire_plugin& p)
{
p->grab_interface->ungrab();
output->deactivate_plugin(p->grab_interface);
p->fini();
auto handle = p->handle;
p.reset();
/* dlopen()/dlclose() do reference counting, so we should close the plugin
* as many times as we opened it.
*
* We also need to close the handle after deallocating the plugin, otherwise
* we unload its destructor before calling it. */
if (handle)
dlclose(handle);
}
wayfire_plugin plugin_manager::load_plugin_from_file(std::string path)
{
// RTLD_GLOBAL is required for RTTI/dynamic_cast across plugins
void *handle = dlopen(path.c_str(), RTLD_NOW | RTLD_GLOBAL);
if(handle == NULL)
{
log_error("error loading plugin: %s", dlerror());
return nullptr;
}
/* Check plugin version */
auto version_func_ptr = dlsym(handle, "getWayfireVersion");
if (version_func_ptr == NULL)
{
log_error("%s: missing getWayfireVersion()", path.c_str());
dlclose(handle);
return nullptr;
}
auto version_func =
union_cast<void*, wayfire_plugin_version_func> (version_func_ptr);
int32_t plugin_abi_version = version_func();
if (version_func() != WAYFIRE_API_ABI_VERSION)
{
log_error("%s: API/ABI version mismatch: Wayfire is %d, plugin built "
"with %d", path.c_str(), WAYFIRE_API_ABI_VERSION, plugin_abi_version);
dlclose(handle);
return nullptr;
}
auto new_instance_func_ptr = dlsym(handle, "newInstance");
if(new_instance_func_ptr == NULL)
{
log_error("%s: missing newInstance(). %s", path.c_str(), dlerror());
return nullptr;
}
log_debug("loading plugin %s", path.c_str());
auto new_instance_func =
union_cast<void*, wayfire_plugin_load_func> (new_instance_func_ptr);
auto ptr = wayfire_plugin(new_instance_func());
ptr->handle = handle;
return ptr;
}
void plugin_manager::reload_dynamic_plugins()
{
auto plugin_list = plugins_opt->as_string();
if (plugin_list == "none")
{
log_error("No plugins specified in the config file, or config file is "
"missing. In this state the compositor is nearly unusable, please "
"ensure your configuration file is set up properly.");
plugin_list = default_plugins;
}
std::stringstream stream(plugin_list);
std::vector<std::string> next_plugins;
auto plugin_prefix = std::string(INSTALL_PREFIX "/lib/wayfire/");
std::string plugin_name;
while(stream >> plugin_name)
{
if (plugin_name.size())
{
if (plugin_name.at(0) == '/')
next_plugins.push_back(plugin_name);
else
next_plugins.push_back(plugin_prefix + "lib" + plugin_name + ".so");
}
}
/* erase plugins that have been removed from the config */
auto it = loaded_plugins.begin();
while(it != loaded_plugins.end())
{
/* skip built-in(static) plugins */
if (it->first.size() && it->first[0] == '_')
{
++it;
continue;
}
if (std::find(next_plugins.begin(), next_plugins.end(), it->first) == next_plugins.end() &&
it->second->is_unloadable())
{
log_debug("unload plugin %s", it->first.c_str());
destroy_plugin(it->second);
it = loaded_plugins.erase(it);
}
else
{
++it;
}
}
/* load new plugins */
for (auto plugin : next_plugins)
{
if (loaded_plugins.count(plugin))
continue;
auto ptr = load_plugin_from_file(plugin);
if (ptr)
{
init_plugin(ptr);
loaded_plugins[plugin] = std::move(ptr);
}
}
}
template<class T> static wayfire_plugin create_plugin()
{
return std::unique_ptr<wf::plugin_interface_t>(new T);
}
void plugin_manager::load_static_plugins()
{
loaded_plugins["_exit"] = create_plugin<wayfire_exit>();
loaded_plugins["_focus"] = create_plugin<wayfire_focus>();
loaded_plugins["_close"] = create_plugin<wayfire_close>();
loaded_plugins["_focus_parent"] = create_plugin<wayfire_handle_focus_parent>();
init_plugin(loaded_plugins["_exit"]);
init_plugin(loaded_plugins["_focus"]);
init_plugin(loaded_plugins["_close"]);
init_plugin(loaded_plugins["_focus_parent"]);
}
<|endoftext|>
|
<commit_before>//===----------------------------------------------------------------------===//
//
// PelotonDB
//
// ddl_table.cpp
//
// Identification: src/backend/bridge/ddl/ddl_table.cpp
//
// Copyright (c) 2015, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include <cassert>
#include <iostream>
#include <vector>
#include "backend/bridge/ddl/ddl.h"
#include "backend/bridge/ddl/ddl_table.h"
#include "backend/bridge/ddl/ddl_database.h"
#include "backend/bridge/ddl/ddl_utils.h"
#include "backend/common/logger.h"
#include "backend/storage/backend_vm.h"
#include "backend/storage/table_factory.h"
#include "backend/storage/database.h"
#include "commands/dbcommands.h"
#include "nodes/pg_list.h"
#include "parser/parse_utilcmd.h"
namespace peloton {
namespace bridge {
//===--------------------------------------------------------------------===//
// Table DDL
//===--------------------------------------------------------------------===//
/**
* @brief Execute the create stmt.
* @param the parse tree
* @param query string
* @return true if we handled it correctly, false otherwise
*/
bool DDLTable::ExecCreateStmt(Node *parsetree,
std::vector<Node *> &parsetree_stack,
Peloton_Status *status, TransactionId txn_id) {
List *stmts = ((CreateStmt *)parsetree)->stmts;
/* ... and do it */
ListCell *l;
foreach (l, stmts) {
Node *stmt = (Node *)lfirst(l);
if (IsA(stmt, CreateStmt)) {
CreateStmt *Cstmt = (CreateStmt *)stmt;
List *schema = (List *)(Cstmt->tableElts);
// Relation name and oid
char *relation_name = Cstmt->relation->relname;
Oid relation_oid = ((CreateStmt *)parsetree)->relation_id;
assert(relation_oid);
std::vector<catalog::Column> column_infos;
std::vector<catalog::ForeignKey> foreign_keys;
bool status;
//===--------------------------------------------------------------------===//
// CreateStmt --> ColumnInfo --> CreateTable
//===--------------------------------------------------------------------===//
if (schema != NULL) {
DDLUtils::ParsingCreateStmt(Cstmt, column_infos, foreign_keys);
DDLTable::CreateTable(relation_oid, relation_name, column_infos);
}
//===--------------------------------------------------------------------===//
// Set Reference Tables
//===--------------------------------------------------------------------===//
status = DDLTable::SetReferenceTables(foreign_keys, relation_oid);
if (status == false) {
LOG_WARN("Failed to set reference tables");
}
}
}
//===--------------------------------------------------------------------===//
// Rerun query
//===--------------------------------------------------------------------===//
for (auto parsetree : parsetree_stack) {
DDL::ProcessUtility(parsetree, "rerun", status, txn_id);
}
parsetree_stack.clear();
return true;
}
/**
* @brief Execute the alter stmt.
* @param the parsetree
* @param the parsetree_stack store parsetree if the table is not created yet
* @return true if we handled it correctly, false otherwise
*/
bool DDLTable::ExecAlterTableStmt(Node *parsetree,
std::vector<Node *> &parsetree_stack) {
AlterTableStmt *atstmt = (AlterTableStmt *)parsetree;
Oid relation_oid = atstmt->relation_id;
List *stmts = atstmt->stmts;
// If table has not been created yet, store it into the parsetree stack
auto &manager = catalog::Manager::GetInstance();
storage::Database *db =
manager.GetDatabaseWithOid(Bridge::GetCurrentDatabaseOid());
if (nullptr == db->GetTableWithOid(relation_oid)) {
parsetree_stack.push_back(parsetree);
return true;
}
ListCell *l;
foreach (l, stmts) {
Node *stmt = (Node *)lfirst(l);
if (IsA(stmt, AlterTableStmt)) {
DDLTable::AlterTable(relation_oid, (AlterTableStmt *)stmt);
}
}
return true;
}
/**
* @brief Execute the drop stmt.
* @param the parse tree
* @return true if we handled it correctly, false otherwise
*/
bool DDLTable::ExecDropStmt(Node *parsetree) {
DropStmt *drop = (DropStmt *)parsetree;
// TODO drop->behavior; /* RESTRICT or CASCADE behavior */
ListCell *cell;
foreach (cell, drop->objects) {
List *names = ((List *)lfirst(cell));
switch (drop->removeType) {
case OBJECT_TABLE: {
char *table_name = strVal(linitial(names));
auto &manager = catalog::Manager::GetInstance();
storage::Database *db =
manager.GetDatabaseWithOid(Bridge::GetCurrentDatabaseOid());
auto table = db->GetTableWithName(table_name);
// skip if no table
if (table == nullptr) break;
Oid table_oid = table->GetOid();
DDLTable::DropTable(table_oid);
} break;
default: {
LOG_WARN("Unsupported drop object %d ", drop->removeType);
} break;
}
}
return true;
}
/**
* @brief Create table.
* @param table_name Table name
* @param column_infos Information about the columns
* @param schema Schema for the table
* @return true if we created a table, false otherwise
*/
bool DDLTable::CreateTable(Oid relation_oid, std::string table_name,
std::vector<catalog::Column> column_infos,
catalog::Schema *schema) {
assert(!table_name.empty());
Oid database_oid = Bridge::GetCurrentDatabaseOid();
if (database_oid == INVALID_OID || relation_oid == INVALID_OID) return false;
// Get db oid
auto &manager = catalog::Manager::GetInstance();
storage::Database *db = manager.GetDatabaseWithOid(database_oid);
// Construct our schema from vector of ColumnInfo
if (schema == NULL) schema = new catalog::Schema(column_infos);
// Build a table from schema
storage::DataTable *table = storage::TableFactory::GetDataTable(
database_oid, relation_oid, schema, table_name);
db->AddTable(table);
if (table != nullptr) {
LOG_INFO("Created table(%u)%s in database(%u) ", relation_oid,
table_name.c_str(), database_oid);
return true;
}
return false;
}
/**
* @brief AlterTable with given AlterTableStmt
* @param relation_oid relation oid
* @param Astmt AlterTableStmt
* @return true if we alter the table successfully, false otherwise
*/
bool DDLTable::AlterTable(Oid relation_oid, AlterTableStmt *Astmt) {
ListCell *lcmd;
foreach (lcmd, Astmt->cmds) {
AlterTableCmd *cmd = (AlterTableCmd *)lfirst(lcmd);
switch (cmd->subtype) {
// case AT_AddColumn: /* add column */
// case AT_DropColumn: /* drop column */
case AT_AddConstraint: /* ADD CONSTRAINT */
{
bool status = AddConstraint(relation_oid, (Constraint *)cmd->def);
if (status == false) {
LOG_WARN("Failed to add constraint");
}
break;
}
default:
break;
}
}
LOG_INFO("Alter the table (%u)\n", relation_oid);
return true;
}
/**
* @brief Drop table.
* @param table_oid Table id.
* @return true if we dropped the table, false otherwise
*/
// FIXME :: Dependencies btw indexes and tables
bool DDLTable::DropTable(Oid table_oid) {
oid_t database_oid = Bridge::GetCurrentDatabaseOid();
if (database_oid == InvalidOid || table_oid == InvalidOid) {
LOG_WARN("Could not drop table :: db oid : %u table oid : %u", database_oid,
table_oid);
return false;
}
// Get db with current database oid
auto &manager = catalog::Manager::GetInstance();
storage::Database *db = manager.GetDatabaseWithOid(database_oid);
db->DropTableWithOid(table_oid);
LOG_INFO("Dropped table with oid : %u\n", table_oid);
return true;
}
/**
* @brief Add new constraint to the table
* @param relation_oid relation oid
* @param constraint constraint
* @return true if we add the constraint, false otherwise
*/
bool DDLTable::AddConstraint(Oid relation_oid, Constraint *constraint) {
ConstraintType contype = PostgresConstraintTypeToPelotonConstraintType(
(PostgresConstraintType)constraint->contype);
std::vector<catalog::ForeignKey> foreign_keys;
std::string conname;
if (constraint->conname != NULL) {
conname = constraint->conname;
} else {
conname = "";
}
switch (contype) {
case CONSTRAINT_TYPE_FOREIGN: {
oid_t database_oid = Bridge::GetCurrentDatabaseOid();
assert(database_oid);
auto &manager = catalog::Manager::GetInstance();
storage::Database *db = manager.GetDatabaseWithOid(database_oid);
// PrimaryKey Table
oid_t PrimaryKeyTableId =
db->GetTableWithName(constraint->pktable->relname)->GetOid();
// Each table column names
std::vector<std::string> pk_column_names;
std::vector<std::string> fk_column_names;
ListCell *column;
if (constraint->pk_attrs != NULL && constraint->pk_attrs->length > 0) {
foreach (column, constraint->pk_attrs) {
char *attname = strVal(lfirst(column));
pk_column_names.push_back(attname);
}
}
if (constraint->fk_attrs != NULL && constraint->fk_attrs->length > 0) {
foreach (column, constraint->fk_attrs) {
char *attname = strVal(lfirst(column));
fk_column_names.push_back(attname);
}
}
catalog::ForeignKey *foreign_key = new catalog::ForeignKey(
PrimaryKeyTableId, pk_column_names, fk_column_names,
constraint->fk_upd_action, constraint->fk_del_action, conname);
foreign_keys.push_back(*foreign_key);
} break;
default:
LOG_WARN("Unrecognized constraint type %d\n", (int)contype);
break;
}
// FIXME :
bool status = SetReferenceTables(foreign_keys, relation_oid);
if (status == false) {
LOG_WARN("Failed to set reference tables");
}
return true;
}
/**
* @brief Set Reference Tables
* @param reference table namees reference table names
* @param relation_oid relation oid
* @return true if we set the reference tables, false otherwise
*/
bool DDLTable::SetReferenceTables(
std::vector<catalog::ForeignKey> &foreign_keys, oid_t relation_oid) {
assert(relation_oid);
oid_t database_oid = Bridge::GetCurrentDatabaseOid();
assert(database_oid);
storage::DataTable *current_table =
(storage::DataTable *)catalog::Manager::GetInstance().GetTableWithOid(
database_oid, relation_oid);
for (auto foreign_key : foreign_keys) {
current_table->AddForeignKey(&foreign_key);
}
return true;
}
} // namespace bridge
} // namespace peloton
<commit_msg>Don't put nullptr into the vector..<commit_after>//===----------------------------------------------------------------------===//
//
// PelotonDB
//
// ddl_table.cpp
//
// Identification: src/backend/bridge/ddl/ddl_table.cpp
//
// Copyright (c) 2015, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include <cassert>
#include <iostream>
#include <vector>
#include "backend/bridge/ddl/ddl.h"
#include "backend/bridge/ddl/ddl_table.h"
#include "backend/bridge/ddl/ddl_database.h"
#include "backend/bridge/ddl/ddl_utils.h"
#include "backend/common/logger.h"
#include "backend/storage/backend_vm.h"
#include "backend/storage/table_factory.h"
#include "backend/storage/database.h"
#include "commands/dbcommands.h"
#include "nodes/pg_list.h"
#include "parser/parse_utilcmd.h"
namespace peloton {
namespace bridge {
//===--------------------------------------------------------------------===//
// Table DDL
//===--------------------------------------------------------------------===//
/**
* @brief Execute the create stmt.
* @param the parse tree
* @param query string
* @return true if we handled it correctly, false otherwise
*/
bool DDLTable::ExecCreateStmt(Node *parsetree,
std::vector<Node *> &parsetree_stack,
Peloton_Status *status, TransactionId txn_id) {
List *stmts = ((CreateStmt *)parsetree)->stmts;
/* ... and do it */
ListCell *l;
foreach (l, stmts) {
Node *stmt = (Node *)lfirst(l);
if (IsA(stmt, CreateStmt)) {
CreateStmt *Cstmt = (CreateStmt *)stmt;
List *schema = (List *)(Cstmt->tableElts);
// Relation name and oid
char *relation_name = Cstmt->relation->relname;
Oid relation_oid = ((CreateStmt *)parsetree)->relation_id;
assert(relation_oid);
std::vector<catalog::Column> column_infos;
std::vector<catalog::ForeignKey> foreign_keys;
bool status;
//===--------------------------------------------------------------------===//
// CreateStmt --> ColumnInfo --> CreateTable
//===--------------------------------------------------------------------===//
if (schema != NULL) {
DDLUtils::ParsingCreateStmt(Cstmt, column_infos, foreign_keys);
DDLTable::CreateTable(relation_oid, relation_name, column_infos);
}
//===--------------------------------------------------------------------===//
// Set Reference Tables
//===--------------------------------------------------------------------===//
status = DDLTable::SetReferenceTables(foreign_keys, relation_oid);
if (status == false) {
LOG_WARN("Failed to set reference tables");
}
}
}
//===--------------------------------------------------------------------===//
// Rerun query
//===--------------------------------------------------------------------===//
for (auto parsetree : parsetree_stack) {
DDL::ProcessUtility(parsetree, "rerun", status, txn_id);
}
parsetree_stack.clear();
return true;
}
/**
* @brief Execute the alter stmt.
* @param the parsetree
* @param the parsetree_stack store parsetree if the table is not created yet
* @return true if we handled it correctly, false otherwise
*/
bool DDLTable::ExecAlterTableStmt(Node *parsetree,
std::vector<Node *> &parsetree_stack) {
AlterTableStmt *atstmt = (AlterTableStmt *)parsetree;
Oid relation_oid = atstmt->relation_id;
List *stmts = atstmt->stmts;
// If table has not been created yet, store it into the parsetree stack
auto &manager = catalog::Manager::GetInstance();
storage::Database *db =
manager.GetDatabaseWithOid(Bridge::GetCurrentDatabaseOid());
if (nullptr == db->GetTableWithOid(relation_oid)) {
parsetree_stack.push_back(parsetree);
return true;
}
ListCell *l;
foreach (l, stmts) {
Node *stmt = (Node *)lfirst(l);
if (IsA(stmt, AlterTableStmt)) {
DDLTable::AlterTable(relation_oid, (AlterTableStmt *)stmt);
}
}
return true;
}
/**
* @brief Execute the drop stmt.
* @param the parse tree
* @return true if we handled it correctly, false otherwise
*/
bool DDLTable::ExecDropStmt(Node *parsetree) {
DropStmt *drop = (DropStmt *)parsetree;
// TODO drop->behavior; /* RESTRICT or CASCADE behavior */
ListCell *cell;
foreach (cell, drop->objects) {
List *names = ((List *)lfirst(cell));
switch (drop->removeType) {
case OBJECT_TABLE: {
char *table_name = strVal(linitial(names));
auto &manager = catalog::Manager::GetInstance();
storage::Database *db =
manager.GetDatabaseWithOid(Bridge::GetCurrentDatabaseOid());
auto table = db->GetTableWithName(table_name);
// skip if no table
if (table == nullptr) break;
Oid table_oid = table->GetOid();
DDLTable::DropTable(table_oid);
} break;
default: {
LOG_WARN("Unsupported drop object %d ", drop->removeType);
} break;
}
}
return true;
}
/**
* @brief Create table.
* @param table_name Table name
* @param column_infos Information about the columns
* @param schema Schema for the table
* @return true if we created a table, false otherwise
*/
bool DDLTable::CreateTable(Oid relation_oid, std::string table_name,
std::vector<catalog::Column> column_infos,
catalog::Schema *schema) {
assert(!table_name.empty());
Oid database_oid = Bridge::GetCurrentDatabaseOid();
if (database_oid == INVALID_OID || relation_oid == INVALID_OID) return false;
// Get db oid
auto &manager = catalog::Manager::GetInstance();
storage::Database *db = manager.GetDatabaseWithOid(database_oid);
// Construct our schema from vector of ColumnInfo
if (schema == NULL) schema = new catalog::Schema(column_infos);
// Build a table from schema
storage::DataTable *table = storage::TableFactory::GetDataTable(
database_oid, relation_oid, schema, table_name);
if (table != nullptr) {
LOG_INFO("Created table(%u)%s in database(%u) ", relation_oid,
table_name.c_str(), database_oid);
db->AddTable(table);
return true;
}
return false;
}
/**
* @brief AlterTable with given AlterTableStmt
* @param relation_oid relation oid
* @param Astmt AlterTableStmt
* @return true if we alter the table successfully, false otherwise
*/
bool DDLTable::AlterTable(Oid relation_oid, AlterTableStmt *Astmt) {
ListCell *lcmd;
foreach (lcmd, Astmt->cmds) {
AlterTableCmd *cmd = (AlterTableCmd *)lfirst(lcmd);
switch (cmd->subtype) {
// case AT_AddColumn: /* add column */
// case AT_DropColumn: /* drop column */
case AT_AddConstraint: /* ADD CONSTRAINT */
{
bool status = AddConstraint(relation_oid, (Constraint *)cmd->def);
if (status == false) {
LOG_WARN("Failed to add constraint");
}
break;
}
default:
break;
}
}
LOG_INFO("Alter the table (%u)\n", relation_oid);
return true;
}
/**
* @brief Drop table.
* @param table_oid Table id.
* @return true if we dropped the table, false otherwise
*/
// FIXME :: Dependencies btw indexes and tables
bool DDLTable::DropTable(Oid table_oid) {
oid_t database_oid = Bridge::GetCurrentDatabaseOid();
if (database_oid == InvalidOid || table_oid == InvalidOid) {
LOG_WARN("Could not drop table :: db oid : %u table oid : %u", database_oid,
table_oid);
return false;
}
// Get db with current database oid
auto &manager = catalog::Manager::GetInstance();
storage::Database *db = manager.GetDatabaseWithOid(database_oid);
db->DropTableWithOid(table_oid);
LOG_INFO("Dropped table with oid : %u\n", table_oid);
return true;
}
/**
* @brief Add new constraint to the table
* @param relation_oid relation oid
* @param constraint constraint
* @return true if we add the constraint, false otherwise
*/
bool DDLTable::AddConstraint(Oid relation_oid, Constraint *constraint) {
ConstraintType contype = PostgresConstraintTypeToPelotonConstraintType(
(PostgresConstraintType)constraint->contype);
std::vector<catalog::ForeignKey> foreign_keys;
std::string conname;
if (constraint->conname != NULL) {
conname = constraint->conname;
} else {
conname = "";
}
switch (contype) {
case CONSTRAINT_TYPE_FOREIGN: {
oid_t database_oid = Bridge::GetCurrentDatabaseOid();
assert(database_oid);
auto &manager = catalog::Manager::GetInstance();
storage::Database *db = manager.GetDatabaseWithOid(database_oid);
// PrimaryKey Table
oid_t PrimaryKeyTableId =
db->GetTableWithName(constraint->pktable->relname)->GetOid();
// Each table column names
std::vector<std::string> pk_column_names;
std::vector<std::string> fk_column_names;
ListCell *column;
if (constraint->pk_attrs != NULL && constraint->pk_attrs->length > 0) {
foreach (column, constraint->pk_attrs) {
char *attname = strVal(lfirst(column));
pk_column_names.push_back(attname);
}
}
if (constraint->fk_attrs != NULL && constraint->fk_attrs->length > 0) {
foreach (column, constraint->fk_attrs) {
char *attname = strVal(lfirst(column));
fk_column_names.push_back(attname);
}
}
catalog::ForeignKey *foreign_key = new catalog::ForeignKey(
PrimaryKeyTableId, pk_column_names, fk_column_names,
constraint->fk_upd_action, constraint->fk_del_action, conname);
foreign_keys.push_back(*foreign_key);
} break;
default:
LOG_WARN("Unrecognized constraint type %d\n", (int)contype);
break;
}
// FIXME :
bool status = SetReferenceTables(foreign_keys, relation_oid);
if (status == false) {
LOG_WARN("Failed to set reference tables");
}
return true;
}
/**
* @brief Set Reference Tables
* @param reference table namees reference table names
* @param relation_oid relation oid
* @return true if we set the reference tables, false otherwise
*/
bool DDLTable::SetReferenceTables(
std::vector<catalog::ForeignKey> &foreign_keys, oid_t relation_oid) {
assert(relation_oid);
oid_t database_oid = Bridge::GetCurrentDatabaseOid();
assert(database_oid);
storage::DataTable *current_table =
(storage::DataTable *)catalog::Manager::GetInstance().GetTableWithOid(
database_oid, relation_oid);
for (auto foreign_key : foreign_keys) {
current_table->AddForeignKey(&foreign_key);
}
return true;
}
} // namespace bridge
} // namespace peloton
<|endoftext|>
|
<commit_before>/*
This file is part of Akregator.
Copyright (C) 2007 Frank Osterfeld <osterfeld@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.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include "selectioncontroller.h"
#include "actionmanager.h"
#include "article.h"
#include "articlejobs.h"
#include "articlemodel.h"
#include "feedlist.h"
#include "subscriptionlistmodel.h"
#include "treenode.h"
#include <KRandom>
#include <KDebug>
#include <QAbstractItemView>
#include <QMenu>
#include <QTimer>
using namespace boost;
using namespace Akregator;
namespace {
static Akregator::Article articleForIndex( const QModelIndex& index, FeedList* feedList )
{
if ( !index.isValid() )
return Akregator::Article();
const QString guid = index.data( ArticleModel::GuidRole ).toString();
const QString feedId = index.data( ArticleModel::FeedIdRole ).toString();
return feedList->findArticle( feedId, guid );
}
static QList<Akregator::Article> articlesForIndexes( const QModelIndexList& indexes, FeedList* feedList )
{
QList<Akregator::Article> articles;
Q_FOREACH ( const QModelIndex& i, indexes )
{
const Article a = articleForIndex( i, feedList );
if ( a.isNull() )
continue;
articles.append( articleForIndex( i, feedList ) );
}
return articles;
}
static Akregator::TreeNode* subscriptionForIndex( const QModelIndex& index, Akregator::FeedList* feedList )
{
if ( !index.isValid() )
return 0L;
return feedList->findByID( index.data( Akregator::SubscriptionListModel::SubscriptionIdRole ).toInt() );
}
} // anon namespace
Akregator::SelectionController::SelectionController( QObject* parent )
: AbstractSelectionController( parent ),
m_feedList(),
m_feedSelector(),
m_articleLister( 0 ),
m_singleDisplay( 0 ),
m_subscriptionModel ( new SubscriptionListModel( shared_ptr<FeedList>(), this ) ),
m_folderExpansionHandler( 0 ),
m_articleModel( 0 ),
m_selectedSubscription()
{
}
Akregator::SelectionController::~SelectionController()
{
delete m_articleModel;
}
void Akregator::SelectionController::setFeedSelector( QAbstractItemView* feedSelector )
{
if ( m_feedSelector == feedSelector )
return;
if ( m_feedSelector ) {
m_feedSelector->disconnect( this );
m_feedSelector->selectionModel()->disconnect( this );
}
m_feedSelector = feedSelector;
if ( !m_feedSelector )
return;
m_feedSelector->setModel( m_subscriptionModel );
connect( m_feedSelector, SIGNAL(customContextMenuRequested(QPoint)),
this, SLOT(subscriptionContextMenuRequested(QPoint)) );
connect( m_feedSelector->selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)),
this, SLOT(selectedSubscriptionChanged(QModelIndex)) );
}
void Akregator::SelectionController::setArticleLister( Akregator::ArticleLister* lister )
{
if ( m_articleLister == lister )
return;
if ( m_articleLister )
m_articleLister->articleSelectionModel()->disconnect( this );
if ( m_articleLister && m_articleLister->itemView() )
m_articleLister->itemView()->disconnect( this );
m_articleLister = lister;
if ( m_articleLister && m_articleLister->itemView() )
connect( m_articleLister->itemView(), SIGNAL(doubleClicked(QModelIndex)),
this, SLOT(articleIndexDoubleClicked(QModelIndex)) );
}
void Akregator::SelectionController::setSingleArticleDisplay( Akregator::SingleArticleDisplay* display )
{
m_singleDisplay = display;
}
Akregator::Article Akregator::SelectionController::currentArticle() const
{
return ::articleForIndex( m_articleLister->articleSelectionModel()->currentIndex(), m_feedList.get() );
}
QList<Akregator::Article> Akregator::SelectionController::selectedArticles() const
{
return ::articlesForIndexes( m_articleLister->articleSelectionModel()->selectedRows(), m_feedList.get() );
}
Akregator::TreeNode* Akregator::SelectionController::selectedSubscription() const
{
return ::subscriptionForIndex( m_feedSelector->selectionModel()->currentIndex(), m_feedList.get() );
}
void Akregator::SelectionController::setFeedList( const shared_ptr<FeedList>& list )
{
if ( m_feedList == list )
return;
m_feedList = list;
std::auto_ptr<SubscriptionListModel> oldModel( m_subscriptionModel );
m_subscriptionModel = new SubscriptionListModel( m_feedList, this );
if ( m_folderExpansionHandler ) {
m_folderExpansionHandler->setFeedList( m_feedList );
m_folderExpansionHandler->setModel( m_subscriptionModel );
}
if ( m_feedSelector ) {
m_feedSelector->setModel( m_subscriptionModel );
disconnect( m_feedSelector->selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)),
this, SLOT(selectedSubscriptionChanged(QModelIndex)) );
connect( m_feedSelector->selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)),
this, SLOT(selectedSubscriptionChanged(QModelIndex)) );
}
}
void Akregator::SelectionController::setFolderExpansionHandler( Akregator::FolderExpansionHandler* handler )
{
if ( handler == m_folderExpansionHandler )
return;
m_folderExpansionHandler = handler;
if ( !m_folderExpansionHandler )
return;
handler->setFeedList( m_feedList );
handler->setModel( m_subscriptionModel );
}
void Akregator::SelectionController::articleHeadersAvailable( KJob* job )
{
assert( job );
assert( job == m_listJob );
if ( job->error() ) {
kWarning() << job->errorText();
return;
}
TreeNode* const node = m_listJob->node();
assert( node ); // if there was no error, the node must still exist
assert( node == m_selectedSubscription ); //...and equal the previously selected node
ArticleModel* const newModel = new ArticleModel( m_listJob->articles() );
connect( node, SIGNAL( destroyed() ),
newModel, SLOT( clear() ) );
connect( node, SIGNAL( signalArticlesAdded( Akregator::TreeNode*, QList<Akregator::Article> ) ),
newModel, SLOT( articlesAdded( Akregator::TreeNode*, QList<Akregator::Article> ) ) );
connect( node, SIGNAL( signalArticlesRemoved( Akregator::TreeNode*, QList<Akregator::Article> ) ),
newModel, SLOT( articlesRemoved( Akregator::TreeNode*, QList<Akregator::Article> ) ) );
connect( node, SIGNAL( signalArticlesUpdated( Akregator::TreeNode*, QList<Akregator::Article> ) ),
newModel, SLOT( articlesUpdated( Akregator::TreeNode*, QList<Akregator::Article> ) ) );
m_articleLister->setIsAggregation( node->isAggregation() );
m_articleLister->setArticleModel( newModel );
delete m_articleModel; //order is important: do not delete the old model before the new model is set in the view
m_articleModel = newModel;
disconnect( m_articleLister->articleSelectionModel(), SIGNAL(selectionChanged(QItemSelection, QItemSelection)),
this, SLOT(articleSelectionChanged()) );
connect( m_articleLister->articleSelectionModel(), SIGNAL(selectionChanged(QItemSelection, QItemSelection)),
this, SLOT(articleSelectionChanged()) );
if ( node )
m_articleLister->setScrollBarPositions( node->listViewScrollBarPositions() );
}
void Akregator::SelectionController::selectedSubscriptionChanged( const QModelIndex& index )
{
if ( !index.isValid() )
return;
if ( m_selectedSubscription && m_articleLister )
m_selectedSubscription->setListViewScrollBarPositions( m_articleLister->scrollBarPositions() );
m_selectedSubscription = selectedSubscription();
emit currentSubscriptionChanged( m_selectedSubscription );
// using a timer here internally to simulate async data fetching (which is still synchronous),
// to ensure the UI copes with async behavior later on
delete m_listJob;
if ( !m_selectedSubscription )
return;
ArticleListJob* const job( new ArticleListJob( m_selectedSubscription ) );
connect( job, SIGNAL(finished(KJob*)),
this, SLOT(articleHeadersAvailable(KJob*)) );
m_listJob = job;
m_listJob->start();
}
void Akregator::SelectionController::subscriptionContextMenuRequested( const QPoint& point )
{
Q_ASSERT( m_feedSelector );
const TreeNode* const node = ::subscriptionForIndex( m_feedSelector->indexAt( point ), m_feedList.get() );
if ( !node )
return;
QWidget* w = ActionManager::getInstance()->container( node->isGroup() ? "feedgroup_popup" : "feeds_popup" );
QMenu* popup = qobject_cast<QMenu*>( w );
if ( popup )
{
const QPoint globalPos = m_feedSelector->viewport()->mapToGlobal( point );
popup->exec( globalPos );
}
}
void Akregator::SelectionController::articleSelectionChanged()
{
const Akregator::Article article = currentArticle();
if ( m_singleDisplay )
m_singleDisplay->showArticle( article );
emit currentArticleChanged( article );
}
void Akregator::SelectionController::articleIndexDoubleClicked( const QModelIndex& index )
{
const Akregator::Article article = ::articleForIndex( index, m_feedList.get() );
emit articleDoubleClicked( article );
}
void SelectionController::setFilters( const std::vector<boost::shared_ptr<const Filters::AbstractMatcher> >& matchers )
{
Q_ASSERT( m_articleLister );
m_articleLister->setFilters( matchers );
}
void SelectionController::forceFilterUpdate()
{
Q_ASSERT( m_articleLister );
m_articleLister->forceFilterUpdate();
}
#include "selectioncontroller.moc"
<commit_msg>don't crash when no selection model exists (as there is no feed selected) BUG:224555<commit_after>/*
This file is part of Akregator.
Copyright (C) 2007 Frank Osterfeld <osterfeld@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.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include "selectioncontroller.h"
#include "actionmanager.h"
#include "article.h"
#include "articlejobs.h"
#include "articlemodel.h"
#include "feedlist.h"
#include "subscriptionlistmodel.h"
#include "treenode.h"
#include <KRandom>
#include <KDebug>
#include <QAbstractItemView>
#include <QMenu>
#include <QTimer>
using namespace boost;
using namespace Akregator;
namespace {
static Akregator::Article articleForIndex( const QModelIndex& index, FeedList* feedList )
{
if ( !index.isValid() )
return Akregator::Article();
const QString guid = index.data( ArticleModel::GuidRole ).toString();
const QString feedId = index.data( ArticleModel::FeedIdRole ).toString();
return feedList->findArticle( feedId, guid );
}
static QList<Akregator::Article> articlesForIndexes( const QModelIndexList& indexes, FeedList* feedList )
{
QList<Akregator::Article> articles;
Q_FOREACH ( const QModelIndex& i, indexes )
{
const Article a = articleForIndex( i, feedList );
if ( a.isNull() )
continue;
articles.append( articleForIndex( i, feedList ) );
}
return articles;
}
static Akregator::TreeNode* subscriptionForIndex( const QModelIndex& index, Akregator::FeedList* feedList )
{
if ( !index.isValid() )
return 0L;
return feedList->findByID( index.data( Akregator::SubscriptionListModel::SubscriptionIdRole ).toInt() );
}
} // anon namespace
Akregator::SelectionController::SelectionController( QObject* parent )
: AbstractSelectionController( parent ),
m_feedList(),
m_feedSelector(),
m_articleLister( 0 ),
m_singleDisplay( 0 ),
m_subscriptionModel ( new SubscriptionListModel( shared_ptr<FeedList>(), this ) ),
m_folderExpansionHandler( 0 ),
m_articleModel( 0 ),
m_selectedSubscription()
{
}
Akregator::SelectionController::~SelectionController()
{
delete m_articleModel;
}
void Akregator::SelectionController::setFeedSelector( QAbstractItemView* feedSelector )
{
if ( m_feedSelector == feedSelector )
return;
if ( m_feedSelector ) {
m_feedSelector->disconnect( this );
m_feedSelector->selectionModel()->disconnect( this );
}
m_feedSelector = feedSelector;
if ( !m_feedSelector )
return;
m_feedSelector->setModel( m_subscriptionModel );
connect( m_feedSelector, SIGNAL(customContextMenuRequested(QPoint)),
this, SLOT(subscriptionContextMenuRequested(QPoint)) );
connect( m_feedSelector->selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)),
this, SLOT(selectedSubscriptionChanged(QModelIndex)) );
}
void Akregator::SelectionController::setArticleLister( Akregator::ArticleLister* lister )
{
if ( m_articleLister == lister )
return;
if ( m_articleLister )
m_articleLister->articleSelectionModel()->disconnect( this );
if ( m_articleLister && m_articleLister->itemView() )
m_articleLister->itemView()->disconnect( this );
m_articleLister = lister;
if ( m_articleLister && m_articleLister->itemView() )
connect( m_articleLister->itemView(), SIGNAL(doubleClicked(QModelIndex)),
this, SLOT(articleIndexDoubleClicked(QModelIndex)) );
}
void Akregator::SelectionController::setSingleArticleDisplay( Akregator::SingleArticleDisplay* display )
{
m_singleDisplay = display;
}
Akregator::Article Akregator::SelectionController::currentArticle() const
{
if ( !m_articleLister || !m_articleLister->articleSelectionModel() )
return Article();
return ::articleForIndex( m_articleLister->articleSelectionModel()->currentIndex(), m_feedList.get() );
}
QList<Akregator::Article> Akregator::SelectionController::selectedArticles() const
{
if ( !m_articleLister || !m_articleLister->articleSelectionModel() )
return QList<Akregator::Article>();
return ::articlesForIndexes( m_articleLister->articleSelectionModel()->selectedRows(), m_feedList.get() );
}
Akregator::TreeNode* Akregator::SelectionController::selectedSubscription() const
{
return ::subscriptionForIndex( m_feedSelector->selectionModel()->currentIndex(), m_feedList.get() );
}
void Akregator::SelectionController::setFeedList( const shared_ptr<FeedList>& list )
{
if ( m_feedList == list )
return;
m_feedList = list;
std::auto_ptr<SubscriptionListModel> oldModel( m_subscriptionModel );
m_subscriptionModel = new SubscriptionListModel( m_feedList, this );
if ( m_folderExpansionHandler ) {
m_folderExpansionHandler->setFeedList( m_feedList );
m_folderExpansionHandler->setModel( m_subscriptionModel );
}
if ( m_feedSelector ) {
m_feedSelector->setModel( m_subscriptionModel );
disconnect( m_feedSelector->selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)),
this, SLOT(selectedSubscriptionChanged(QModelIndex)) );
connect( m_feedSelector->selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)),
this, SLOT(selectedSubscriptionChanged(QModelIndex)) );
}
}
void Akregator::SelectionController::setFolderExpansionHandler( Akregator::FolderExpansionHandler* handler )
{
if ( handler == m_folderExpansionHandler )
return;
m_folderExpansionHandler = handler;
if ( !m_folderExpansionHandler )
return;
handler->setFeedList( m_feedList );
handler->setModel( m_subscriptionModel );
}
void Akregator::SelectionController::articleHeadersAvailable( KJob* job )
{
assert( job );
assert( job == m_listJob );
if ( job->error() ) {
kWarning() << job->errorText();
return;
}
TreeNode* const node = m_listJob->node();
assert( node ); // if there was no error, the node must still exist
assert( node == m_selectedSubscription ); //...and equal the previously selected node
ArticleModel* const newModel = new ArticleModel( m_listJob->articles() );
connect( node, SIGNAL( destroyed() ),
newModel, SLOT( clear() ) );
connect( node, SIGNAL( signalArticlesAdded( Akregator::TreeNode*, QList<Akregator::Article> ) ),
newModel, SLOT( articlesAdded( Akregator::TreeNode*, QList<Akregator::Article> ) ) );
connect( node, SIGNAL( signalArticlesRemoved( Akregator::TreeNode*, QList<Akregator::Article> ) ),
newModel, SLOT( articlesRemoved( Akregator::TreeNode*, QList<Akregator::Article> ) ) );
connect( node, SIGNAL( signalArticlesUpdated( Akregator::TreeNode*, QList<Akregator::Article> ) ),
newModel, SLOT( articlesUpdated( Akregator::TreeNode*, QList<Akregator::Article> ) ) );
m_articleLister->setIsAggregation( node->isAggregation() );
m_articleLister->setArticleModel( newModel );
delete m_articleModel; //order is important: do not delete the old model before the new model is set in the view
m_articleModel = newModel;
disconnect( m_articleLister->articleSelectionModel(), SIGNAL(selectionChanged(QItemSelection, QItemSelection)),
this, SLOT(articleSelectionChanged()) );
connect( m_articleLister->articleSelectionModel(), SIGNAL(selectionChanged(QItemSelection, QItemSelection)),
this, SLOT(articleSelectionChanged()) );
if ( node )
m_articleLister->setScrollBarPositions( node->listViewScrollBarPositions() );
}
void Akregator::SelectionController::selectedSubscriptionChanged( const QModelIndex& index )
{
if ( !index.isValid() )
return;
if ( m_selectedSubscription && m_articleLister )
m_selectedSubscription->setListViewScrollBarPositions( m_articleLister->scrollBarPositions() );
m_selectedSubscription = selectedSubscription();
emit currentSubscriptionChanged( m_selectedSubscription );
// using a timer here internally to simulate async data fetching (which is still synchronous),
// to ensure the UI copes with async behavior later on
delete m_listJob;
if ( !m_selectedSubscription )
return;
ArticleListJob* const job( new ArticleListJob( m_selectedSubscription ) );
connect( job, SIGNAL(finished(KJob*)),
this, SLOT(articleHeadersAvailable(KJob*)) );
m_listJob = job;
m_listJob->start();
}
void Akregator::SelectionController::subscriptionContextMenuRequested( const QPoint& point )
{
Q_ASSERT( m_feedSelector );
const TreeNode* const node = ::subscriptionForIndex( m_feedSelector->indexAt( point ), m_feedList.get() );
if ( !node )
return;
QWidget* w = ActionManager::getInstance()->container( node->isGroup() ? "feedgroup_popup" : "feeds_popup" );
QMenu* popup = qobject_cast<QMenu*>( w );
if ( popup )
{
const QPoint globalPos = m_feedSelector->viewport()->mapToGlobal( point );
popup->exec( globalPos );
}
}
void Akregator::SelectionController::articleSelectionChanged()
{
const Akregator::Article article = currentArticle();
if ( m_singleDisplay )
m_singleDisplay->showArticle( article );
emit currentArticleChanged( article );
}
void Akregator::SelectionController::articleIndexDoubleClicked( const QModelIndex& index )
{
const Akregator::Article article = ::articleForIndex( index, m_feedList.get() );
emit articleDoubleClicked( article );
}
void SelectionController::setFilters( const std::vector<boost::shared_ptr<const Filters::AbstractMatcher> >& matchers )
{
Q_ASSERT( m_articleLister );
m_articleLister->setFilters( matchers );
}
void SelectionController::forceFilterUpdate()
{
Q_ASSERT( m_articleLister );
m_articleLister->forceFilterUpdate();
}
#include "selectioncontroller.moc"
<|endoftext|>
|
<commit_before>#include <sys/errno.h>
#include <sys/uio.h>
#include <errno.h>
#include <limits.h>
#include <unistd.h>
#include <common/buffer.h>
#include <event/action.h>
#include <event/callback.h>
#include <event/event_system.h>
#include <io/io_system.h>
#define IO_READ_BUFFER_SIZE 65536
IOSystem::Handle::Handle(int fd, Channel *owner)
: log_("/io/system/handle"),
fd_(fd),
owner_(owner),
close_callback_(NULL),
close_action_(NULL),
read_amount_(0),
read_buffer_(),
read_callback_(NULL),
read_action_(NULL),
write_buffer_(),
write_callback_(NULL),
write_action_(NULL)
{ }
IOSystem::Handle::~Handle()
{
ASSERT(fd_ == -1);
ASSERT(close_action_ == NULL);
ASSERT(close_callback_ == NULL);
ASSERT(read_action_ == NULL);
ASSERT(read_callback_ == NULL);
ASSERT(write_action_ == NULL);
ASSERT(write_callback_ == NULL);
}
void
IOSystem::Handle::close_callback(void)
{
close_action_->cancel();
close_action_ = NULL;
ASSERT(fd_ != -1);
int rv = ::close(fd_);
if (rv == -1) {
switch (errno) {
case EAGAIN:
close_action_ = close_schedule();
break;
default:
close_callback_->event(Event(Event::Error, errno));
Action *a = EventSystem::instance()->schedule(close_callback_);
close_action_ = a;
close_callback_ = NULL;
break;
}
return;
}
fd_ = -1;
close_callback_->event(Event(Event::Done, 0));
Action *a = EventSystem::instance()->schedule(close_callback_);
close_action_ = a;
close_callback_ = NULL;
}
void
IOSystem::Handle::close_cancel(void)
{
ASSERT(close_action_ != NULL);
close_action_->cancel();
close_action_ = NULL;
if (close_callback_ != NULL) {
delete close_callback_;
close_callback_ = NULL;
}
}
Action *
IOSystem::Handle::close_schedule(void)
{
ASSERT(close_action_ == NULL);
Callback *cb = callback(this, &IOSystem::Handle::close_callback);
Action *a = EventSystem::instance()->schedule(cb);
return (a);
}
void
IOSystem::Handle::read_callback(Event e)
{
read_action_->cancel();
read_action_ = NULL;
switch (e.type_) {
case Event::EOS:
case Event::Done:
break;
default:
HALT(log_) << "Unexpected event: " << e;
}
size_t rlen;
if (read_amount_ == 0)
rlen = IO_READ_BUFFER_SIZE;
else {
rlen = read_amount_ - read_buffer_.length();
ASSERT(rlen != 0);
if (rlen > IO_READ_BUFFER_SIZE)
rlen = IO_READ_BUFFER_SIZE;
}
uint8_t data[IO_READ_BUFFER_SIZE];
ssize_t len = ::read(fd_, data, sizeof data);
if (len == -1) {
switch (errno) {
case EAGAIN:
read_action_ = read_schedule();
break;
default:
read_callback_->event(Event(Event::Error, errno, read_buffer_));
Action *a = EventSystem::instance()->schedule(read_callback_);
read_action_ = a;
read_callback_ = NULL;
read_buffer_.clear();
read_amount_ = 0;
break;
}
return;
}
/*
* XXX
* If we get an EOS from EventPoll, should we just terminate after that
* one read? How can we tell how much data is still available to be
* read? Will we get it all in one read? Eventually, one would expect
* to get a read with a length of 0, or an error, but will kevent even
* continue to fire off read events?
*/
if (len == 0) {
read_callback_->event(Event(Event::EOS, 0, read_buffer_));
Action *a = EventSystem::instance()->schedule(read_callback_);
read_action_ = a;
read_callback_ = NULL;
read_buffer_.clear();
read_amount_ = 0;
return;
}
read_buffer_.append(data, len);
read_action_ = read_schedule();
}
void
IOSystem::Handle::read_cancel(void)
{
ASSERT(read_action_ != NULL);
read_action_->cancel();
read_action_ = NULL;
if (read_callback_ != NULL) {
delete read_callback_;
read_callback_ = NULL;
}
}
Action *
IOSystem::Handle::read_schedule(void)
{
ASSERT(read_action_ == NULL);
if (!read_buffer_.empty() && read_buffer_.length() >= read_amount_) {
if (read_amount_ == 0)
read_amount_ = read_buffer_.length();
read_callback_->event(Event(Event::Done, 0, Buffer(read_buffer_, read_amount_)));
Action *a = EventSystem::instance()->schedule(read_callback_);
read_callback_ = NULL;
read_buffer_.skip(read_amount_);
read_amount_ = 0;
return (a);
}
EventCallback *cb = callback(this, &IOSystem::Handle::read_callback);
Action *a = EventSystem::instance()->poll(EventPoll::Readable, fd_, cb);
return (a);
}
void
IOSystem::Handle::write_callback(Event e)
{
write_action_->cancel();
write_action_ = NULL;
switch (e.type_) {
case Event::EOS:
case Event::Done:
break;
default:
HALT(log_) << "Unexpected event: " << e;
}
/* XXX This doesn't handle UDP nicely. Right? */
struct iovec iov[IOV_MAX];
size_t iovcnt = write_buffer_.fill_iovec(iov, IOV_MAX);
ssize_t len = ::writev(fd_, iov, iovcnt);
if (len == -1) {
switch (errno) {
case EAGAIN:
write_action_ = write_schedule();
break;
default:
write_callback_->event(Event(Event::Error, errno));
Action *a = EventSystem::instance()->schedule(write_callback_);
write_action_ = a;
write_callback_ = NULL;
break;
}
return;
}
write_buffer_.skip(len);
if (write_buffer_.empty()) {
write_callback_->event(Event(Event::Done, 0));
Action *a = EventSystem::instance()->schedule(write_callback_);
write_action_ = a;
write_callback_ = NULL;
return;
}
write_action_ = write_schedule();
}
void
IOSystem::Handle::write_cancel(void)
{
ASSERT(write_action_ != NULL);
write_action_->cancel();
write_action_ = NULL;
if (write_callback_ != NULL) {
delete write_callback_;
write_callback_ = NULL;
}
}
Action *
IOSystem::Handle::write_schedule(void)
{
ASSERT(write_action_ == NULL);
EventCallback *cb = callback(this, &IOSystem::Handle::write_callback);
Action *a = EventSystem::instance()->poll(EventPoll::Writable, fd_, cb);
return (a);
}
IOSystem::IOSystem(void)
: log_("/io/system"),
handle_map_()
{ }
IOSystem::~IOSystem()
{
ASSERT(handle_map_.empty());
}
void
IOSystem::attach(int fd, Channel *owner)
{
ASSERT(handle_map_.find(handle_key_t(fd, owner)) == handle_map_.end());
handle_map_[handle_key_t(fd, owner)] = new IOSystem::Handle(fd, owner);
}
void
IOSystem::detach(int fd, Channel *owner)
{
handle_map_t::iterator it;
IOSystem::Handle *h;
it = handle_map_.find(handle_key_t(fd, owner));
ASSERT(it != handle_map_.end());
h = it->second;
ASSERT(h != NULL);
ASSERT(h->owner_ == owner);
handle_map_.erase(it);
delete h;
}
Action *
IOSystem::close(int fd, Channel *owner, EventCallback *cb)
{
IOSystem::Handle *h;
h = handle_map_[handle_key_t(fd, owner)];
ASSERT(h != NULL);
ASSERT(h->close_callback_ == NULL);
ASSERT(h->close_action_ == NULL);
ASSERT(h->read_callback_ == NULL);
ASSERT(h->read_action_ == NULL);
ASSERT(h->write_callback_ == NULL);
ASSERT(h->write_action_ == NULL);
ASSERT(h->fd_ != -1);
h->close_callback_ = cb;
h->close_action_ = h->close_schedule();
return (cancellation(h, &IOSystem::Handle::close_cancel));
}
Action *
IOSystem::read(int fd, Channel *owner, size_t amount, EventCallback *cb)
{
IOSystem::Handle *h;
h = handle_map_[handle_key_t(fd, owner)];
ASSERT(h != NULL);
ASSERT(h->read_callback_ == NULL);
ASSERT(h->read_action_ == NULL);
h->read_amount_ = amount;
h->read_callback_ = cb;
h->read_action_ = h->read_schedule();
return (cancellation(h, &IOSystem::Handle::read_cancel));
}
Action *
IOSystem::write(int fd, Channel *owner, Buffer *buffer, EventCallback *cb)
{
IOSystem::Handle *h;
h = handle_map_[handle_key_t(fd, owner)];
ASSERT(h != NULL);
ASSERT(h->write_callback_ == NULL);
ASSERT(h->write_action_ == NULL);
ASSERT(h->write_buffer_.empty());
ASSERT(!buffer->empty());
h->write_buffer_.append(buffer);
buffer->clear();
h->write_callback_ = cb;
h->write_action_ = h->write_schedule();
return (cancellation(h, &IOSystem::Handle::write_cancel));
}
<commit_msg>Note my unhappiness with doing an extra copy of read data.<commit_after>#include <sys/errno.h>
#include <sys/uio.h>
#include <errno.h>
#include <limits.h>
#include <unistd.h>
#include <common/buffer.h>
#include <event/action.h>
#include <event/callback.h>
#include <event/event_system.h>
#include <io/io_system.h>
#define IO_READ_BUFFER_SIZE 65536
IOSystem::Handle::Handle(int fd, Channel *owner)
: log_("/io/system/handle"),
fd_(fd),
owner_(owner),
close_callback_(NULL),
close_action_(NULL),
read_amount_(0),
read_buffer_(),
read_callback_(NULL),
read_action_(NULL),
write_buffer_(),
write_callback_(NULL),
write_action_(NULL)
{ }
IOSystem::Handle::~Handle()
{
ASSERT(fd_ == -1);
ASSERT(close_action_ == NULL);
ASSERT(close_callback_ == NULL);
ASSERT(read_action_ == NULL);
ASSERT(read_callback_ == NULL);
ASSERT(write_action_ == NULL);
ASSERT(write_callback_ == NULL);
}
void
IOSystem::Handle::close_callback(void)
{
close_action_->cancel();
close_action_ = NULL;
ASSERT(fd_ != -1);
int rv = ::close(fd_);
if (rv == -1) {
switch (errno) {
case EAGAIN:
close_action_ = close_schedule();
break;
default:
close_callback_->event(Event(Event::Error, errno));
Action *a = EventSystem::instance()->schedule(close_callback_);
close_action_ = a;
close_callback_ = NULL;
break;
}
return;
}
fd_ = -1;
close_callback_->event(Event(Event::Done, 0));
Action *a = EventSystem::instance()->schedule(close_callback_);
close_action_ = a;
close_callback_ = NULL;
}
void
IOSystem::Handle::close_cancel(void)
{
ASSERT(close_action_ != NULL);
close_action_->cancel();
close_action_ = NULL;
if (close_callback_ != NULL) {
delete close_callback_;
close_callback_ = NULL;
}
}
Action *
IOSystem::Handle::close_schedule(void)
{
ASSERT(close_action_ == NULL);
Callback *cb = callback(this, &IOSystem::Handle::close_callback);
Action *a = EventSystem::instance()->schedule(cb);
return (a);
}
void
IOSystem::Handle::read_callback(Event e)
{
read_action_->cancel();
read_action_ = NULL;
switch (e.type_) {
case Event::EOS:
case Event::Done:
break;
default:
HALT(log_) << "Unexpected event: " << e;
}
size_t rlen;
if (read_amount_ == 0)
rlen = IO_READ_BUFFER_SIZE;
else {
rlen = read_amount_ - read_buffer_.length();
ASSERT(rlen != 0);
if (rlen > IO_READ_BUFFER_SIZE)
rlen = IO_READ_BUFFER_SIZE;
}
/* XXX Read into an iovec of BufferSegments? */
uint8_t data[IO_READ_BUFFER_SIZE];
ssize_t len = ::read(fd_, data, sizeof data);
if (len == -1) {
switch (errno) {
case EAGAIN:
read_action_ = read_schedule();
break;
default:
read_callback_->event(Event(Event::Error, errno, read_buffer_));
Action *a = EventSystem::instance()->schedule(read_callback_);
read_action_ = a;
read_callback_ = NULL;
read_buffer_.clear();
read_amount_ = 0;
break;
}
return;
}
/*
* XXX
* If we get an EOS from EventPoll, should we just terminate after that
* one read? How can we tell how much data is still available to be
* read? Will we get it all in one read? Eventually, one would expect
* to get a read with a length of 0, or an error, but will kevent even
* continue to fire off read events?
*/
if (len == 0) {
read_callback_->event(Event(Event::EOS, 0, read_buffer_));
Action *a = EventSystem::instance()->schedule(read_callback_);
read_action_ = a;
read_callback_ = NULL;
read_buffer_.clear();
read_amount_ = 0;
return;
}
read_buffer_.append(data, len);
read_action_ = read_schedule();
}
void
IOSystem::Handle::read_cancel(void)
{
ASSERT(read_action_ != NULL);
read_action_->cancel();
read_action_ = NULL;
if (read_callback_ != NULL) {
delete read_callback_;
read_callback_ = NULL;
}
}
Action *
IOSystem::Handle::read_schedule(void)
{
ASSERT(read_action_ == NULL);
if (!read_buffer_.empty() && read_buffer_.length() >= read_amount_) {
if (read_amount_ == 0)
read_amount_ = read_buffer_.length();
read_callback_->event(Event(Event::Done, 0, Buffer(read_buffer_, read_amount_)));
Action *a = EventSystem::instance()->schedule(read_callback_);
read_callback_ = NULL;
read_buffer_.skip(read_amount_);
read_amount_ = 0;
return (a);
}
EventCallback *cb = callback(this, &IOSystem::Handle::read_callback);
Action *a = EventSystem::instance()->poll(EventPoll::Readable, fd_, cb);
return (a);
}
void
IOSystem::Handle::write_callback(Event e)
{
write_action_->cancel();
write_action_ = NULL;
switch (e.type_) {
case Event::EOS:
case Event::Done:
break;
default:
HALT(log_) << "Unexpected event: " << e;
}
/* XXX This doesn't handle UDP nicely. Right? */
struct iovec iov[IOV_MAX];
size_t iovcnt = write_buffer_.fill_iovec(iov, IOV_MAX);
ssize_t len = ::writev(fd_, iov, iovcnt);
if (len == -1) {
switch (errno) {
case EAGAIN:
write_action_ = write_schedule();
break;
default:
write_callback_->event(Event(Event::Error, errno));
Action *a = EventSystem::instance()->schedule(write_callback_);
write_action_ = a;
write_callback_ = NULL;
break;
}
return;
}
write_buffer_.skip(len);
if (write_buffer_.empty()) {
write_callback_->event(Event(Event::Done, 0));
Action *a = EventSystem::instance()->schedule(write_callback_);
write_action_ = a;
write_callback_ = NULL;
return;
}
write_action_ = write_schedule();
}
void
IOSystem::Handle::write_cancel(void)
{
ASSERT(write_action_ != NULL);
write_action_->cancel();
write_action_ = NULL;
if (write_callback_ != NULL) {
delete write_callback_;
write_callback_ = NULL;
}
}
Action *
IOSystem::Handle::write_schedule(void)
{
ASSERT(write_action_ == NULL);
EventCallback *cb = callback(this, &IOSystem::Handle::write_callback);
Action *a = EventSystem::instance()->poll(EventPoll::Writable, fd_, cb);
return (a);
}
IOSystem::IOSystem(void)
: log_("/io/system"),
handle_map_()
{ }
IOSystem::~IOSystem()
{
ASSERT(handle_map_.empty());
}
void
IOSystem::attach(int fd, Channel *owner)
{
ASSERT(handle_map_.find(handle_key_t(fd, owner)) == handle_map_.end());
handle_map_[handle_key_t(fd, owner)] = new IOSystem::Handle(fd, owner);
}
void
IOSystem::detach(int fd, Channel *owner)
{
handle_map_t::iterator it;
IOSystem::Handle *h;
it = handle_map_.find(handle_key_t(fd, owner));
ASSERT(it != handle_map_.end());
h = it->second;
ASSERT(h != NULL);
ASSERT(h->owner_ == owner);
handle_map_.erase(it);
delete h;
}
Action *
IOSystem::close(int fd, Channel *owner, EventCallback *cb)
{
IOSystem::Handle *h;
h = handle_map_[handle_key_t(fd, owner)];
ASSERT(h != NULL);
ASSERT(h->close_callback_ == NULL);
ASSERT(h->close_action_ == NULL);
ASSERT(h->read_callback_ == NULL);
ASSERT(h->read_action_ == NULL);
ASSERT(h->write_callback_ == NULL);
ASSERT(h->write_action_ == NULL);
ASSERT(h->fd_ != -1);
h->close_callback_ = cb;
h->close_action_ = h->close_schedule();
return (cancellation(h, &IOSystem::Handle::close_cancel));
}
Action *
IOSystem::read(int fd, Channel *owner, size_t amount, EventCallback *cb)
{
IOSystem::Handle *h;
h = handle_map_[handle_key_t(fd, owner)];
ASSERT(h != NULL);
ASSERT(h->read_callback_ == NULL);
ASSERT(h->read_action_ == NULL);
h->read_amount_ = amount;
h->read_callback_ = cb;
h->read_action_ = h->read_schedule();
return (cancellation(h, &IOSystem::Handle::read_cancel));
}
Action *
IOSystem::write(int fd, Channel *owner, Buffer *buffer, EventCallback *cb)
{
IOSystem::Handle *h;
h = handle_map_[handle_key_t(fd, owner)];
ASSERT(h != NULL);
ASSERT(h->write_callback_ == NULL);
ASSERT(h->write_action_ == NULL);
ASSERT(h->write_buffer_.empty());
ASSERT(!buffer->empty());
h->write_buffer_.append(buffer);
buffer->clear();
h->write_callback_ = cb;
h->write_action_ = h->write_schedule();
return (cancellation(h, &IOSystem::Handle::write_cancel));
}
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.