text stringlengths 54 60.6k |
|---|
<commit_before>// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
// Simple test for a fuzzer: find interesting value of array index.
#include <assert.h>
#include <cstdint>
#include <cstring>
#include <cstddef>
#include <iostream>
static volatile int Sink;
const int kArraySize = 1234567;
int array[kArraySize];
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {
if (Size < 8) return 0;
size_t a = 0;
memcpy(&a, Data, 8);
Sink = array[a % (kArraySize + 1)];
return 0;
}
<commit_msg>[libFuzzer] Update Load test to work on 32 bits.<commit_after>// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
// Simple test for a fuzzer: find interesting value of array index.
#include <assert.h>
#include <cstdint>
#include <cstring>
#include <cstddef>
#include <iostream>
static volatile int Sink;
const int kArraySize = 1234567;
int array[kArraySize];
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {
if (Size < 8) return 0;
uint64_t a = 0;
memcpy(&a, Data, 8);
Sink = array[a % (kArraySize + 1)];
return 0;
}
<|endoftext|> |
<commit_before>#include "DeferredRenderer.hpp"
#include "scene/lights/Light.hpp"
#include "scene/Sky.hpp"
#include "system/System.hpp"
#include "graphics/GLUtilities.hpp"
DeferredRenderer::DeferredRenderer(const glm::vec2 & resolution, ShadowMode mode, bool ssao) :
_applySSAO(ssao), _shadowMode(mode) {
const uint renderWidth = uint(resolution[0]);
const uint renderHeight = uint(resolution[1]);
// G-buffer setup.
const Descriptor albedoDesc = {Layout::RGBA16F, Filter::NEAREST_NEAREST, Wrap::CLAMP};
const Descriptor normalDesc = {Layout::RGB16F, Filter::NEAREST_NEAREST, Wrap::CLAMP};
const Descriptor effectsDesc = {Layout::RGB8, Filter::NEAREST_NEAREST, Wrap::CLAMP};
const Descriptor depthDesc = {Layout::DEPTH_COMPONENT32F, Filter::NEAREST_NEAREST, Wrap::CLAMP};
const Descriptor desc = {Layout::RGB16F, Filter::LINEAR_LINEAR, Wrap::CLAMP};
const std::vector<Descriptor> descs = {albedoDesc, normalDesc, effectsDesc, depthDesc};
_gbuffer = std::unique_ptr<Framebuffer>(new Framebuffer(renderWidth, renderHeight, descs, false, "G-buffer"));
_ssaoPass = std::unique_ptr<SSAO>(new SSAO(renderWidth, renderHeight, 2, 0.5f));
_lightBuffer = std::unique_ptr<Framebuffer>(new Framebuffer(renderWidth, renderHeight, desc, false, "Deferred lighting"));
_preferredFormat.push_back(desc);
_needsDepth = false;
_skyboxProgram = Resources::manager().getProgram("skybox_gbuffer", "skybox_infinity", "skybox_gbuffer");
_bgProgram = Resources::manager().getProgram("background_gbuffer", "background_infinity", "background_gbuffer");
_atmoProgram = Resources::manager().getProgram("atmosphere_gbuffer", "background_infinity", "atmosphere_gbuffer");
_parallaxProgram = Resources::manager().getProgram("object_parallax_gbuffer");
_objectProgram = Resources::manager().getProgram("object_gbuffer");
_emissiveProgram = Resources::manager().getProgram("object_emissive_gbuffer");
// Lighting passes.
_ambientScreen = std::unique_ptr<AmbientQuad>(new AmbientQuad(_gbuffer->texture(0), _gbuffer->texture(1),
_gbuffer->texture(2), _gbuffer->depthBuffer(), _ssaoPass->texture()));
_lightRenderer = std::unique_ptr<DeferredLight>(new DeferredLight(_gbuffer->texture(0), _gbuffer->texture(1), _gbuffer->depthBuffer(), _gbuffer->texture(2)));
checkGLError();
}
void DeferredRenderer::setScene(const std::shared_ptr<Scene> & scene) {
// Do not accept a null scene.
if(!scene) {
return;
}
_scene = scene;
_culler.reset(new Culler(_scene->objects));
checkGLError();
}
void DeferredRenderer::renderScene(const glm::mat4 & view, const glm::mat4 & proj, const glm::vec3 & pos) {
GLUtilities::setDepthState(true, TestFunction::LESS, true);
// Bind the full scene framebuffer.
_gbuffer->bind();
// Set screen viewport
_gbuffer->setViewport();
// Clear the depth buffer (we know we will draw everywhere, no need to clear color).
GLUtilities::clearDepth(1.0f);
// Request list of visible objects from culler.
const auto & visibles = _culler->cullAndSort(view, proj, pos);
// Scene objects.
for(const long & objectId : visibles) {
// Once we get a -1, there is no other object to render.
if(objectId == -1){
break;
}
const Object & object = _scene->objects[objectId];
// Combine the three matrices.
const glm::mat4 MV = view * object.model();
const glm::mat4 MVP = proj * MV;
// Compute the normal matrix
const glm::mat3 normalMatrix = glm::transpose(glm::inverse(glm::mat3(MV)));
// Select the program (and shaders).
switch(object.type()) {
case Object::Parallax:
_parallaxProgram->use();
// Upload the MVP matrix.
_parallaxProgram->uniform("mvp", MVP);
// Upload the projection matrix.
_parallaxProgram->uniform("p", proj);
// Upload the MV matrix.
_parallaxProgram->uniform("mv", MV);
// Upload the normal matrix.
_parallaxProgram->uniform("normalMatrix", normalMatrix);
break;
case Object::Regular:
_objectProgram->use();
// Upload the MVP matrix.
_objectProgram->uniform("mvp", MVP);
// Upload the normal matrix.
_objectProgram->uniform("normalMatrix", normalMatrix);
_objectProgram->uniform("hasUV", object.useTexCoords());
break;
case Object::Emissive:
_emissiveProgram->use();
// Upload the MVP matrix.
_emissiveProgram->uniform("mvp", MVP);
// Are UV available. Note: we might want to decouple UV use from their existence.
_emissiveProgram->uniform("hasUV", object.useTexCoords());
break;
default:
break;
}
// Backface culling state.
if(object.twoSided()) {
GLUtilities::setCullState(false);
}
// Bind the textures.
GLUtilities::bindTextures(object.textures());
GLUtilities::drawMesh(*object.mesh());
// Restore state.
GLUtilities::setCullState(true);
}
renderBackground(view, proj, pos);
GLUtilities::setDepthState(false);
}
void DeferredRenderer::renderBackground(const glm::mat4 & view, const glm::mat4 & proj, const glm::vec3 & pos){
// Background.
// No need to write the skybox depth to the framebuffer.
// Accept a depth of 1.0 (far plane).
GLUtilities::setDepthState(true, TestFunction::LEQUAL, false);
const Object * background = _scene->background.get();
const Scene::Background mode = _scene->backgroundMode;
if(mode == Scene::Background::SKYBOX) {
// Skybox.
const glm::mat4 backgroundMVP = proj * view * background->model();
// Draw background.
_skyboxProgram->use();
// Upload the MVP matrix.
_skyboxProgram->uniform("mvp", backgroundMVP);
GLUtilities::bindTextures(background->textures());
GLUtilities::drawMesh(*background->mesh());
} else if(mode == Scene::Background::ATMOSPHERE) {
// Atmosphere screen quad.
_atmoProgram->use();
// Revert the model to clip matrix, removing the translation part.
const glm::mat4 worldToClipNoT = proj * glm::mat4(glm::mat3(view));
const glm::mat4 clipToWorldNoT = glm::inverse(worldToClipNoT);
const glm::vec3 & sunDir = dynamic_cast<const Sky *>(background)->direction();
// Send and draw.
_atmoProgram->uniform("clipToWorld", clipToWorldNoT);
_atmoProgram->uniform("viewPos", pos);
_atmoProgram->uniform("lightDirection", sunDir);
GLUtilities::bindTextures(background->textures());
GLUtilities::drawMesh(*background->mesh());
} else {
// Background color or 2D image.
_bgProgram->use();
if(mode == Scene::Background::IMAGE) {
_bgProgram->uniform("useTexture", 1);
GLUtilities::bindTextures(background->textures());
} else {
_bgProgram->uniform("useTexture", 0);
_bgProgram->uniform("bgColor", _scene->backgroundColor);
}
GLUtilities::drawMesh(*background->mesh());
}
GLUtilities::setDepthState(true, TestFunction::LESS, true);
}
void DeferredRenderer::draw(const Camera & camera, Framebuffer & framebuffer, size_t layer) {
const glm::mat4 & view = camera.view();
const glm::mat4 & proj = camera.projection();
const glm::vec3 & pos = camera.position();
// --- Scene pass -------
renderScene(view, proj, pos);
// --- SSAO pass
if(_applySSAO) {
_ssaoPass->process(proj, _gbuffer->depthBuffer(), _gbuffer->texture(int(TextureType::Normal)));
} else {
_ssaoPass->clear();
}
// --- Gbuffer composition pass
_lightRenderer->updateCameraInfos(view, proj);
_lightRenderer->updateShadowMapInfos(_shadowMode, 0.002f);
_lightBuffer->bind();
_lightBuffer->setViewport();
_ambientScreen->draw(view, proj, _scene->environment);
GLUtilities::setBlendState(true, BlendEquation::ADD, BlendFunction::ONE, BlendFunction::ONE);
for(auto & light : _scene->lights) {
light->draw(*_lightRenderer);
}
GLUtilities::setBlendState(false);
// Copy to the final framebuffer.
GLUtilities::blit(*_lightBuffer, framebuffer, 0, layer, Filter::NEAREST);
}
void DeferredRenderer::resize(unsigned int width, unsigned int height) {
// Resize the framebuffers.
_gbuffer->resize(glm::vec2(width, height));
_lightBuffer->resize(glm::vec2(width, height));
_ssaoPass->resize(width, height);
checkGLError();
}
void DeferredRenderer::interface(){
ImGui::Checkbox("Freeze culling", &_freezeFrustum);
ImGui::Combo("Shadow technique", reinterpret_cast<int*>(&_shadowMode), "None\0Basic\0Variance\0\0");
ImGui::Checkbox("SSAO", &_applySSAO);
if(_applySSAO) {
ImGui::SameLine();
ImGui::Combo("Blur quality", reinterpret_cast<int*>(&_ssaoPass->quality()), "Low\0Medium\0High\0\0");
ImGui::InputFloat("Radius", &_ssaoPass->radius(), 0.5f);
}
}
const Framebuffer * DeferredRenderer::sceneDepth() const {
return _gbuffer.get();
}
const Texture * DeferredRenderer::sceneNormal() const {
return _gbuffer->texture(1);
}
<commit_msg>DeferredRenderer: add missing culler interface.<commit_after>#include "DeferredRenderer.hpp"
#include "scene/lights/Light.hpp"
#include "scene/Sky.hpp"
#include "system/System.hpp"
#include "graphics/GLUtilities.hpp"
DeferredRenderer::DeferredRenderer(const glm::vec2 & resolution, ShadowMode mode, bool ssao) :
_applySSAO(ssao), _shadowMode(mode) {
const uint renderWidth = uint(resolution[0]);
const uint renderHeight = uint(resolution[1]);
// G-buffer setup.
const Descriptor albedoDesc = {Layout::RGBA16F, Filter::NEAREST_NEAREST, Wrap::CLAMP};
const Descriptor normalDesc = {Layout::RGB16F, Filter::NEAREST_NEAREST, Wrap::CLAMP};
const Descriptor effectsDesc = {Layout::RGB8, Filter::NEAREST_NEAREST, Wrap::CLAMP};
const Descriptor depthDesc = {Layout::DEPTH_COMPONENT32F, Filter::NEAREST_NEAREST, Wrap::CLAMP};
const Descriptor desc = {Layout::RGB16F, Filter::LINEAR_LINEAR, Wrap::CLAMP};
const std::vector<Descriptor> descs = {albedoDesc, normalDesc, effectsDesc, depthDesc};
_gbuffer = std::unique_ptr<Framebuffer>(new Framebuffer(renderWidth, renderHeight, descs, false, "G-buffer"));
_ssaoPass = std::unique_ptr<SSAO>(new SSAO(renderWidth, renderHeight, 2, 0.5f));
_lightBuffer = std::unique_ptr<Framebuffer>(new Framebuffer(renderWidth, renderHeight, desc, false, "Deferred lighting"));
_preferredFormat.push_back(desc);
_needsDepth = false;
_skyboxProgram = Resources::manager().getProgram("skybox_gbuffer", "skybox_infinity", "skybox_gbuffer");
_bgProgram = Resources::manager().getProgram("background_gbuffer", "background_infinity", "background_gbuffer");
_atmoProgram = Resources::manager().getProgram("atmosphere_gbuffer", "background_infinity", "atmosphere_gbuffer");
_parallaxProgram = Resources::manager().getProgram("object_parallax_gbuffer");
_objectProgram = Resources::manager().getProgram("object_gbuffer");
_emissiveProgram = Resources::manager().getProgram("object_emissive_gbuffer");
// Lighting passes.
_ambientScreen = std::unique_ptr<AmbientQuad>(new AmbientQuad(_gbuffer->texture(0), _gbuffer->texture(1),
_gbuffer->texture(2), _gbuffer->depthBuffer(), _ssaoPass->texture()));
_lightRenderer = std::unique_ptr<DeferredLight>(new DeferredLight(_gbuffer->texture(0), _gbuffer->texture(1), _gbuffer->depthBuffer(), _gbuffer->texture(2)));
checkGLError();
}
void DeferredRenderer::setScene(const std::shared_ptr<Scene> & scene) {
// Do not accept a null scene.
if(!scene) {
return;
}
_scene = scene;
_culler.reset(new Culler(_scene->objects));
checkGLError();
}
void DeferredRenderer::renderScene(const glm::mat4 & view, const glm::mat4 & proj, const glm::vec3 & pos) {
GLUtilities::setDepthState(true, TestFunction::LESS, true);
// Bind the full scene framebuffer.
_gbuffer->bind();
// Set screen viewport
_gbuffer->setViewport();
// Clear the depth buffer (we know we will draw everywhere, no need to clear color).
GLUtilities::clearDepth(1.0f);
// Request list of visible objects from culler.
const auto & visibles = _culler->cullAndSort(view, proj, pos);
// Scene objects.
for(const long & objectId : visibles) {
// Once we get a -1, there is no other object to render.
if(objectId == -1){
break;
}
const Object & object = _scene->objects[objectId];
// Combine the three matrices.
const glm::mat4 MV = view * object.model();
const glm::mat4 MVP = proj * MV;
// Compute the normal matrix
const glm::mat3 normalMatrix = glm::transpose(glm::inverse(glm::mat3(MV)));
// Select the program (and shaders).
switch(object.type()) {
case Object::Parallax:
_parallaxProgram->use();
// Upload the MVP matrix.
_parallaxProgram->uniform("mvp", MVP);
// Upload the projection matrix.
_parallaxProgram->uniform("p", proj);
// Upload the MV matrix.
_parallaxProgram->uniform("mv", MV);
// Upload the normal matrix.
_parallaxProgram->uniform("normalMatrix", normalMatrix);
break;
case Object::Regular:
_objectProgram->use();
// Upload the MVP matrix.
_objectProgram->uniform("mvp", MVP);
// Upload the normal matrix.
_objectProgram->uniform("normalMatrix", normalMatrix);
_objectProgram->uniform("hasUV", object.useTexCoords());
break;
case Object::Emissive:
_emissiveProgram->use();
// Upload the MVP matrix.
_emissiveProgram->uniform("mvp", MVP);
// Are UV available. Note: we might want to decouple UV use from their existence.
_emissiveProgram->uniform("hasUV", object.useTexCoords());
break;
default:
break;
}
// Backface culling state.
if(object.twoSided()) {
GLUtilities::setCullState(false);
}
// Bind the textures.
GLUtilities::bindTextures(object.textures());
GLUtilities::drawMesh(*object.mesh());
// Restore state.
GLUtilities::setCullState(true);
}
renderBackground(view, proj, pos);
GLUtilities::setDepthState(false);
}
void DeferredRenderer::renderBackground(const glm::mat4 & view, const glm::mat4 & proj, const glm::vec3 & pos){
// Background.
// No need to write the skybox depth to the framebuffer.
// Accept a depth of 1.0 (far plane).
GLUtilities::setDepthState(true, TestFunction::LEQUAL, false);
const Object * background = _scene->background.get();
const Scene::Background mode = _scene->backgroundMode;
if(mode == Scene::Background::SKYBOX) {
// Skybox.
const glm::mat4 backgroundMVP = proj * view * background->model();
// Draw background.
_skyboxProgram->use();
// Upload the MVP matrix.
_skyboxProgram->uniform("mvp", backgroundMVP);
GLUtilities::bindTextures(background->textures());
GLUtilities::drawMesh(*background->mesh());
} else if(mode == Scene::Background::ATMOSPHERE) {
// Atmosphere screen quad.
_atmoProgram->use();
// Revert the model to clip matrix, removing the translation part.
const glm::mat4 worldToClipNoT = proj * glm::mat4(glm::mat3(view));
const glm::mat4 clipToWorldNoT = glm::inverse(worldToClipNoT);
const glm::vec3 & sunDir = dynamic_cast<const Sky *>(background)->direction();
// Send and draw.
_atmoProgram->uniform("clipToWorld", clipToWorldNoT);
_atmoProgram->uniform("viewPos", pos);
_atmoProgram->uniform("lightDirection", sunDir);
GLUtilities::bindTextures(background->textures());
GLUtilities::drawMesh(*background->mesh());
} else {
// Background color or 2D image.
_bgProgram->use();
if(mode == Scene::Background::IMAGE) {
_bgProgram->uniform("useTexture", 1);
GLUtilities::bindTextures(background->textures());
} else {
_bgProgram->uniform("useTexture", 0);
_bgProgram->uniform("bgColor", _scene->backgroundColor);
}
GLUtilities::drawMesh(*background->mesh());
}
GLUtilities::setDepthState(true, TestFunction::LESS, true);
}
void DeferredRenderer::draw(const Camera & camera, Framebuffer & framebuffer, size_t layer) {
const glm::mat4 & view = camera.view();
const glm::mat4 & proj = camera.projection();
const glm::vec3 & pos = camera.position();
// --- Scene pass -------
renderScene(view, proj, pos);
// --- SSAO pass
if(_applySSAO) {
_ssaoPass->process(proj, _gbuffer->depthBuffer(), _gbuffer->texture(int(TextureType::Normal)));
} else {
_ssaoPass->clear();
}
// --- Gbuffer composition pass
_lightRenderer->updateCameraInfos(view, proj);
_lightRenderer->updateShadowMapInfos(_shadowMode, 0.002f);
_lightBuffer->bind();
_lightBuffer->setViewport();
_ambientScreen->draw(view, proj, _scene->environment);
GLUtilities::setBlendState(true, BlendEquation::ADD, BlendFunction::ONE, BlendFunction::ONE);
for(auto & light : _scene->lights) {
light->draw(*_lightRenderer);
}
GLUtilities::setBlendState(false);
// Copy to the final framebuffer.
GLUtilities::blit(*_lightBuffer, framebuffer, 0, layer, Filter::NEAREST);
}
void DeferredRenderer::resize(unsigned int width, unsigned int height) {
// Resize the framebuffers.
_gbuffer->resize(glm::vec2(width, height));
_lightBuffer->resize(glm::vec2(width, height));
_ssaoPass->resize(width, height);
checkGLError();
}
void DeferredRenderer::interface(){
ImGui::Combo("Shadow technique", reinterpret_cast<int*>(&_shadowMode), "None\0Basic\0Variance\0\0");
ImGui::Checkbox("SSAO", &_applySSAO);
if(_applySSAO) {
ImGui::SameLine();
ImGui::Combo("Blur quality", reinterpret_cast<int*>(&_ssaoPass->quality()), "Low\0Medium\0High\0\0");
ImGui::InputFloat("Radius", &_ssaoPass->radius(), 0.5f);
}
if(_culler){
_culler->interface();
}
}
const Framebuffer * DeferredRenderer::sceneDepth() const {
return _gbuffer.get();
}
const Texture * DeferredRenderer::sceneNormal() const {
return _gbuffer->texture(1);
}
<|endoftext|> |
<commit_before>//===--- MemoryBuffer.cpp - Memory Buffer implementation ------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the MemoryBuffer interface.
//
//===----------------------------------------------------------------------===//
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/ADT/OwningPtr.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/System/Path.h"
#include "llvm/System/Process.h"
#include "llvm/System/Program.h"
#include <cassert>
#include <cstdio>
#include <cstring>
#include <cerrno>
#include <sys/types.h>
#include <sys/stat.h>
#if !defined(_MSC_VER) && !defined(__MINGW32__)
#include <unistd.h>
#include <sys/uio.h>
#else
#include <io.h>
#endif
#include <fcntl.h>
using namespace llvm;
//===----------------------------------------------------------------------===//
// MemoryBuffer implementation itself.
//===----------------------------------------------------------------------===//
MemoryBuffer::~MemoryBuffer() {
if (MustDeleteBuffer)
free((void*)BufferStart);
}
/// initCopyOf - Initialize this source buffer with a copy of the specified
/// memory range. We make the copy so that we can null terminate it
/// successfully.
void MemoryBuffer::initCopyOf(const char *BufStart, const char *BufEnd) {
size_t Size = BufEnd-BufStart;
BufferStart = (char *)malloc((Size+1) * sizeof(char));
BufferEnd = BufferStart+Size;
memcpy(const_cast<char*>(BufferStart), BufStart, Size);
*const_cast<char*>(BufferEnd) = 0; // Null terminate buffer.
MustDeleteBuffer = true;
}
/// init - Initialize this MemoryBuffer as a reference to externally allocated
/// memory, memory that we know is already null terminated.
void MemoryBuffer::init(const char *BufStart, const char *BufEnd) {
assert(BufEnd[0] == 0 && "Buffer is not null terminated!");
BufferStart = BufStart;
BufferEnd = BufEnd;
MustDeleteBuffer = false;
}
//===----------------------------------------------------------------------===//
// MemoryBufferMem implementation.
//===----------------------------------------------------------------------===//
namespace {
class MemoryBufferMem : public MemoryBuffer {
std::string FileID;
public:
MemoryBufferMem(const char *Start, const char *End, StringRef FID,
bool Copy = false)
: FileID(FID) {
if (!Copy)
init(Start, End);
else
initCopyOf(Start, End);
}
virtual const char *getBufferIdentifier() const {
return FileID.c_str();
}
};
}
/// getMemBuffer - Open the specified memory range as a MemoryBuffer. Note
/// that EndPtr[0] must be a null byte and be accessible!
MemoryBuffer *MemoryBuffer::getMemBuffer(const char *StartPtr,
const char *EndPtr,
const char *BufferName) {
return new MemoryBufferMem(StartPtr, EndPtr, BufferName);
}
/// getMemBufferCopy - Open the specified memory range as a MemoryBuffer,
/// copying the contents and taking ownership of it. This has no requirements
/// on EndPtr[0].
MemoryBuffer *MemoryBuffer::getMemBufferCopy(const char *StartPtr,
const char *EndPtr,
const char *BufferName) {
return new MemoryBufferMem(StartPtr, EndPtr, BufferName, true);
}
/// getNewUninitMemBuffer - Allocate a new MemoryBuffer of the specified size
/// that is completely initialized to zeros. Note that the caller should
/// initialize the memory allocated by this method. The memory is owned by
/// the MemoryBuffer object.
MemoryBuffer *MemoryBuffer::getNewUninitMemBuffer(size_t Size,
StringRef BufferName) {
char *Buf = (char *)malloc((Size+1) * sizeof(char));
if (!Buf) return 0;
Buf[Size] = 0;
MemoryBufferMem *SB = new MemoryBufferMem(Buf, Buf+Size, BufferName);
// The memory for this buffer is owned by the MemoryBuffer.
SB->MustDeleteBuffer = true;
return SB;
}
/// getNewMemBuffer - Allocate a new MemoryBuffer of the specified size that
/// is completely initialized to zeros. Note that the caller should
/// initialize the memory allocated by this method. The memory is owned by
/// the MemoryBuffer object.
MemoryBuffer *MemoryBuffer::getNewMemBuffer(size_t Size,
const char *BufferName) {
MemoryBuffer *SB = getNewUninitMemBuffer(Size, BufferName);
if (!SB) return 0;
memset(const_cast<char*>(SB->getBufferStart()), 0, Size+1);
return SB;
}
/// getFileOrSTDIN - Open the specified file as a MemoryBuffer, or open stdin
/// if the Filename is "-". If an error occurs, this returns null and fills
/// in *ErrStr with a reason. If stdin is empty, this API (unlike getSTDIN)
/// returns an empty buffer.
MemoryBuffer *MemoryBuffer::getFileOrSTDIN(StringRef Filename,
std::string *ErrStr,
int64_t FileSize) {
if (Filename == "-")
return getSTDIN();
return getFile(Filename, ErrStr, FileSize);
}
//===----------------------------------------------------------------------===//
// MemoryBuffer::getFile implementation.
//===----------------------------------------------------------------------===//
namespace {
/// MemoryBufferMMapFile - This represents a file that was mapped in with the
/// sys::Path::MapInFilePages method. When destroyed, it calls the
/// sys::Path::UnMapFilePages method.
class MemoryBufferMMapFile : public MemoryBuffer {
std::string Filename;
public:
MemoryBufferMMapFile(StringRef filename, const char *Pages, uint64_t Size)
: Filename(filename) {
init(Pages, Pages+Size);
}
virtual const char *getBufferIdentifier() const {
return Filename.c_str();
}
~MemoryBufferMMapFile() {
sys::Path::UnMapFilePages(getBufferStart(), getBufferSize());
}
};
}
MemoryBuffer *MemoryBuffer::getFile(StringRef Filename, std::string *ErrStr,
int64_t FileSize) {
int OpenFlags = 0;
#ifdef O_BINARY
OpenFlags |= O_BINARY; // Open input file in binary mode on win32.
#endif
int FD = ::open(Filename.str().c_str(), O_RDONLY|OpenFlags);
if (FD == -1) {
if (ErrStr) *ErrStr = strerror(errno);
return 0;
}
// If we don't know the file size, use fstat to find out. fstat on an open
// file descriptor is cheaper than stat on a random path.
if (FileSize == -1) {
struct stat FileInfo;
// TODO: This should use fstat64 when available.
if (fstat(FD, &FileInfo) == -1) {
if (ErrStr) *ErrStr = strerror(errno);
::close(FD);
return 0;
}
FileSize = FileInfo.st_size;
}
// If the file is large, try to use mmap to read it in. We don't use mmap
// for small files, because this can severely fragment our address space. Also
// don't try to map files that are exactly a multiple of the system page size,
// as the file would not have the required null terminator.
//
// FIXME: Can we just mmap an extra page in the latter case?
if (FileSize >= 4096*4 &&
(FileSize & (sys::Process::GetPageSize()-1)) != 0) {
if (const char *Pages = sys::Path::MapInFilePages(FD, FileSize)) {
// Close the file descriptor, now that the whole file is in memory.
::close(FD);
return new MemoryBufferMMapFile(Filename, Pages, FileSize);
}
}
MemoryBuffer *Buf = MemoryBuffer::getNewUninitMemBuffer(FileSize, Filename);
if (!Buf) {
// Failed to create a buffer.
if (ErrStr) *ErrStr = "could not allocate buffer";
::close(FD);
return 0;
}
OwningPtr<MemoryBuffer> SB(Buf);
char *BufPtr = const_cast<char*>(SB->getBufferStart());
size_t BytesLeft = FileSize;
while (BytesLeft) {
ssize_t NumRead = ::read(FD, BufPtr, BytesLeft);
if (NumRead > 0) {
BytesLeft -= NumRead;
BufPtr += NumRead;
} else if (NumRead == -1 && errno == EINTR) {
// try again
} else {
// error reading.
if (ErrStr) *ErrStr = strerror(errno);
close(FD);
return 0;
}
}
close(FD);
return SB.take();
}
//===----------------------------------------------------------------------===//
// MemoryBuffer::getSTDIN implementation.
//===----------------------------------------------------------------------===//
namespace {
class STDINBufferFile : public MemoryBuffer {
public:
virtual const char *getBufferIdentifier() const {
return "<stdin>";
}
};
}
MemoryBuffer *MemoryBuffer::getSTDIN() {
char Buffer[4096*4];
std::vector<char> FileData;
// Read in all of the data from stdin, we cannot mmap stdin.
//
// FIXME: That isn't necessarily true, we should try to mmap stdin and
// fallback if it fails.
sys::Program::ChangeStdinToBinary();
size_t ReadBytes;
do {
ReadBytes = fread(Buffer, sizeof(char), sizeof(Buffer), stdin);
FileData.insert(FileData.end(), Buffer, Buffer+ReadBytes);
} while (ReadBytes == sizeof(Buffer));
FileData.push_back(0); // &FileData[Size] is invalid. So is &*FileData.end().
size_t Size = FileData.size();
MemoryBuffer *B = new STDINBufferFile();
B->initCopyOf(&FileData[0], &FileData[Size-1]);
return B;
}
<commit_msg>sizeof(char) is always 1.<commit_after>//===--- MemoryBuffer.cpp - Memory Buffer implementation ------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the MemoryBuffer interface.
//
//===----------------------------------------------------------------------===//
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/ADT/OwningPtr.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/System/Path.h"
#include "llvm/System/Process.h"
#include "llvm/System/Program.h"
#include <cassert>
#include <cstdio>
#include <cstring>
#include <cerrno>
#include <sys/types.h>
#include <sys/stat.h>
#if !defined(_MSC_VER) && !defined(__MINGW32__)
#include <unistd.h>
#include <sys/uio.h>
#else
#include <io.h>
#endif
#include <fcntl.h>
using namespace llvm;
//===----------------------------------------------------------------------===//
// MemoryBuffer implementation itself.
//===----------------------------------------------------------------------===//
MemoryBuffer::~MemoryBuffer() {
if (MustDeleteBuffer)
free((void*)BufferStart);
}
/// initCopyOf - Initialize this source buffer with a copy of the specified
/// memory range. We make the copy so that we can null terminate it
/// successfully.
void MemoryBuffer::initCopyOf(const char *BufStart, const char *BufEnd) {
size_t Size = BufEnd-BufStart;
BufferStart = (char *)malloc(Size+1);
BufferEnd = BufferStart+Size;
memcpy(const_cast<char*>(BufferStart), BufStart, Size);
*const_cast<char*>(BufferEnd) = 0; // Null terminate buffer.
MustDeleteBuffer = true;
}
/// init - Initialize this MemoryBuffer as a reference to externally allocated
/// memory, memory that we know is already null terminated.
void MemoryBuffer::init(const char *BufStart, const char *BufEnd) {
assert(BufEnd[0] == 0 && "Buffer is not null terminated!");
BufferStart = BufStart;
BufferEnd = BufEnd;
MustDeleteBuffer = false;
}
//===----------------------------------------------------------------------===//
// MemoryBufferMem implementation.
//===----------------------------------------------------------------------===//
namespace {
class MemoryBufferMem : public MemoryBuffer {
std::string FileID;
public:
MemoryBufferMem(const char *Start, const char *End, StringRef FID,
bool Copy = false)
: FileID(FID) {
if (!Copy)
init(Start, End);
else
initCopyOf(Start, End);
}
virtual const char *getBufferIdentifier() const {
return FileID.c_str();
}
};
}
/// getMemBuffer - Open the specified memory range as a MemoryBuffer. Note
/// that EndPtr[0] must be a null byte and be accessible!
MemoryBuffer *MemoryBuffer::getMemBuffer(const char *StartPtr,
const char *EndPtr,
const char *BufferName) {
return new MemoryBufferMem(StartPtr, EndPtr, BufferName);
}
/// getMemBufferCopy - Open the specified memory range as a MemoryBuffer,
/// copying the contents and taking ownership of it. This has no requirements
/// on EndPtr[0].
MemoryBuffer *MemoryBuffer::getMemBufferCopy(const char *StartPtr,
const char *EndPtr,
const char *BufferName) {
return new MemoryBufferMem(StartPtr, EndPtr, BufferName, true);
}
/// getNewUninitMemBuffer - Allocate a new MemoryBuffer of the specified size
/// that is completely initialized to zeros. Note that the caller should
/// initialize the memory allocated by this method. The memory is owned by
/// the MemoryBuffer object.
MemoryBuffer *MemoryBuffer::getNewUninitMemBuffer(size_t Size,
StringRef BufferName) {
char *Buf = (char *)malloc(Size+1);
if (!Buf) return 0;
Buf[Size] = 0;
MemoryBufferMem *SB = new MemoryBufferMem(Buf, Buf+Size, BufferName);
// The memory for this buffer is owned by the MemoryBuffer.
SB->MustDeleteBuffer = true;
return SB;
}
/// getNewMemBuffer - Allocate a new MemoryBuffer of the specified size that
/// is completely initialized to zeros. Note that the caller should
/// initialize the memory allocated by this method. The memory is owned by
/// the MemoryBuffer object.
MemoryBuffer *MemoryBuffer::getNewMemBuffer(size_t Size,
const char *BufferName) {
MemoryBuffer *SB = getNewUninitMemBuffer(Size, BufferName);
if (!SB) return 0;
memset(const_cast<char*>(SB->getBufferStart()), 0, Size+1);
return SB;
}
/// getFileOrSTDIN - Open the specified file as a MemoryBuffer, or open stdin
/// if the Filename is "-". If an error occurs, this returns null and fills
/// in *ErrStr with a reason. If stdin is empty, this API (unlike getSTDIN)
/// returns an empty buffer.
MemoryBuffer *MemoryBuffer::getFileOrSTDIN(StringRef Filename,
std::string *ErrStr,
int64_t FileSize) {
if (Filename == "-")
return getSTDIN();
return getFile(Filename, ErrStr, FileSize);
}
//===----------------------------------------------------------------------===//
// MemoryBuffer::getFile implementation.
//===----------------------------------------------------------------------===//
namespace {
/// MemoryBufferMMapFile - This represents a file that was mapped in with the
/// sys::Path::MapInFilePages method. When destroyed, it calls the
/// sys::Path::UnMapFilePages method.
class MemoryBufferMMapFile : public MemoryBuffer {
std::string Filename;
public:
MemoryBufferMMapFile(StringRef filename, const char *Pages, uint64_t Size)
: Filename(filename) {
init(Pages, Pages+Size);
}
virtual const char *getBufferIdentifier() const {
return Filename.c_str();
}
~MemoryBufferMMapFile() {
sys::Path::UnMapFilePages(getBufferStart(), getBufferSize());
}
};
}
MemoryBuffer *MemoryBuffer::getFile(StringRef Filename, std::string *ErrStr,
int64_t FileSize) {
int OpenFlags = 0;
#ifdef O_BINARY
OpenFlags |= O_BINARY; // Open input file in binary mode on win32.
#endif
int FD = ::open(Filename.str().c_str(), O_RDONLY|OpenFlags);
if (FD == -1) {
if (ErrStr) *ErrStr = strerror(errno);
return 0;
}
// If we don't know the file size, use fstat to find out. fstat on an open
// file descriptor is cheaper than stat on a random path.
if (FileSize == -1) {
struct stat FileInfo;
// TODO: This should use fstat64 when available.
if (fstat(FD, &FileInfo) == -1) {
if (ErrStr) *ErrStr = strerror(errno);
::close(FD);
return 0;
}
FileSize = FileInfo.st_size;
}
// If the file is large, try to use mmap to read it in. We don't use mmap
// for small files, because this can severely fragment our address space. Also
// don't try to map files that are exactly a multiple of the system page size,
// as the file would not have the required null terminator.
//
// FIXME: Can we just mmap an extra page in the latter case?
if (FileSize >= 4096*4 &&
(FileSize & (sys::Process::GetPageSize()-1)) != 0) {
if (const char *Pages = sys::Path::MapInFilePages(FD, FileSize)) {
// Close the file descriptor, now that the whole file is in memory.
::close(FD);
return new MemoryBufferMMapFile(Filename, Pages, FileSize);
}
}
MemoryBuffer *Buf = MemoryBuffer::getNewUninitMemBuffer(FileSize, Filename);
if (!Buf) {
// Failed to create a buffer.
if (ErrStr) *ErrStr = "could not allocate buffer";
::close(FD);
return 0;
}
OwningPtr<MemoryBuffer> SB(Buf);
char *BufPtr = const_cast<char*>(SB->getBufferStart());
size_t BytesLeft = FileSize;
while (BytesLeft) {
ssize_t NumRead = ::read(FD, BufPtr, BytesLeft);
if (NumRead > 0) {
BytesLeft -= NumRead;
BufPtr += NumRead;
} else if (NumRead == -1 && errno == EINTR) {
// try again
} else {
// error reading.
if (ErrStr) *ErrStr = strerror(errno);
close(FD);
return 0;
}
}
close(FD);
return SB.take();
}
//===----------------------------------------------------------------------===//
// MemoryBuffer::getSTDIN implementation.
//===----------------------------------------------------------------------===//
namespace {
class STDINBufferFile : public MemoryBuffer {
public:
virtual const char *getBufferIdentifier() const {
return "<stdin>";
}
};
}
MemoryBuffer *MemoryBuffer::getSTDIN() {
char Buffer[4096*4];
std::vector<char> FileData;
// Read in all of the data from stdin, we cannot mmap stdin.
//
// FIXME: That isn't necessarily true, we should try to mmap stdin and
// fallback if it fails.
sys::Program::ChangeStdinToBinary();
size_t ReadBytes;
do {
ReadBytes = fread(Buffer, sizeof(char), sizeof(Buffer), stdin);
FileData.insert(FileData.end(), Buffer, Buffer+ReadBytes);
} while (ReadBytes == sizeof(Buffer));
FileData.push_back(0); // &FileData[Size] is invalid. So is &*FileData.end().
size_t Size = FileData.size();
MemoryBuffer *B = new STDINBufferFile();
B->initCopyOf(&FileData[0], &FileData[Size-1]);
return B;
}
<|endoftext|> |
<commit_before>#include "../bart_builder.h"
#include "../problem_definition.h"
#include "gtest/gtest.h"
#include "../../test_helpers/bart_test_helper.h"
class BARTBuilderTest : public ::testing::Test {
protected:
void SetUp ();
// FE builder test
template <int dim>
void FEBuilderTest ();
// AQ builder test
template <int dim>
void AQBuilderTest ();
dealii::ParameterHandler prm;
};
void BARTBuilderTest::SetUp () {
prm.declare_entry("have reflective BC", "false",
dealii::Patterns::Bool(), "");
prm.declare_entry("angular quadrature order", "4",
dealii::Patterns::Integer(), "");
prm.declare_entry("angular quadrature name", "gl",
dealii::Patterns::Selection("gl"), "");
prm.declare_entry("number of groups", "1", dealii::Patterns::Integer(), "");
prm.declare_entry("transport model", "regular",
dealii::Patterns::Selection("regular|ep"), "");
prm.declare_entry("finite element polynomial degree", "1",
dealii::Patterns::Integer(), "");
prm.declare_entry("do nda", "true",
dealii::Patterns::Bool(), "");
prm.declare_entry("ho spatial discretization", "",
dealii::Patterns::Anything(), "");
prm.declare_entry("nda spatial discretization", "",
dealii::Patterns::Anything(), "");
}
template <int dim>
void BARTBuilderTest::FEBuilderTest () {
BARTBuilder<dim> builders (prm);
// set values to parameters
prm.set ("ho spatial discretization", "cfem");
prm.set ("nda spatial discretization", "cfem");
builders.SetParams (prm);
std::vector<dealii::FiniteElement<dim, dim>*> fe_ptrs;
builders.BuildFESpaces (fe_ptrs);
// testing for FE names
EXPECT_EQ (fe_ptrs.front()->get_name(),
"FE_Q<"+dealii::Utilities::int_to_string(dim)+">(1)");
EXPECT_EQ (fe_ptrs.back()->get_name(),
"FE_Q<"+dealii::Utilities::int_to_string(dim)+">(1)");
// changing FE types
prm.set ("ho spatial discretization", "dfem");
prm.set ("nda spatial discretization", "dfem");
builders.SetParams (prm);
fe_ptrs.clear ();
builders.BuildFESpaces (fe_ptrs);
EXPECT_EQ (fe_ptrs.front()->get_name(),
"FE_DGQ<"+dealii::Utilities::int_to_string(dim)+">(1)");
EXPECT_EQ (fe_ptrs.back()->get_name(),
"FE_DGQ<"+dealii::Utilities::int_to_string(dim)+">(1)");
// changing NDA FE type
prm.set ("nda spatial discretization", "cmfd");
builders.SetParams (prm);
fe_ptrs.clear ();
builders.BuildFESpaces (fe_ptrs);
EXPECT_EQ (fe_ptrs.back()->get_name(),
"FE_DGQ<"+dealii::Utilities::int_to_string(dim)+">(0)");
// changing NDA FE type
prm.set ("nda spatial discretization", "rtk");
builders.SetParams (prm);
fe_ptrs.clear ();
builders.BuildFESpaces (fe_ptrs);
EXPECT_EQ (fe_ptrs.back()->get_name(),
"FE_RaviartThomas<"+dealii::Utilities::int_to_string(dim)+">(1)");
}
TEST_F (BARTBuilderTest, FEBuilder2DTest) {
FEBuilderTest<2> ();
}
TEST_F (BARTBuilderTest, FEBuilder3DTest) {
FEBuilderTest<3> ();
}
template <int dim>
void BARTBuilderTest::AQBuilderTest () {
BARTBuilder<dim> builders (prm);
std::unique_ptr<AQBase<dim>> aq_ptr;
std::string aq_name = (dim==1) ? "gl" : "lsgc";
prm.set ("angular quadrature name", aq_name);
prm.set ("angular quadrature order", "4");
// call builder function to build aq
builders.BuildAQ (prm, aq_ptr);
aq_ptr->MakeAQ();
auto wi = aq_ptr->GetAQWeights();
auto omega_i = aq_ptr->GetAQDirs();
// check output
std::string filename = "aq_builder_"+dealii::Utilities::int_to_string(dim)+"d";
btest::GoldTestInit(filename);
for (unsigned int i=0; i<wi.size(); ++i)
{
dealii::deallog << "Weight: " << wi[i] << "; Omega: ";
for (int j=0; j<dim; ++j)
dealii::deallog << omega_i[i][j] << " ";
dealii::deallog << std::endl;
}
btest::GoldTestRun(filename);
}
TEST_F (BARTBuilderTest, AQBuilder1DTest) {
AQBuilderTest<1> ();
}
TEST_F (BARTBuilderTest, AQBuilder2DTest) {
AQBuilderTest<2> ();
}
TEST_F (BARTBuilderTest, AQBuilder3DTest) {
AQBuilderTest<3> ();
}
<commit_msg>Fixed aq builder test failure #80<commit_after>#include "../bart_builder.h"
#include "../problem_definition.h"
#include "gtest/gtest.h"
#include "../../test_helpers/bart_test_helper.h"
class BARTBuilderTest : public ::testing::Test {
protected:
void SetUp ();
// FE builder test
template <int dim>
void FEBuilderTest ();
// AQ builder test
template <int dim>
void AQBuilderTest ();
dealii::ParameterHandler prm;
};
void BARTBuilderTest::SetUp () {
prm.declare_entry("have reflective BC", "false",
dealii::Patterns::Bool(), "");
prm.declare_entry("angular quadrature order", "4",
dealii::Patterns::Integer(), "");
prm.declare_entry("angular quadrature name", "gl",
dealii::Patterns::Selection("gl|lsgc"), "");
prm.declare_entry("number of groups", "1", dealii::Patterns::Integer(), "");
prm.declare_entry("transport model", "regular",
dealii::Patterns::Selection("regular|ep"), "");
prm.declare_entry("finite element polynomial degree", "1",
dealii::Patterns::Integer(), "");
prm.declare_entry("do nda", "true",
dealii::Patterns::Bool(), "");
prm.declare_entry("ho spatial discretization", "",
dealii::Patterns::Anything(), "");
prm.declare_entry("nda spatial discretization", "",
dealii::Patterns::Anything(), "");
}
template <int dim>
void BARTBuilderTest::FEBuilderTest () {
BARTBuilder<dim> builders (prm);
// set values to parameters
prm.set ("ho spatial discretization", "cfem");
prm.set ("nda spatial discretization", "cfem");
builders.SetParams (prm);
std::vector<dealii::FiniteElement<dim, dim>*> fe_ptrs;
builders.BuildFESpaces (fe_ptrs);
// testing for FE names
EXPECT_EQ (fe_ptrs.front()->get_name(),
"FE_Q<"+dealii::Utilities::int_to_string(dim)+">(1)");
EXPECT_EQ (fe_ptrs.back()->get_name(),
"FE_Q<"+dealii::Utilities::int_to_string(dim)+">(1)");
// changing FE types
prm.set ("ho spatial discretization", "dfem");
prm.set ("nda spatial discretization", "dfem");
builders.SetParams (prm);
fe_ptrs.clear ();
builders.BuildFESpaces (fe_ptrs);
EXPECT_EQ (fe_ptrs.front()->get_name(),
"FE_DGQ<"+dealii::Utilities::int_to_string(dim)+">(1)");
EXPECT_EQ (fe_ptrs.back()->get_name(),
"FE_DGQ<"+dealii::Utilities::int_to_string(dim)+">(1)");
// changing NDA FE type
prm.set ("nda spatial discretization", "cmfd");
builders.SetParams (prm);
fe_ptrs.clear ();
builders.BuildFESpaces (fe_ptrs);
EXPECT_EQ (fe_ptrs.back()->get_name(),
"FE_DGQ<"+dealii::Utilities::int_to_string(dim)+">(0)");
// changing NDA FE type
prm.set ("nda spatial discretization", "rtk");
builders.SetParams (prm);
fe_ptrs.clear ();
builders.BuildFESpaces (fe_ptrs);
EXPECT_EQ (fe_ptrs.back()->get_name(),
"FE_RaviartThomas<"+dealii::Utilities::int_to_string(dim)+">(1)");
}
TEST_F (BARTBuilderTest, FEBuilder2DTest) {
FEBuilderTest<2> ();
}
TEST_F (BARTBuilderTest, FEBuilder3DTest) {
FEBuilderTest<3> ();
}
template <int dim>
void BARTBuilderTest::AQBuilderTest () {
BARTBuilder<dim> builders (prm);
std::unique_ptr<AQBase<dim>> aq_ptr;
std::string aq_name = (dim==1) ? "gl" : "lsgc";
prm.set ("angular quadrature name", aq_name);
prm.set ("angular quadrature order", "4");
// call builder function to build aq
builders.BuildAQ (prm, aq_ptr);
aq_ptr->MakeAQ();
auto wi = aq_ptr->GetAQWeights();
auto omega_i = aq_ptr->GetAQDirs();
// check output
std::string filename = "aq_builder_"+dealii::Utilities::int_to_string(dim)+"d";
btest::GoldTestInit(filename);
for (unsigned int i=0; i<wi.size(); ++i)
{
dealii::deallog << "Weight: " << wi[i] << "; Omega: ";
for (int j=0; j<dim; ++j)
dealii::deallog << omega_i[i][j] << " ";
dealii::deallog << std::endl;
}
btest::GoldTestRun(filename);
}
TEST_F (BARTBuilderTest, AQBuilder1DTest) {
AQBuilderTest<1> ();
}
TEST_F (BARTBuilderTest, AQBuilder2DTest) {
AQBuilderTest<2> ();
}
TEST_F (BARTBuilderTest, AQBuilder3DTest) {
AQBuilderTest<3> ();
}
<|endoftext|> |
<commit_before>/***************************************************************
*
* Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You may
* obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************/
// This is a wrapper program that we use for things we launch via glexec,
// in order to get around glexec's inability to pass environment variables.
// The basic procedure is:
// 1) Condor sets up a UNIX domain socket pair
// 2) Condor invokes this wrapper via glexec, passing one of the sockets
// to the wrapper as it's standard input stream.
// 3) A stream of environment variables is sent over the socket pair and
// merged into the environment that will be used for the job.
// 4) The job's "real" standard input FD is sent over the socket pair. The
// wrapper's socket end is dup'ed and FD 0 is then set to use the
// received FD.
// 5) The wrapper's socket end is set close-on-exec, and the wrapper then
// exec's the job.
#define _CONDOR_ALLOW_OPEN
#include "condor_common.h"
#include "MyString.h"
#include "env.h"
#include "fdpass.h"
static char* read_env(int);
static int read_fd(int);
int
main(int, char* argv[])
{
MyString err;
// dup FD 0 since well will later replace FD 0 with the job's stdin
//
int sock_fd = dup(0);
if (sock_fd == -1) {
err.sprintf("dup error on FD 0: %s", strerror(errno));
write(0, err.Value(), err.Length() + 1);
exit(1);
}
// set up an Env object that we'll use for the job. we'll initialize
// it with the environment that glexec prepared for us then merge on
// top of that the environment that Condor sends us
//
Env env;
env.MergeFrom(environ);
char* env_buf = read_env(sock_fd);
env.MergeFrom(env_buf);
delete[] env_buf;
// now receive an FD on our stdin (which is a UNIX domain socket)
// that we'll use as the job's stdin
//
int job_fd = read_fd(sock_fd);
if (dup2(job_fd, 0) == -1) {
err.sprintf("dup2 to FD 0 error: %s", strerror(errno));
write(sock_fd, err.Value(), err.Length() + 1);
exit(1);
}
close(job_fd);
if (fcntl(sock_fd, F_SETFD, FD_CLOEXEC) == -1) {
err.sprintf("fcntl error setting close-on-exec: %s",
strerror(errno));
write(sock_fd, err.Value(), err.Length() + 1);
exit(1);
}
// now we can exec the job. for arguments, we shift this wrappers
// arguments by one. similarly, the job's executable path is taken
// as our argv[1]
//
char** envp = env.getStringArray();
execve(argv[1], &argv[1], envp);
err.sprintf("execve error: %s", strerror(errno));
write(sock_fd, err.Value(), err.Length() + 1);
exit(1);
}
static char*
read_env(int sock_fd)
{
MyString err;
int env_len;
if (fread(&env_len, sizeof(env_len), 1, stdin) != 1) {
if (feof(stdin)) {
err = "unexpected EOF reading env size";
}
else {
err.sprintf("fread error reading env size: %s",
strerror(errno));
}
write(sock_fd, err.Value(), err.Length() + 1);
exit(1);
}
if (env_len <= 0) {
err.sprintf("invalid env size %d read from stdin", env_len);
write(sock_fd, err.Value(), err.Length() + 1);
exit(1);
}
char* env_buf = new char[env_len];
if (env_buf == NULL) {
err.sprintf("failure to allocate %d bytes", env_len);
write(sock_fd, err.Value(), err.Length() + 1);
exit(1);
}
if (fread(env_buf, env_len, 1, stdin) != 1) {
if (feof(stdin)) {
err = "unexpected EOF reading env";
}
else {
err.sprintf("fread error reading env: %s",
strerror(errno));
}
write(sock_fd, err.Value(), err.Length() + 1);
exit(1);
}
return env_buf;
}
static int
read_fd(int sock_fd)
{
MyString err;
int flag;
if (fread(&flag, sizeof(flag), 1, stdin) != 1) {
if (feof(stdin)) {
err = "unexpected EOF reading FD flag";
}
else {
err.sprintf("fread error reading FD flag: %s",
strerror(errno));
}
write(sock_fd, err.Value(), err.Length() + 1);
exit(1);
}
int fd;
if (flag) {
fd = fdpass_recv(sock_fd);
if (fd == -1) {
err.sprintf("fdpass_recv failed\n");
write(sock_fd, err.Value(), err.Length() + 1);
exit(1);
}
}
else {
fd = open("/dev/null", O_RDONLY);
if (fd == -1) {
err.sprintf("error opening /dev/null: %s",
strerror(errno));
write(sock_fd, err.Value(), err.Length() + 1);
exit(1);
}
}
return fd;
}
<commit_msg>Revert "Changed environment precedence in condor_glexec_wrapper"<commit_after>/***************************************************************
*
* Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You may
* obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************/
// This is a wrapper program that we use for things we launch via glexec,
// in order to get around glexec's inability to pass environment variables.
// The basic procedure is:
// 1) Condor sets up a UNIX domain socket pair
// 2) Condor invokes this wrapper via glexec, passing one of the sockets
// to the wrapper as it's standard input stream.
// 3) A stream of environment variables is sent over the socket pair and
// merged into the environment that will be used for the job.
// 4) The job's "real" standard input FD is sent over the socket pair. The
// wrapper's socket end is dup'ed and FD 0 is then set to use the
// received FD.
// 5) The wrapper's socket end is set close-on-exec, and the wrapper then
// exec's the job.
#define _CONDOR_ALLOW_OPEN
#include "condor_common.h"
#include "MyString.h"
#include "env.h"
#include "fdpass.h"
static char* read_env(int);
static int read_fd(int);
int
main(int, char* argv[])
{
MyString err;
// dup FD 0 since well will later replace FD 0 with the job's stdin
//
int sock_fd = dup(0);
if (sock_fd == -1) {
err.sprintf("dup error on FD 0: %s", strerror(errno));
write(0, err.Value(), err.Length() + 1);
exit(1);
}
// set up an Env object that we'll use for the job. we'll initialize
// it with the environment that Condor sends us then merge on top of
// that the environment that glexec prepared for us
//
Env env;
char* env_buf = read_env(sock_fd);
env.MergeFrom(env_buf);
env.MergeFrom(environ);
delete[] env_buf;
// now receive an FD on our stdin (which is a UNIX domain socket)
// that we'll use as the job's stdin
//
int job_fd = read_fd(sock_fd);
if (dup2(job_fd, 0) == -1) {
err.sprintf("dup2 to FD 0 error: %s", strerror(errno));
write(sock_fd, err.Value(), err.Length() + 1);
exit(1);
}
close(job_fd);
if (fcntl(sock_fd, F_SETFD, FD_CLOEXEC) == -1) {
err.sprintf("fcntl error setting close-on-exec: %s",
strerror(errno));
write(sock_fd, err.Value(), err.Length() + 1);
exit(1);
}
// now we can exec the job. for arguments, we shift this wrappers
// arguments by one. similarly, the job's executable path is taken
// as our argv[1]
//
char** envp = env.getStringArray();
execve(argv[1], &argv[1], envp);
err.sprintf("execve error: %s", strerror(errno));
write(sock_fd, err.Value(), err.Length() + 1);
exit(1);
}
static char*
read_env(int sock_fd)
{
MyString err;
int env_len;
if (fread(&env_len, sizeof(env_len), 1, stdin) != 1) {
if (feof(stdin)) {
err = "unexpected EOF reading env size";
}
else {
err.sprintf("fread error reading env size: %s",
strerror(errno));
}
write(sock_fd, err.Value(), err.Length() + 1);
exit(1);
}
if (env_len <= 0) {
err.sprintf("invalid env size %d read from stdin", env_len);
write(sock_fd, err.Value(), err.Length() + 1);
exit(1);
}
char* env_buf = new char[env_len];
if (env_buf == NULL) {
err.sprintf("failure to allocate %d bytes", env_len);
write(sock_fd, err.Value(), err.Length() + 1);
exit(1);
}
if (fread(env_buf, env_len, 1, stdin) != 1) {
if (feof(stdin)) {
err = "unexpected EOF reading env";
}
else {
err.sprintf("fread error reading env: %s",
strerror(errno));
}
write(sock_fd, err.Value(), err.Length() + 1);
exit(1);
}
return env_buf;
}
static int
read_fd(int sock_fd)
{
MyString err;
int flag;
if (fread(&flag, sizeof(flag), 1, stdin) != 1) {
if (feof(stdin)) {
err = "unexpected EOF reading FD flag";
}
else {
err.sprintf("fread error reading FD flag: %s",
strerror(errno));
}
write(sock_fd, err.Value(), err.Length() + 1);
exit(1);
}
int fd;
if (flag) {
fd = fdpass_recv(sock_fd);
if (fd == -1) {
err.sprintf("fdpass_recv failed\n");
write(sock_fd, err.Value(), err.Length() + 1);
exit(1);
}
}
else {
fd = open("/dev/null", O_RDONLY);
if (fd == -1) {
err.sprintf("error opening /dev/null: %s",
strerror(errno));
write(sock_fd, err.Value(), err.Length() + 1);
exit(1);
}
}
return fd;
}
<|endoftext|> |
<commit_before>#ifndef WEAKPOINTER_HPP
#define WEAKPOINTER_HPP
#include "List.hpp"
namespace org_pqrs_Karabiner {
#define DECLARE_WEAKPOINTER(TYPENAME) \
class TYPENAME; \
class WeakPointerManager_##TYPENAME final { \
public: \
/* Call WeakPointerManager::add in constructor. */ \
/* For example: */ \
\
/* ----------------------------------------------- */ \
/* DECLARE_WEAKPOINTER(TestClass); */ \
/* */ \
/* class TestClass final { */ \
/* public: */ \
/* TestClass(void) { */ \
/* WeakPointerManager_TestClass::add(this); */ \
/* } */ \
/* ~TestClass(void) { */ \
/* WeakPointerManager_TestClass::remove(this); */ \
/* } */ \
/* }; */ \
/* ----------------------------------------------- */ \
\
/* Note: */ \
/* DO NOT call WeakPointerManager::add twice with same pointer. */ \
/* If you call WeakPointerManager::add twice, */ \
/* WeakPointerManager::expired will return false with deleted pointer. */ \
\
static void add(const TYPENAME* p) { \
auto item = new WeakPointerManagerItem(p); \
if (item) { \
list_.push_back(item); \
} \
} \
\
static void remove(const TYPENAME* pointer) { \
for (WeakPointerManagerItem* p = static_cast<WeakPointerManagerItem*>(list_.safe_front()); \
p; \
p = static_cast<WeakPointerManagerItem*>(p->getnext())) { \
if (p->pointer == pointer) { \
list_.erase_and_delete(p); \
break; \
} \
} \
} \
\
static bool expired(const TYPENAME* pointer) { \
for (WeakPointerManagerItem* p = static_cast<WeakPointerManagerItem*>(list_.safe_front()); \
p; \
p = static_cast<WeakPointerManagerItem*>(p->getnext())) { \
if (p->pointer == pointer) { \
return false; \
} \
} \
return true; \
} \
\
private: \
class WeakPointerManagerItem : public List::Item { \
public: \
WeakPointerManagerItem(const TYPENAME* p) : pointer(p) {} \
virtual ~WeakPointerManagerItem(void) {} \
\
const TYPENAME* pointer; \
}; \
\
static List list_; \
}; \
\
class WeakPointer_##TYPENAME final { \
public: \
WeakPointer_##TYPENAME(TYPENAME* p) : pointer_(p) {} \
bool expired(void) const { return WeakPointerManager_##TYPENAME::expired(pointer_); } \
\
TYPENAME* operator->(void) const { return pointer_; } \
TYPENAME* get(void) const { return pointer_; } \
\
private: \
TYPENAME* pointer_; \
};
#define DEFINE_WEAKPOINTER(TYPENAME) \
List WeakPointerManager_##TYPENAME::list_;
#define DEFINE_WEAKPOINTER_IN_CLASS(CLASS, TYPENAME) \
List CLASS::WeakPointerManager_##TYPENAME::list_;
}
#endif
<commit_msg>improved WeakPointer for reuse address<commit_after>#ifndef WEAKPOINTER_HPP
#define WEAKPOINTER_HPP
#include "List.hpp"
namespace org_pqrs_Karabiner {
#define DECLARE_WEAKPOINTER(TYPENAME) \
class TYPENAME; \
class WeakPointerManager_##TYPENAME final { \
public: \
/* Call WeakPointerManager::add in constructor. */ \
/* For example: */ \
\
/* ----------------------------------------------- */ \
/* DECLARE_WEAKPOINTER(TestClass); */ \
/* */ \
/* class TestClass final { */ \
/* public: */ \
/* TestClass(void) { */ \
/* WeakPointerManager_TestClass::add(this); */ \
/* } */ \
/* ~TestClass(void) { */ \
/* WeakPointerManager_TestClass::remove(this); */ \
/* } */ \
/* }; */ \
/* ----------------------------------------------- */ \
\
/* Note: */ \
/* DO NOT call WeakPointerManager::add twice with same pointer. */ \
/* If you call WeakPointerManager::add twice, */ \
/* WeakPointerManager::expired will return false with deleted pointer. */ \
\
static void add(const TYPENAME* p) { \
auto item = new WeakPointerManagerItem(p, ++lastid_); \
if (item) { \
list_.push_back(item); \
} \
} \
\
static void remove(const TYPENAME* pointer) { \
for (WeakPointerManagerItem* p = static_cast<WeakPointerManagerItem*>(list_.safe_front()); \
p; \
p = static_cast<WeakPointerManagerItem*>(p->getnext())) { \
if (p->pointer == pointer) { \
list_.erase_and_delete(p); \
break; \
} \
} \
} \
\
static bool expired(const TYPENAME* pointer, int id) { \
for (WeakPointerManagerItem* p = static_cast<WeakPointerManagerItem*>(list_.safe_front()); \
p; \
p = static_cast<WeakPointerManagerItem*>(p->getnext())) { \
if (p->pointer == pointer && p->id == id) { \
return false; \
} \
} \
return true; \
} \
\
static int getid(const TYPENAME* pointer) { \
for (WeakPointerManagerItem* p = static_cast<WeakPointerManagerItem*>(list_.safe_front()); \
p; \
p = static_cast<WeakPointerManagerItem*>(p->getnext())) { \
if (p->pointer == pointer) { \
return p->id; \
} \
} \
return -1; \
} \
\
private: \
class WeakPointerManagerItem final : public List::Item { \
public: \
WeakPointerManagerItem(const TYPENAME* p, int c) : pointer(p), id(c) {} \
~WeakPointerManagerItem(void) {} \
\
const TYPENAME* pointer; \
int id; \
}; \
\
static List list_; \
static int lastid_; \
}; \
\
class WeakPointer_##TYPENAME final { \
public: \
WeakPointer_##TYPENAME(TYPENAME* p) : pointer_(p), \
id_(WeakPointerManager_##TYPENAME::getid(p)) {} \
bool expired(void) const { return WeakPointerManager_##TYPENAME::expired(pointer_, id_); } \
\
TYPENAME* operator->(void) const { return pointer_; } \
TYPENAME* get(void) const { return pointer_; } \
\
bool operator==(WeakPointer_##TYPENAME other) const { \
return pointer_ == other.pointer_ && id_ == other.id_; \
} \
\
private: \
TYPENAME* pointer_; \
int id_; \
};
#define DEFINE_WEAKPOINTER(TYPENAME) \
List WeakPointerManager_##TYPENAME::list_; \
int WeakPointerManager_##TYPENAME::lastid_ = 0;
#define DEFINE_WEAKPOINTER_IN_CLASS(CLASS, TYPENAME) \
List CLASS::WeakPointerManager_##TYPENAME::list_; \
int CLASS::WeakPointerManager_##TYPENAME::lastid_ = 0;
}
#endif
<|endoftext|> |
<commit_before>/*
* FilePath.cpp
*
* Copyright (C) 2020 by RStudio, PBC
*
* Unless you have received this program directly from RStudio pursuant to the terms of a commercial license agreement
* with RStudio, then this program is licensed to you under the following terms:
*
* 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 <tests/TestThat.hpp>
#include <shared_core/FilePath.hpp>
namespace rstudio {
namespace core {
TEST_CASE("Empty File Path tests")
{
SECTION("Construction")
{
FilePath f;
CHECK(f.getAbsolutePath().empty());
}
SECTION("Comparison (equal, true)")
{
FilePath f1, f2;
CHECK(f1 == f2);
CHECK(f2 == f1);
CHECK(f1 == f1);
}
SECTION("Comparison (equal, false)")
{
FilePath f1, f2("/a/different/path");
CHECK_FALSE(f1 == f2);
CHECK_FALSE(f2 == f1);
}
SECTION("Comparison (inequal, false)")
{
FilePath f1, f2;
CHECK_FALSE(f1 != f2);
CHECK_FALSE(f2 != f1);
CHECK_FALSE(f1 != f1);
}
SECTION("Comparison (inequal, true)")
{
FilePath f1, f2("/a/different/path");
CHECK(f1 != f2);
CHECK(f2 != f1);
}
SECTION("Comparison (lt)")
{
FilePath f1, f2("/a/different/path");
CHECK(f1 < f2);
CHECK_FALSE(f2 < f1);
}
SECTION("Retrieval methods")
{
FilePath f;
std::vector<FilePath> children;
CHECK_FALSE(f.exists());
CHECK(f.getAbsolutePath().empty());
CHECK(f.getAbsolutePathNative().empty());
#ifdef _WIN32
CHECK(f.getAbsolutePathW().empty());
#endif
CHECK(f.getCanonicalPath().empty());
CHECK(f.getChildren(children)); // Returns error.
CHECK(children.empty());
CHECK(f.getExtension().empty());
CHECK(f.getExtensionLowerCase().empty());
CHECK(f.getFilename().empty());
CHECK(f.getLastWriteTime() == 0);
CHECK(f.getLexicallyNormalPath().empty());
CHECK(f.getMimeContentType() == "text/plain"); // text/plain is the default.
CHECK(f.getParent() == f); // Error on getting the parent, so self should be returned.
CHECK(f.getRelativePath(FilePath("/a/parent/path")) == "");
CHECK(f.getSize() == 0);
CHECK(f.getSizeRecursive() == 0);
CHECK(f.getStem().empty());
CHECK_FALSE(f.hasExtension("ext"));
CHECK_FALSE(f.hasTextMimeType()); // has text mime type sets the default mime type as "application/octet-stream"
CHECK_FALSE(f.isDirectory());
CHECK(f.isEmpty());
CHECK_FALSE(f.isHidden());
CHECK_FALSE(f.isJunction());
CHECK_FALSE(f.isRegularFile());
CHECK_FALSE(f.isSymlink());
CHECK(f.isWithin(f));
CHECK_FALSE(f.isWithin(FilePath("/some/path")));
}
}
} // namespace core
} // namespace rstudio
<commit_msg>clean up clang tidy warning about str.empty<commit_after>/*
* FilePath.cpp
*
* Copyright (C) 2020 by RStudio, PBC
*
* Unless you have received this program directly from RStudio pursuant to the terms of a commercial license agreement
* with RStudio, then this program is licensed to you under the following terms:
*
* 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 <tests/TestThat.hpp>
#include <shared_core/FilePath.hpp>
namespace rstudio {
namespace core {
TEST_CASE("Empty File Path tests")
{
SECTION("Construction")
{
FilePath f;
CHECK(f.getAbsolutePath().empty());
}
SECTION("Comparison (equal, true)")
{
FilePath f1, f2;
CHECK(f1 == f2);
CHECK(f2 == f1);
CHECK(f1 == f1);
}
SECTION("Comparison (equal, false)")
{
FilePath f1, f2("/a/different/path");
CHECK_FALSE(f1 == f2);
CHECK_FALSE(f2 == f1);
}
SECTION("Comparison (inequal, false)")
{
FilePath f1, f2;
CHECK_FALSE(f1 != f2);
CHECK_FALSE(f2 != f1);
CHECK_FALSE(f1 != f1);
}
SECTION("Comparison (inequal, true)")
{
FilePath f1, f2("/a/different/path");
CHECK(f1 != f2);
CHECK(f2 != f1);
}
SECTION("Comparison (lt)")
{
FilePath f1, f2("/a/different/path");
CHECK(f1 < f2);
CHECK_FALSE(f2 < f1);
}
SECTION("Retrieval methods")
{
FilePath f;
std::vector<FilePath> children;
CHECK_FALSE(f.exists());
CHECK(f.getAbsolutePath().empty());
CHECK(f.getAbsolutePathNative().empty());
#ifdef _WIN32
CHECK(f.getAbsolutePathW().empty());
#endif
CHECK(f.getCanonicalPath().empty());
CHECK(f.getChildren(children)); // Returns error.
CHECK(children.empty());
CHECK(f.getExtension().empty());
CHECK(f.getExtensionLowerCase().empty());
CHECK(f.getFilename().empty());
CHECK(f.getLastWriteTime() == 0);
CHECK(f.getLexicallyNormalPath().empty());
CHECK(f.getMimeContentType() == "text/plain"); // text/plain is the default.
CHECK(f.getParent() == f); // Error on getting the parent, so self should be returned.
CHECK(f.getRelativePath(FilePath("/a/parent/path")).empty());
CHECK(f.getSize() == 0);
CHECK(f.getSizeRecursive() == 0);
CHECK(f.getStem().empty());
CHECK_FALSE(f.hasExtension("ext"));
CHECK_FALSE(f.hasTextMimeType()); // has text mime type sets the default mime type as "application/octet-stream"
CHECK_FALSE(f.isDirectory());
CHECK(f.isEmpty());
CHECK_FALSE(f.isHidden());
CHECK_FALSE(f.isJunction());
CHECK_FALSE(f.isRegularFile());
CHECK_FALSE(f.isSymlink());
CHECK(f.isWithin(f));
CHECK_FALSE(f.isWithin(FilePath("/some/path")));
}
}
} // namespace core
} // namespace rstudio
<|endoftext|> |
<commit_before>// This file is part of Poseidon.
// Copyleft 2020, LH_Mouse. All wrongs reserved.
#include "precompiled.hpp"
#include "static/main_config.hpp"
#include "static/async_logger.hpp"
#include "static/timer_driver.hpp"
#include "static/network_driver.hpp"
#include "utilities.hpp"
#include <locale.h>
#include <unistd.h>
#include <signal.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
using namespace poseidon;
namespace {
[[noreturn]]
int
do_print_help_and_exit(const char* self)
{
::printf(
// 1 2 3 4 5 6 7 |
// 3456789012345678901234567890123456789012345678901234567890123456789012345|
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""" R"'''''''''''''''(
Usage: %s [OPTIONS] [[--] DIRECTORY]
-d daemonize
-h show help message then exit
-V show version information then exit
-v enable verbose mode
Daemonization, if requested, is performed after loading config files. Early
failues are printed to standard error.
If DIRECTORY is specified, the working directory is switched there before
doing everything else.
Visit the homepage at <%s>.
Report bugs to <%s>.
)'''''''''''''''" """"""""""""""""""""""""""""""""""""""""""""""""""""""""+1,
// 3456789012345678901234567890123456789012345678901234567890123456789012345|
// 1 2 3 4 5 6 7 |
self,
PACKAGE_URL,
PACKAGE_BUGREPORT);
::fflush(stdout);
::quick_exit(0);
}
const char*
do_tell_build_time()
{
static char s_time_str[64];
if(ROCKET_EXPECT(s_time_str[0]))
return s_time_str;
// Convert the build time to ISO 8601 format.
::tm tr;
::std::memset(&tr, 0, sizeof(tr));
::strptime(__DATE__ " " __TIME__, "%b %d %Y %H:%M:%S", &tr);
::strftime(s_time_str, sizeof(s_time_str), "%Y-%m-%d %H:%M:%S", &tr);
return s_time_str;
}
[[noreturn]]
int
do_print_version_and_exit()
{
::printf(
// 1 2 3 4 5 6 7 |
// 3456789012345678901234567890123456789012345678901234567890123456789012345|
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""" R"'''''''''''''''(
%s [built on %s]
Visit the homepage at <%s>.
Report bugs to <%s>.
)'''''''''''''''" """"""""""""""""""""""""""""""""""""""""""""""""""""""""+1,
// 3456789012345678901234567890123456789012345678901234567890123456789012345|
// 1 2 3 4 5 6 7 |
PACKAGE_STRING, do_tell_build_time(),
PACKAGE_URL,
PACKAGE_BUGREPORT);
::fflush(stdout);
::quick_exit(0);
}
// We want to detect Ctrl-C.
::std::atomic<bool> exit_now;
void
do_trap_exit_signal(int sig)
noexcept
{
// Trap Ctrl-C. Failure to set the signal handler is ignored.
struct ::sigaction sigx = { };
sigx.sa_handler = [](int) { exit_now = 1; };
::sigaction(sig, &sigx, nullptr);
}
// Define command-line options here.
struct Command_Line_Options
{
// options
bool daemonize = false;
bool verbose = false;
// non-options
cow_string cd_here;
};
// This may also be automatic objects. It is declared here for convenience.
Command_Line_Options cmdline;
// These are process exit status codes.
enum Exit_Code : uint8_t
{
exit_success = 0,
exit_system_error = 1,
exit_invalid_argument = 2,
};
[[noreturn]]
int
do_exit(Exit_Code code, const char* fmt = nullptr, ...)
noexcept
{
// Output the string to standard error.
if(fmt) {
::va_list ap;
va_start(ap, fmt);
::vfprintf(stderr, fmt, ap);
va_end(ap);
}
// Perform fast exit.
::fflush(nullptr);
::quick_exit(static_cast<int>(code));
}
void
do_parse_command_line(int argc, char** argv)
{
bool help = false;
bool version = false;
opt<bool> daemonize;
opt<bool> verbose;
opt<cow_string> cd_here;
// Check for some common options before calling `getopt()`.
if(argc > 1) {
if(::strcmp(argv[1], "--help") == 0)
do_print_help_and_exit(argv[0]);
if(::strcmp(argv[1], "--version") == 0)
do_print_version_and_exit();
}
// Parse command-line options.
int ch;
while((ch = ::getopt(argc, argv, "+dhVv")) != -1) {
// Identify a single option.
switch(ch) {
case 'd':
daemonize = true;
continue;
case 'h':
help = true;
continue;
case 'V':
version = true;
continue;
case 'v':
verbose = true;
continue;
}
// `getopt()` will have written an error message to standard error.
do_exit(exit_invalid_argument, "Try `%s -h` for help.\n",
argv[0]);
}
// Check for early exit conditions.
if(help)
do_print_help_and_exit(argv[0]);
if(version)
do_print_version_and_exit();
// If more arguments follow, they denote the working directory.
if(argc - optind > 1)
do_exit(exit_invalid_argument, "%s: too many arguments -- '%s'\n"
"Try `%s -h` for help.\n",
argv[0], argv[optind+1],
argv[0]);
if(argc - optind > 0)
cd_here = cow_string(argv[optind]);
// Daemonization mode is off by default.
if(daemonize)
cmdline.daemonize = *daemonize;
// Verbose mode is off by default.
if(verbose)
cmdline.verbose = *verbose;
// The default working directory is empty which means 'do not switch'.
if(cd_here)
cmdline.cd_here = ::std::move(*cd_here);
}
} // namespace
int
main(int argc, char** argv)
try {
// Select the C locale.
// UTF-8 is required for wide-oriented standard streams.
::setlocale(LC_ALL, "C.UTF-8");
// Note that this function shall not return in case of errors.
do_parse_command_line(argc, argv);
// Set current working directory if one is specified.
if(cmdline.cd_here.size())
if(::chdir(cmdline.cd_here.safe_c_str()) != 0)
POSEIDON_THROW("could not set working directory to '$2'\n"
"[`chdir()` failed: $1]",
noadl::format_errno(errno), cmdline.cd_here);
// Load 'main.conf' before daemonization, so any earlier failures are
// visible to the user.
Main_Config::reload();
Async_Logger::reload();
Network_Driver::reload();
// Daemonize the process before entering modal loop.
if(cmdline.daemonize)
if(::daemon(1, 0) != 0)
POSEIDON_THROW("could not daemonize process\n"
"[`chdir()` failed: $1]",
noadl::format_errno(errno));
// Set name of the main thread. Failure to set the name is ignored.
::pthread_setname_np(::pthread_self(), "poseidon");
// Disable cancellation for safety. Failure to set the cancel state is ignored.
::pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, nullptr);
// Trap exit signals. Failure to set signal handlers is ignored.
// This also makes stdio functions fail immediately.
do_trap_exit_signal(SIGINT);
do_trap_exit_signal(SIGTERM);
do_trap_exit_signal(SIGHUP);
// Ignore `SIGPIPE` for good.
::signal(SIGPIPE, SIG_IGN);
// Start daemon threads.
Async_Logger::start();
Timer_Driver::start();
Network_Driver::start();
sleep(10000);
do_exit(exit_success, "interrupt\n");
}
catch(exception& stdex) {
// Print the message in `stdex`. There isn't much we can do.
do_exit(exit_system_error, "%s\n[exception class `%s`]\n",
stdex.what(), typeid(stdex).name());
}
<commit_msg>main: Add startup log<commit_after>// This file is part of Poseidon.
// Copyleft 2020, LH_Mouse. All wrongs reserved.
#include "precompiled.hpp"
#include "static/main_config.hpp"
#include "static/async_logger.hpp"
#include "static/timer_driver.hpp"
#include "static/network_driver.hpp"
#include "utilities.hpp"
#include <locale.h>
#include <unistd.h>
#include <signal.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
using namespace poseidon;
namespace {
[[noreturn]]
int
do_print_help_and_exit(const char* self)
{
::printf(
// 1 2 3 4 5 6 7 |
// 3456789012345678901234567890123456789012345678901234567890123456789012345|
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""" R"'''''''''''''''(
Usage: %s [OPTIONS] [[--] DIRECTORY]
-d daemonize
-h show help message then exit
-V show version information then exit
-v enable verbose mode
Daemonization, if requested, is performed after loading config files. Early
failues are printed to standard error.
If DIRECTORY is specified, the working directory is switched there before
doing everything else.
Visit the homepage at <%s>.
Report bugs to <%s>.
)'''''''''''''''" """"""""""""""""""""""""""""""""""""""""""""""""""""""""+1,
// 3456789012345678901234567890123456789012345678901234567890123456789012345|
// 1 2 3 4 5 6 7 |
self,
PACKAGE_URL,
PACKAGE_BUGREPORT);
::fflush(stdout);
::quick_exit(0);
}
const char*
do_tell_build_time()
{
static char s_time_str[64];
if(ROCKET_EXPECT(s_time_str[0]))
return s_time_str;
// Convert the build time to ISO 8601 format.
::tm tr;
::std::memset(&tr, 0, sizeof(tr));
::strptime(__DATE__ " " __TIME__, "%b %d %Y %H:%M:%S", &tr);
::strftime(s_time_str, sizeof(s_time_str), "%Y-%m-%d %H:%M:%S", &tr);
return s_time_str;
}
[[noreturn]]
int
do_print_version_and_exit()
{
::printf(
// 1 2 3 4 5 6 7 |
// 3456789012345678901234567890123456789012345678901234567890123456789012345|
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""" R"'''''''''''''''(
%s [built on %s]
Visit the homepage at <%s>.
Report bugs to <%s>.
)'''''''''''''''" """"""""""""""""""""""""""""""""""""""""""""""""""""""""+1,
// 3456789012345678901234567890123456789012345678901234567890123456789012345|
// 1 2 3 4 5 6 7 |
PACKAGE_STRING, do_tell_build_time(),
PACKAGE_URL,
PACKAGE_BUGREPORT);
::fflush(stdout);
::quick_exit(0);
}
// We want to detect Ctrl-C.
::std::atomic<bool> exit_now;
void
do_trap_exit_signal(int sig)
noexcept
{
// Trap Ctrl-C. Failure to set the signal handler is ignored.
struct ::sigaction sigx = { };
sigx.sa_handler = [](int) { exit_now = 1; };
::sigaction(sig, &sigx, nullptr);
}
// Define command-line options here.
struct Command_Line_Options
{
// options
bool daemonize = false;
bool verbose = false;
// non-options
cow_string cd_here;
};
// This may also be automatic objects. It is declared here for convenience.
Command_Line_Options cmdline;
// These are process exit status codes.
enum Exit_Code : uint8_t
{
exit_success = 0,
exit_system_error = 1,
exit_invalid_argument = 2,
};
[[noreturn]]
int
do_exit(Exit_Code code, const char* fmt = nullptr, ...)
noexcept
{
// Output the string to standard error.
if(fmt) {
::va_list ap;
va_start(ap, fmt);
::vfprintf(stderr, fmt, ap);
va_end(ap);
}
// Perform fast exit.
::fflush(nullptr);
::quick_exit(static_cast<int>(code));
}
void
do_parse_command_line(int argc, char** argv)
{
bool help = false;
bool version = false;
opt<bool> daemonize;
opt<bool> verbose;
opt<cow_string> cd_here;
// Check for some common options before calling `getopt()`.
if(argc > 1) {
if(::strcmp(argv[1], "--help") == 0)
do_print_help_and_exit(argv[0]);
if(::strcmp(argv[1], "--version") == 0)
do_print_version_and_exit();
}
// Parse command-line options.
int ch;
while((ch = ::getopt(argc, argv, "+dhVv")) != -1) {
// Identify a single option.
switch(ch) {
case 'd':
daemonize = true;
continue;
case 'h':
help = true;
continue;
case 'V':
version = true;
continue;
case 'v':
verbose = true;
continue;
}
// `getopt()` will have written an error message to standard error.
do_exit(exit_invalid_argument, "Try `%s -h` for help.\n",
argv[0]);
}
// Check for early exit conditions.
if(help)
do_print_help_and_exit(argv[0]);
if(version)
do_print_version_and_exit();
// If more arguments follow, they denote the working directory.
if(argc - optind > 1)
do_exit(exit_invalid_argument, "%s: too many arguments -- '%s'\n"
"Try `%s -h` for help.\n",
argv[0], argv[optind+1],
argv[0]);
if(argc - optind > 0)
cd_here = cow_string(argv[optind]);
// Daemonization mode is off by default.
if(daemonize)
cmdline.daemonize = *daemonize;
// Verbose mode is off by default.
if(verbose)
cmdline.verbose = *verbose;
// The default working directory is empty which means 'do not switch'.
if(cd_here)
cmdline.cd_here = ::std::move(*cd_here);
}
} // namespace
int
main(int argc, char** argv)
try {
// Select the C locale.
// UTF-8 is required for wide-oriented standard streams.
::setlocale(LC_ALL, "C.UTF-8");
// Note that this function shall not return in case of errors.
do_parse_command_line(argc, argv);
// Set current working directory if one is specified.
if(cmdline.cd_here.size())
if(::chdir(cmdline.cd_here.safe_c_str()) != 0)
POSEIDON_THROW("could not set working directory to '$2'\n"
"[`chdir()` failed: $1]",
noadl::format_errno(errno), cmdline.cd_here);
// Load 'main.conf' before daemonization, so any earlier failures are
// visible to the user.
Main_Config::reload();
Async_Logger::reload();
Network_Driver::reload();
// Daemonize the process before entering modal loop.
if(cmdline.daemonize)
if(::daemon(1, 0) != 0)
POSEIDON_THROW("could not daemonize process\n"
"[`chdir()` failed: $1]",
noadl::format_errno(errno));
// Set name of the main thread. Failure to set the name is ignored.
::pthread_setname_np(::pthread_self(), "poseidon");
// Disable cancellation for safety. Failure to set the cancel state is ignored.
::pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, nullptr);
// Trap exit signals. Failure to set signal handlers is ignored.
// This also makes stdio functions fail immediately.
do_trap_exit_signal(SIGINT);
do_trap_exit_signal(SIGTERM);
do_trap_exit_signal(SIGHUP);
// Ignore `SIGPIPE` for good.
::signal(SIGPIPE, SIG_IGN);
// Start daemon threads.
Async_Logger::start();
Timer_Driver::start();
Network_Driver::start();
POSEIDON_LOG_INFO(PACKAGE_STRING " started up successfully (PID $1)", ::getpid());
sleep(10000);
do_exit(exit_success, "interrupt\n");
}
catch(exception& stdex) {
// Print the message in `stdex`. There isn't much we can do.
do_exit(exit_system_error, "%s\n[exception class `%s`]\n",
stdex.what(), typeid(stdex).name());
}
<|endoftext|> |
<commit_before>#include "python_plugin.hh"
#include "inifile.hh"
#include <stdio.h>
#include <stdlib.h>
#define MAX_ERRMSG_SIZE 256
#define ERRMSG(fmt, args...) \
do { \
char msgbuf[MAX_ERRMSG_SIZE]; \
snprintf(msgbuf, sizeof(msgbuf) -1, fmt, ##args); \
error_msg = std::string(msgbuf); \
} while(0)
#define logPP(level, fmt, ...) \
do { \
ERRMSG(fmt, ## __VA_ARGS__); \
if (log_level >= level) { \
fprintf(stderr, fmt, ## __VA_ARGS__); \
fprintf(stderr,"\n"); \
} \
} while (0)
extern const char *strstore(const char *s);
// http://hafizpariabi.blogspot.com/2008/01/using-custom-deallocator-in.html
// reason: avoid segfaults by del(interp_instance) on program exit
// make delete(interp_instance) a noop wrt Interp
// static void interpDeallocFunc(Interp *interp) {}
static void interpDeallocFunc(Interp *interp) {}
int PythonPlugin::run_string(const char *cmd, bp::object &retval, bool as_file)
{
if (reload_on_change)
reload();
try {
if (as_file)
retval = bp::exec_file(cmd, main_namespace, main_namespace);
else
retval = bp::exec(cmd, main_namespace, main_namespace);
status = PLUGIN_OK;
}
catch (bp::error_already_set) {
if (PyErr_Occurred()) {
exception_msg = handle_pyerror();
} else
exception_msg = "unknown exception";
status = PLUGIN_EXCEPTION;
bp::handle_exception();
PyErr_Clear();
}
if (status == PLUGIN_EXCEPTION) {
logPP(1, "run_string(%s): \n%s",
cmd, exception_msg.c_str());
}
return status;
}
int PythonPlugin::call(const char *module, const char *callable,
bp::object tupleargs, bp::object kwargs, bp::object &retval)
{
bp::object function;
if (callable == NULL)
return PLUGIN_NO_CALLABLE;
if (reload_on_change)
reload();
if (status < PLUGIN_OK)
return status;
try {
if (module == NULL) { // default to function in toplevel module
function = main_namespace[callable];
} else {
bp::object submod = main_namespace[module];
bp::object submod_namespace = submod.attr("__dict__");
function = submod_namespace[callable];
}
retval = function(*tupleargs, **kwargs);
status = PLUGIN_OK;
}
catch (bp::error_already_set) {
if (PyErr_Occurred()) {
exception_msg = handle_pyerror();
} else
exception_msg = "unknown exception";
status = PLUGIN_EXCEPTION;
bp::handle_exception();
PyErr_Clear();
}
if (status == PLUGIN_EXCEPTION) {
logPP(1, "call(%s.%s): \n%s",
module, callable, exception_msg.c_str());
}
return status;
}
bool PythonPlugin::is_callable(const char *module,
const char *funcname)
{
bool unexpected = false;
bool result = false;
bp::object function;
if (reload_on_change)
reload();
if ((status != PLUGIN_OK) ||
(funcname == NULL)) {
return false;
}
try {
if (module == NULL) { // default to function in toplevel module
function = main_namespace[funcname];
} else {
bp::object submod = main_namespace[module];
bp::object submod_namespace = submod.attr("__dict__");
function = submod_namespace[funcname];
}
result = PyCallable_Check(function.ptr());
}
catch (bp::error_already_set) {
// KeyError expected if not callable
if (!PyErr_ExceptionMatches(PyExc_KeyError)) {
// something else, strange
exception_msg = handle_pyerror();
unexpected = true;
}
result = false;
PyErr_Clear();
}
if (unexpected)
logPP(1, "is_callable(%s.%s): unexpected exception:\n%s",module,funcname,exception_msg.c_str());
if (log_level)
logPP(4, "is_callable(%s.%s) = %s", module ? module : "",funcname,result ? "TRUE":"FALSE");
return result;
}
int PythonPlugin::reload()
{
struct stat st;
if (stat(abs_path, &st)) {
logPP(1, "reload: stat(%s) returned %s", abs_path, strerror(errno));
status = PLUGIN_STAT_FAILED;
return status;
}
if (st.st_mtime > module_mtime) {
module_mtime = st.st_mtime;
initialize(true);
logPP(1, "reload(): module %s reloaded, status=%d", module_basename, status);
} else {
logPP(5, "reload: no-op");
status = PLUGIN_OK;
}
return status;
}
// decode a Python exception into a string.
// Free function usable without working plugin instance.
std::string handle_pyerror()
{
PyObject *exc, *val, *tb;
bp::object formatted_list, formatted;
PyErr_Fetch(&exc, &val, &tb);
bp::handle<> hexc(exc), hval(bp::allow_null(val)), htb(bp::allow_null(tb));
bp::object traceback(bp::import("traceback"));
if (!tb) {
bp::object format_exception_only(traceback.attr("format_exception_only"));
formatted_list = format_exception_only(hexc, hval);
} else {
bp::object format_exception(traceback.attr("format_exception"));
formatted_list = format_exception(hexc, hval, htb);
}
formatted = bp::str("\n").join(formatted_list);
return bp::extract<std::string>(formatted);
}
void PythonPlugin::initialize(bool reload, Interp *interp )
{
std::string msg;
if (Py_IsInitialized()) {
try {
bp::object module = bp::import("__main__");
main_namespace = module.attr("__dict__");
for(unsigned i = 0; i < inittab_entries.size(); i++) {
main_namespace[inittab_entries[i]] = bp::import(inittab_entries[i].c_str());
}
if (interp != NULL) {
bp::object interp_module = bp::import("interpreter");
bp::scope(interp_module).attr("this") = interp_ptr(interp, interpDeallocFunc);
}
bp::object result = bp::exec_file(abs_path,
main_namespace,
main_namespace);
status = PLUGIN_OK;
}
catch (bp::error_already_set) {
if (PyErr_Occurred()) {
exception_msg = handle_pyerror();
} else
exception_msg = "unknown exception";
bp::handle_exception();
status = PLUGIN_INIT_EXCEPTION;
PyErr_Clear();
}
if (status == PLUGIN_INIT_EXCEPTION) {
logPP(1, "initialize: module '%s' init failed: \n%s",
abs_path, exception_msg.c_str());
}
} else {
status = PLUGIN_PYTHON_NOT_INITIALIZED;
}
}
PythonPlugin::PythonPlugin(const char *iniFilename,
const char *section,
struct _inittab *inittab,
Interp *interp)
{
IniFile inifile;
const char *inistring;
if (section == NULL) {
logPP(1, "no section");
status = PLUGIN_NO_SECTION;
return;
}
if ((iniFilename == NULL) &&
((iniFilename = getenv("INI_FILE_NAME")) == NULL)) {
logPP(1, "no inifile");
status = PLUGIN_NO_INIFILE;
return;
}
if (inifile.Open(iniFilename) == false) {
logPP(1, "Unable to open inifile:%s:\n", iniFilename);
status = PLUGIN_BAD_INIFILE;
return;
}
if ((inistring = inifile.Find("PLUGIN_DIR", section)) != NULL)
plugin_dir = strstore(inistring);
else {
logPP(1, "no PLUGIN_DIR in inifile:%s:\n", iniFilename);
status = PLUGIN_NO_PLUGIN_DIR;
return;
}
if ((inistring = inifile.Find("MODULE_BASENAME", section)) != NULL)
module_basename = strstore(inistring);
else {
logPP(1, "no MODULE_BASENAME in inifile:%s:\n", iniFilename);
status = PLUGIN_NO_MODULE_BASENAME;
return;
}
if ((inistring = inifile.Find("RELOAD_ON_CHANGE", section)) != NULL)
reload_on_change = (atoi(inistring) > 0);
if ((inistring = inifile.Find("LOG_LEVEL", section)) != NULL)
log_level = atoi(inistring);
inifile.Close();
char module_path[PATH_MAX];
strcpy(module_path, plugin_dir );
strcat(module_path,"/");
strcat(module_path, module_basename);
strcat(module_path,".py");
char real_path[PATH_MAX];
if (realpath(module_path, real_path) == NULL) {
logPP(1, "cant resolve path to '%s'", module_path);
status = PLUGIN_BAD_PATH;
return;
}
struct stat st;
if (stat(real_path, &st)) {
logPP(1, "stat(%s) returns %s", real_path, strerror(errno));
status = PLUGIN_STAT_FAILED;
return;
}
abs_path = strstore(real_path);
module_mtime = st.st_mtime; // record timestamp
Py_SetProgramName((char *) abs_path);
if ((inittab != NULL) &&
PyImport_ExtendInittab(inittab)) {
logPP(1, "cant extend inittab");
status = PLUGIN_INITTAB_FAILED;
return;
}
Py_Initialize();
char pathcmd[PATH_MAX];
sprintf(pathcmd, "import sys\nsys.path.insert(0,\"%s\")", plugin_dir);
if (PyRun_SimpleString(pathcmd)) {
logPP(1, "exeception running '%s'", pathcmd);
exception_msg = "exeception running "; // + pathcmd;
status = PLUGIN_EXCEPTION_DURING_PATH_APPEND;
return;
}
logPP(3,"PythonPlugin: Python '%s'", Py_GetVersion());
initialize(false, interp);
}
// the externally visible singleton instance
PythonPlugin *python_plugin;
// first caller wins
PythonPlugin *PythonPlugin::configure(const char *iniFilename,
const char *section,
struct _inittab *inittab,Interp *interp)
{
if (python_plugin == NULL) {
python_plugin = new PythonPlugin(iniFilename, section, inittab, interp);
}
return (python_plugin->usable()) ? python_plugin : NULL;
}
<commit_msg>python_plugin: properly init log_level<commit_after>#include "python_plugin.hh"
#include "inifile.hh"
#include <stdio.h>
#include <stdlib.h>
#define MAX_ERRMSG_SIZE 256
#define ERRMSG(fmt, args...) \
do { \
char msgbuf[MAX_ERRMSG_SIZE]; \
snprintf(msgbuf, sizeof(msgbuf) -1, fmt, ##args); \
error_msg = std::string(msgbuf); \
} while(0)
#define logPP(level, fmt, ...) \
do { \
ERRMSG(fmt, ## __VA_ARGS__); \
if (log_level >= level) { \
fprintf(stderr, fmt, ## __VA_ARGS__); \
fprintf(stderr,"\n"); \
} \
} while (0)
extern const char *strstore(const char *s);
// http://hafizpariabi.blogspot.com/2008/01/using-custom-deallocator-in.html
// reason: avoid segfaults by del(interp_instance) on program exit
// make delete(interp_instance) a noop wrt Interp
// static void interpDeallocFunc(Interp *interp) {}
static void interpDeallocFunc(Interp *interp) {}
int PythonPlugin::run_string(const char *cmd, bp::object &retval, bool as_file)
{
if (reload_on_change)
reload();
try {
if (as_file)
retval = bp::exec_file(cmd, main_namespace, main_namespace);
else
retval = bp::exec(cmd, main_namespace, main_namespace);
status = PLUGIN_OK;
}
catch (bp::error_already_set) {
if (PyErr_Occurred()) {
exception_msg = handle_pyerror();
} else
exception_msg = "unknown exception";
status = PLUGIN_EXCEPTION;
bp::handle_exception();
PyErr_Clear();
}
if (status == PLUGIN_EXCEPTION) {
logPP(1, "run_string(%s): \n%s",
cmd, exception_msg.c_str());
}
return status;
}
int PythonPlugin::call(const char *module, const char *callable,
bp::object tupleargs, bp::object kwargs, bp::object &retval)
{
bp::object function;
if (callable == NULL)
return PLUGIN_NO_CALLABLE;
if (reload_on_change)
reload();
if (status < PLUGIN_OK)
return status;
try {
if (module == NULL) { // default to function in toplevel module
function = main_namespace[callable];
} else {
bp::object submod = main_namespace[module];
bp::object submod_namespace = submod.attr("__dict__");
function = submod_namespace[callable];
}
retval = function(*tupleargs, **kwargs);
status = PLUGIN_OK;
}
catch (bp::error_already_set) {
if (PyErr_Occurred()) {
exception_msg = handle_pyerror();
} else
exception_msg = "unknown exception";
status = PLUGIN_EXCEPTION;
bp::handle_exception();
PyErr_Clear();
}
if (status == PLUGIN_EXCEPTION) {
logPP(1, "call(%s.%s): \n%s",
module, callable, exception_msg.c_str());
}
return status;
}
bool PythonPlugin::is_callable(const char *module,
const char *funcname)
{
bool unexpected = false;
bool result = false;
bp::object function;
if (reload_on_change)
reload();
if ((status != PLUGIN_OK) ||
(funcname == NULL)) {
return false;
}
try {
if (module == NULL) { // default to function in toplevel module
function = main_namespace[funcname];
} else {
bp::object submod = main_namespace[module];
bp::object submod_namespace = submod.attr("__dict__");
function = submod_namespace[funcname];
}
result = PyCallable_Check(function.ptr());
}
catch (bp::error_already_set) {
// KeyError expected if not callable
if (!PyErr_ExceptionMatches(PyExc_KeyError)) {
// something else, strange
exception_msg = handle_pyerror();
unexpected = true;
}
result = false;
PyErr_Clear();
}
if (unexpected)
logPP(1, "is_callable(%s.%s): unexpected exception:\n%s",module,funcname,exception_msg.c_str());
if (log_level)
logPP(4, "is_callable(%s.%s) = %s", module ? module : "",funcname,result ? "TRUE":"FALSE");
return result;
}
int PythonPlugin::reload()
{
struct stat st;
if (stat(abs_path, &st)) {
logPP(1, "reload: stat(%s) returned %s", abs_path, strerror(errno));
status = PLUGIN_STAT_FAILED;
return status;
}
if (st.st_mtime > module_mtime) {
module_mtime = st.st_mtime;
initialize(true);
logPP(1, "reload(): module %s reloaded, status=%d", module_basename, status);
} else {
logPP(5, "reload: no-op");
status = PLUGIN_OK;
}
return status;
}
// decode a Python exception into a string.
// Free function usable without working plugin instance.
std::string handle_pyerror()
{
PyObject *exc, *val, *tb;
bp::object formatted_list, formatted;
PyErr_Fetch(&exc, &val, &tb);
bp::handle<> hexc(exc), hval(bp::allow_null(val)), htb(bp::allow_null(tb));
bp::object traceback(bp::import("traceback"));
if (!tb) {
bp::object format_exception_only(traceback.attr("format_exception_only"));
formatted_list = format_exception_only(hexc, hval);
} else {
bp::object format_exception(traceback.attr("format_exception"));
formatted_list = format_exception(hexc, hval, htb);
}
formatted = bp::str("\n").join(formatted_list);
return bp::extract<std::string>(formatted);
}
void PythonPlugin::initialize(bool reload, Interp *interp )
{
std::string msg;
if (Py_IsInitialized()) {
try {
bp::object module = bp::import("__main__");
main_namespace = module.attr("__dict__");
for(unsigned i = 0; i < inittab_entries.size(); i++) {
main_namespace[inittab_entries[i]] = bp::import(inittab_entries[i].c_str());
}
if (interp != NULL) {
bp::object interp_module = bp::import("interpreter");
bp::scope(interp_module).attr("this") = interp_ptr(interp, interpDeallocFunc);
}
bp::object result = bp::exec_file(abs_path,
main_namespace,
main_namespace);
status = PLUGIN_OK;
}
catch (bp::error_already_set) {
if (PyErr_Occurred()) {
exception_msg = handle_pyerror();
} else
exception_msg = "unknown exception";
bp::handle_exception();
status = PLUGIN_INIT_EXCEPTION;
PyErr_Clear();
}
if (status == PLUGIN_INIT_EXCEPTION) {
logPP(1, "initialize: module '%s' init failed: \n%s",
abs_path, exception_msg.c_str());
}
} else {
status = PLUGIN_PYTHON_NOT_INITIALIZED;
}
}
PythonPlugin::PythonPlugin(const char *iniFilename,
const char *section,
struct _inittab *inittab,
Interp *interp) :
log_level(0)
{
IniFile inifile;
const char *inistring;
if (section == NULL) {
logPP(1, "no section");
status = PLUGIN_NO_SECTION;
return;
}
if ((iniFilename == NULL) &&
((iniFilename = getenv("INI_FILE_NAME")) == NULL)) {
logPP(1, "no inifile");
status = PLUGIN_NO_INIFILE;
return;
}
if (inifile.Open(iniFilename) == false) {
logPP(1, "Unable to open inifile:%s:\n", iniFilename);
status = PLUGIN_BAD_INIFILE;
return;
}
if ((inistring = inifile.Find("PLUGIN_DIR", section)) != NULL)
plugin_dir = strstore(inistring);
else {
logPP(3, "no PLUGIN_DIR in inifile:%s:\n", iniFilename);
status = PLUGIN_NO_PLUGIN_DIR;
return;
}
if ((inistring = inifile.Find("MODULE_BASENAME", section)) != NULL)
module_basename = strstore(inistring);
else {
logPP(1, "no MODULE_BASENAME in inifile:%s:\n", iniFilename);
status = PLUGIN_NO_MODULE_BASENAME;
return;
}
if ((inistring = inifile.Find("RELOAD_ON_CHANGE", section)) != NULL)
reload_on_change = (atoi(inistring) > 0);
if ((inistring = inifile.Find("LOG_LEVEL", section)) != NULL)
log_level = atoi(inistring);
inifile.Close();
char module_path[PATH_MAX];
strcpy(module_path, plugin_dir );
strcat(module_path,"/");
strcat(module_path, module_basename);
strcat(module_path,".py");
char real_path[PATH_MAX];
if (realpath(module_path, real_path) == NULL) {
logPP(1, "cant resolve path to '%s'", module_path);
status = PLUGIN_BAD_PATH;
return;
}
struct stat st;
if (stat(real_path, &st)) {
logPP(1, "stat(%s) returns %s", real_path, strerror(errno));
status = PLUGIN_STAT_FAILED;
return;
}
abs_path = strstore(real_path);
module_mtime = st.st_mtime; // record timestamp
Py_SetProgramName((char *) abs_path);
if ((inittab != NULL) &&
PyImport_ExtendInittab(inittab)) {
logPP(1, "cant extend inittab");
status = PLUGIN_INITTAB_FAILED;
return;
}
Py_Initialize();
char pathcmd[PATH_MAX];
sprintf(pathcmd, "import sys\nsys.path.insert(0,\"%s\")", plugin_dir);
if (PyRun_SimpleString(pathcmd)) {
logPP(1, "exeception running '%s'", pathcmd);
exception_msg = "exeception running "; // + pathcmd;
status = PLUGIN_EXCEPTION_DURING_PATH_APPEND;
return;
}
logPP(3,"PythonPlugin: Python '%s'", Py_GetVersion());
initialize(false, interp);
}
// the externally visible singleton instance
PythonPlugin *python_plugin;
// first caller wins
PythonPlugin *PythonPlugin::configure(const char *iniFilename,
const char *section,
struct _inittab *inittab,Interp *interp)
{
if (python_plugin == NULL) {
python_plugin = new PythonPlugin(iniFilename, section, inittab, interp);
}
return (python_plugin->usable()) ? python_plugin : NULL;
}
<|endoftext|> |
<commit_before>/** \copyright
* Copyright (c) 2015, Balazs Racz
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* \file Stm32Gpio.hxx
*
* Helper declarations for using GPIO pins (both for GPIO and other hardware)
* on STM32 microcontrollers.
*
* @author Balazs Racz
* @date 24 Aug 2015
*/
#ifndef _FREERTOS_DRIVERS_ST_STM32GPIO_HXX_
#define _FREERTOS_DRIVERS_ST_STM32GPIO_HXX_
#include "os/Gpio.hxx"
#include "GpioWrapper.hxx"
#if defined(STM32F072xB) || defined(STM32F091xC)
#include "stm32f0xx_hal_gpio.h"
#elif defined(STM32F103xB)
#include "stm32f1xx_hal_gpio.h"
#elif defined(STM32F303xC)
#include "stm32f3xx_hal_gpio.h"
#else
#error Dont know what STM32 chip you have.
#endif
/// Static GPIO implementation for the STM32 microcontrollers. Do not use
/// directly: use @ref GPIO_PIN macro.
/// @param PORT is the port base address pointer (e.g. GPIOC)
/// @param PIN is the GPIO_PIN_# value for the pin number.
/// @param PIN_NUM is the number of the pin in the port. Zero-based.
template <uint32_t GPIOx, uint16_t PIN, uint8_t PIN_NUM> struct Stm32GpioDefs
{
/// @return the PIO structure of the give gpio port.
static GPIO_TypeDef *port()
{
return (GPIO_TypeDef *)GPIOx;
}
/// @return the pin number within the port.
static uint16_t pin()
{
return PIN;
}
/// Sets the output pin to a given level.
static void set(bool value)
{
if (value)
{
#if defined(STM32F303xC)
port()->BSRRL = pin();
#else
port()->BSRR = pin();
#endif
}
else
{
#if defined(STM32F303xC)
port()->BSRRH = pin();
#else
port()->BSRR = pin() << 16;
#endif
}
}
/// Sets the output pin to a given level.
static bool get()
{
return port()->IDR & pin();
}
/// @return a os-indepentent Gpio abstraction instance for use in
/// libraries.
static constexpr const Gpio *instance()
{
return GpioWrapper<Stm32GpioDefs<GPIOx, PIN, PIN_NUM>>::instance();
}
/// @return whether this pin is configured as an output.
static bool is_output()
{
uint8_t* mode = (uint8_t*)port();
uint8_t m = mode[PIN_NUM >> 1];
if (PIN_NUM & 1) { m >>= 4; }
return (m & 3) != 0;
}
};
template <class Defs, bool SAFE_VALUE> struct GpioOutputPin : public Defs
{
using Defs::port;
using Defs::pin;
using Defs::set;
/// Initializes the hardware pin.
static void hw_init()
{
GPIO_InitTypeDef gpio_init = {0};
gpio_init.Pin = pin();
gpio_init.Mode = GPIO_MODE_OUTPUT_PP;
gpio_init.Pull = GPIO_NOPULL;
gpio_init.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(port(), &gpio_init);
}
/// Sets the output pin to a safe value.
static void hw_set_to_safe()
{
hw_init();
set(SAFE_VALUE);
}
};
/// Defines a GPIO output pin, initialized to be an output pin with low level.
///
/// Do not use this class directly. Use @ref GPIO_PIN instead.
template <class Defs>
struct GpioOutputSafeLow : public GpioOutputPin<Defs, false>
{
};
/// Defines a GPIO output pin, initialized to be an output pin with high level.
///
/// Do not use this class directly. Use @ref GPIO_PIN instead.
template <class Defs>
struct GpioOutputSafeHigh : public GpioOutputPin<Defs, true>
{
};
/// Defines a GPIO output pin for driving an LED. The MCU must be in spec for
/// the necessary output current.
///
/// Do not use this class directly. Use @ref GPIO_PIN instead.
template <class Defs> struct LedPin : public GpioOutputPin<Defs, false>
{
};
template <class Defs, uint32_t PULL_MODE> struct GpioInputPin : public Defs
{
using Defs::port;
using Defs::pin;
using Defs::set;
/// Initializes the hardware pin.
static void hw_init()
{
GPIO_InitTypeDef gpio_init = {0};
gpio_init.Pin = pin();
gpio_init.Mode = GPIO_MODE_INPUT;
gpio_init.Pull = PULL_MODE;
gpio_init.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(port(), &gpio_init);
}
/// Sets the hardware pin to a safe state.
static void hw_set_to_safe()
{
hw_init();
}
/// @return true if the pin is set to drive an output.
static bool is_output()
{
return false;
}
};
/// GPIO Input pin with weak pull up.
///
/// Do not use this class directly. Use @ref GPIO_PIN instead.
template <class Defs>
struct GpioInputPU : public GpioInputPin<Defs, GPIO_PULLUP>
{
};
/// GPIO Input pin with weak pull down.
///
/// Do not use this class directly. Use @ref GPIO_PIN instead.
template <class Defs>
struct GpioInputPD : public GpioInputPin<Defs, GPIO_PULLDOWN>
{
};
/// GPIO Input pin in standard configuration (no pull).
///
/// Do not use this class directly. Use @ref GPIO_PIN instead.
template <class Defs>
struct GpioInputNP : public GpioInputPin<Defs, GPIO_NOPULL>
{
};
/// Helper macro for defining GPIO pins.
///
/// @param NAME is the basename of the declaration. For NAME==FOO the macro
/// declares FOO_Pin as a structure on which the read-write functions will be
/// available.
///
/// @param BaseClass is the initialization structure, such as @ref LedPin, or
/// @ref GpioOutputSafeHigh or @ref GpioOutputSafeLow.
///
/// @param PORTNAME is a letter defining which port this is (like A, B,
/// C). E.g. for PC8 this is C.
///
/// @param NUM is the pin number, such as 8 for PC8.
///
/// Example:
/// GPIO_PIN(FOO, LedPin, 0, 3);
/// ...
/// FOO_Pin::set(true);
#define GPIO_PIN(NAME, BaseClass, PORTNAME, NUM) \
typedef BaseClass<Stm32GpioDefs<(uint32_t)(GPIO ## PORTNAME ## _BASE), GPIO_PIN_ ## NUM, NUM>> NAME##_Pin
#endif // _FREERTOS_DRIVERS_ST_STM32GPIO_HXX_
<commit_msg>Fixes bug in STM32 GPIO driver that SafeHIgh and SafeLOw for outputs were not taken into account when booting.<commit_after>/** \copyright
* Copyright (c) 2015, Balazs Racz
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* \file Stm32Gpio.hxx
*
* Helper declarations for using GPIO pins (both for GPIO and other hardware)
* on STM32 microcontrollers.
*
* @author Balazs Racz
* @date 24 Aug 2015
*/
#ifndef _FREERTOS_DRIVERS_ST_STM32GPIO_HXX_
#define _FREERTOS_DRIVERS_ST_STM32GPIO_HXX_
#include "os/Gpio.hxx"
#include "GpioWrapper.hxx"
#if defined(STM32F072xB) || defined(STM32F091xC)
#include "stm32f0xx_hal_gpio.h"
#elif defined(STM32F103xB)
#include "stm32f1xx_hal_gpio.h"
#elif defined(STM32F303xC)
#include "stm32f3xx_hal_gpio.h"
#else
#error Dont know what STM32 chip you have.
#endif
/// Static GPIO implementation for the STM32 microcontrollers. Do not use
/// directly: use @ref GPIO_PIN macro.
/// @param PORT is the port base address pointer (e.g. GPIOC)
/// @param PIN is the GPIO_PIN_# value for the pin number.
/// @param PIN_NUM is the number of the pin in the port. Zero-based.
template <uint32_t GPIOx, uint16_t PIN, uint8_t PIN_NUM> struct Stm32GpioDefs
{
/// @return the PIO structure of the give gpio port.
static GPIO_TypeDef *port()
{
return (GPIO_TypeDef *)GPIOx;
}
/// @return the pin number within the port.
static uint16_t pin()
{
return PIN;
}
/// Sets the output pin to a given level.
static void set(bool value)
{
if (value)
{
#if defined(STM32F303xC)
port()->BSRRL = pin();
#else
port()->BSRR = pin();
#endif
}
else
{
#if defined(STM32F303xC)
port()->BSRRH = pin();
#else
port()->BSRR = pin() << 16;
#endif
}
}
/// Sets the output pin to a given level.
static bool get()
{
return port()->IDR & pin();
}
/// @return a os-indepentent Gpio abstraction instance for use in
/// libraries.
static constexpr const Gpio *instance()
{
return GpioWrapper<Stm32GpioDefs<GPIOx, PIN, PIN_NUM>>::instance();
}
/// @return whether this pin is configured as an output.
static bool is_output()
{
uint8_t* mode = (uint8_t*)port();
uint8_t m = mode[PIN_NUM >> 1];
if (PIN_NUM & 1) { m >>= 4; }
return (m & 3) != 0;
}
};
template <class Defs, bool SAFE_VALUE> struct GpioOutputPin : public Defs
{
using Defs::port;
using Defs::pin;
using Defs::set;
/// Initializes the hardware pin.
static void hw_init()
{
GPIO_InitTypeDef gpio_init = {0};
gpio_init.Pin = pin();
gpio_init.Mode = GPIO_MODE_OUTPUT_PP;
gpio_init.Pull = GPIO_NOPULL;
gpio_init.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(port(), &gpio_init);
set(SAFE_VALUE);
}
/// Sets the output pin to a safe value.
static void hw_set_to_safe()
{
hw_init();
set(SAFE_VALUE);
}
};
/// Defines a GPIO output pin, initialized to be an output pin with low level.
///
/// Do not use this class directly. Use @ref GPIO_PIN instead.
template <class Defs>
struct GpioOutputSafeLow : public GpioOutputPin<Defs, false>
{
};
/// Defines a GPIO output pin, initialized to be an output pin with high level.
///
/// Do not use this class directly. Use @ref GPIO_PIN instead.
template <class Defs>
struct GpioOutputSafeHigh : public GpioOutputPin<Defs, true>
{
};
/// Defines a GPIO output pin for driving an LED. The MCU must be in spec for
/// the necessary output current.
///
/// Do not use this class directly. Use @ref GPIO_PIN instead.
template <class Defs> struct LedPin : public GpioOutputPin<Defs, false>
{
};
template <class Defs, uint32_t PULL_MODE> struct GpioInputPin : public Defs
{
using Defs::port;
using Defs::pin;
using Defs::set;
/// Initializes the hardware pin.
static void hw_init()
{
GPIO_InitTypeDef gpio_init = {0};
gpio_init.Pin = pin();
gpio_init.Mode = GPIO_MODE_INPUT;
gpio_init.Pull = PULL_MODE;
gpio_init.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(port(), &gpio_init);
}
/// Sets the hardware pin to a safe state.
static void hw_set_to_safe()
{
hw_init();
}
/// @return true if the pin is set to drive an output.
static bool is_output()
{
return false;
}
};
/// GPIO Input pin with weak pull up.
///
/// Do not use this class directly. Use @ref GPIO_PIN instead.
template <class Defs>
struct GpioInputPU : public GpioInputPin<Defs, GPIO_PULLUP>
{
};
/// GPIO Input pin with weak pull down.
///
/// Do not use this class directly. Use @ref GPIO_PIN instead.
template <class Defs>
struct GpioInputPD : public GpioInputPin<Defs, GPIO_PULLDOWN>
{
};
/// GPIO Input pin in standard configuration (no pull).
///
/// Do not use this class directly. Use @ref GPIO_PIN instead.
template <class Defs>
struct GpioInputNP : public GpioInputPin<Defs, GPIO_NOPULL>
{
};
/// Helper macro for defining GPIO pins.
///
/// @param NAME is the basename of the declaration. For NAME==FOO the macro
/// declares FOO_Pin as a structure on which the read-write functions will be
/// available.
///
/// @param BaseClass is the initialization structure, such as @ref LedPin, or
/// @ref GpioOutputSafeHigh or @ref GpioOutputSafeLow.
///
/// @param PORTNAME is a letter defining which port this is (like A, B,
/// C). E.g. for PC8 this is C.
///
/// @param NUM is the pin number, such as 8 for PC8.
///
/// Example:
/// GPIO_PIN(FOO, LedPin, 0, 3);
/// ...
/// FOO_Pin::set(true);
#define GPIO_PIN(NAME, BaseClass, PORTNAME, NUM) \
typedef BaseClass<Stm32GpioDefs<(uint32_t)(GPIO ## PORTNAME ## _BASE), GPIO_PIN_ ## NUM, NUM>> NAME##_Pin
#endif // _FREERTOS_DRIVERS_ST_STM32GPIO_HXX_
<|endoftext|> |
<commit_before>#include <gflags/gflags.h>
#include <stddef.h>
#include <algorithm>
#include <chrono>
#include <iostream>
#include <map>
#include <memory>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
#include "ncode_common/src/common.h"
#include "ncode_common/src/map_util.h"
#include "ncode_common/src/net/net_common.h"
#include "ncode_common/src/net/net_gen.h"
#include "ncode_common/src/strutil.h"
#include "ncode_common/src/viz/grapher.h"
#include "../common.h"
#include "../mean_est/mean_est.h"
#include "../routing_system.h"
#include "ctr.h"
#include "path_provider.h"
DEFINE_double(cd_link_gbps, 1.0, "Capacity of C->D");
DEFINE_double(ab_link_gbps, 1.0, "Capacity of A->B");
DEFINE_double(cd_link_ms, 10, "Delay of C->D");
DEFINE_double(ab_link_ms, 10, "Delay of A->B");
DEFINE_double(cd_aggregate_gbps, 0.9, "Demand of C->D aggregate");
DEFINE_double(ab_aggregate_gbps, 0.9, "Demand of A->B aggregate");
DEFINE_uint64(cd_aggregate_flows, 1000, "Number of C->D flows");
DEFINE_uint64(ab_aggregate_flows, 1000, "Number of A->B flows");
DEFINE_uint64(steps, 20, "Number of steps");
DEFINE_double(decay_factor, 0.0, "How quickly to decay prediction");
DEFINE_string(opt, "CTR", "The optimizer to use");
DEFINE_bool(dampen_ratio, false, "Preserve the flow count / volume ratio?");
namespace ctr {
static constexpr std::chrono::milliseconds kSyntheticBinSize =
std::chrono::milliseconds(10);
static constexpr size_t kSyntheticBinCount = 600;
class StabilityEvalHarness {
public:
StabilityEvalHarness(TrafficMatrix* initial_tm, RoutingSystem* routing_system,
size_t cycle_count)
: initial_tm_(initial_tm),
routing_system_(routing_system),
graph_(routing_system_->graph()) {
Cycle(cycle_count);
}
const std::vector<RoutingConfigurationDelta>& deltas() const {
return deltas_;
}
void PlotLinkFractions(const std::string& out) const {
std::vector<nc::viz::DataSeries2D> series;
for (const auto& path_and_fractions : path_to_fraction_) {
const nc::net::Walk* walk = path_and_fractions.first;
series.emplace_back();
nc::viz::DataSeries2D& data_series = series.back();
data_series.data = path_and_fractions.second;
data_series.label = walk->ToStringNoPorts(*graph_);
}
nc::viz::PlotParameters2D params;
params.x_label = "timestep";
params.y_label = "fraction";
nc::viz::PythonGrapher grapher(out);
grapher.PlotLine(params, series);
}
void DumpLinkFractions() const {
std::cout << path_to_fraction_.size() << "\n";
for (const auto& path_and_fractions : path_to_fraction_) {
const nc::net::Walk* walk = path_and_fractions.first;
std::vector<std::string> to_combine;
for (const auto& times_and_fractions : path_and_fractions.second) {
to_combine.emplace_back(nc::StrCat("(", times_and_fractions.first, ",",
times_and_fractions.second, ")"));
}
std::cout << walk->ToStringNoPorts(*graph_) << " : ("
<< nc::Join(to_combine, ",") << ")\n";
}
}
void DumpAggregateVolumes() const {
std::cout << volumes_.size() << "\n";
for (const auto& aggregate_and_volumes : volumes_) {
const AggregateId& aggregate_id = aggregate_and_volumes.first;
const std::vector<nc::net::Bandwidth>& volumes =
aggregate_and_volumes.second;
std::string out = nc::Join(volumes, ",", [](nc::net::Bandwidth v) {
return std::to_string(v.Mbps());
});
std::cout << aggregate_id.ToString(*graph_) << " : (" << out << ")\n";
}
}
private:
// Produces a traffic matrix that is scaled based on each flow's shortest path
// stretch. If all flows of an aggregate are on a path that is 2x as long as
// the shortest path then their demand will be 1/2 of what it would be if they
// were on the shortest path.
std::unique_ptr<TrafficMatrix> ScaleBasedOnOutput(
const RoutingConfiguration& routing,
const TrafficMatrix& original_tm) const {
std::map<AggregateId, DemandAndFlowCount> out;
for (const auto& aggregate_and_routes : routing.routes()) {
const AggregateId& aggregate_id = aggregate_and_routes.first;
const DemandAndFlowCount& demand_and_flow_count =
nc::FindOrDieNoPrint(routing.demands(), aggregate_id);
const DemandAndFlowCount& initial_demand_and_flow_count =
nc::FindOrDieNoPrint(initial_tm_->demands(), aggregate_id);
size_t flow_count = demand_and_flow_count.second;
nc::net::Bandwidth sp_bandwidth = initial_demand_and_flow_count.first;
nc::net::Delay sp_delay = aggregate_id.GetSPDelay(*graph_);
double total_mbps = 0;
double per_flow_sp_mbps = sp_bandwidth.Mbps() / flow_count;
const std::vector<RouteAndFraction>& routes = aggregate_and_routes.second;
for (const RouteAndFraction& route_and_fraction : routes) {
nc::net::Delay path_delay = route_and_fraction.first->delay();
double sp_ratio =
static_cast<double>(sp_delay.count()) / path_delay.count();
// Each flow in the aggregate will get bandwidth proportional to how far
// away it is from the shortest path.
total_mbps += route_and_fraction.second * flow_count * sp_ratio *
per_flow_sp_mbps;
CHECK(total_mbps == total_mbps);
}
std::mt19937 rnd(1);
std::uniform_real_distribution<double> dist(1, 10);
double new_flow_count = flow_count;
if (FLAGS_dampen_ratio) {
// The demand in the output will not be the same as the one in the input
// to the optimizer because of prediction. Need to dampen the ratio
// based on the original input, not the predicted one.
const DemandAndFlowCount& original_demand_and_flow_count =
nc::FindOrDieNoPrint(original_tm.demands(), aggregate_id);
new_flow_count = total_mbps * flow_count /
original_demand_and_flow_count.first.Mbps();
new_flow_count = std::max(1.0, new_flow_count);
}
out[aggregate_id] = {nc::net::Bandwidth::FromMBitsPerSecond(total_mbps),
new_flow_count};
}
return nc::make_unique<TrafficMatrix>(graph_, out);
}
// Performs a number of runs with the optimizer. Returns n - 1 values, one for
// each delta between a run and its following run.
void Cycle(size_t n) {
std::unique_ptr<TrafficMatrix> prev_tm;
std::unique_ptr<RoutingConfiguration> prev_routing;
for (size_t i = 0; i < n; ++i) {
const TrafficMatrix* tm = prev_tm ? prev_tm.get() : initial_tm_;
UpdateVolumes(*tm);
RoutingSystemUpdateResult update_result =
routing_system_->Update(SyntheticHistoryFromTM(*tm));
auto& routing = update_result.routing;
for (const auto& aggregate_and_routes : routing->routes()) {
for (const auto& path_and_fraction : aggregate_and_routes.second) {
path_to_fraction_[path_and_fraction.first].emplace_back(
i, path_and_fraction.second);
}
}
if (prev_routing) {
deltas_.emplace_back(prev_routing->GetDifference(*routing));
}
prev_tm = ScaleBasedOnOutput(*routing, *tm);
prev_routing = std::move(routing);
}
}
void UpdateVolumes(const TrafficMatrix& tm) {
for (const auto& aggregate_and_demands : tm.demands()) {
const AggregateId& aggregate = aggregate_and_demands.first;
volumes_[aggregate].emplace_back(aggregate_and_demands.second.first);
}
}
std::map<AggregateId, AggregateHistory> SyntheticHistoryFromTM(
const TrafficMatrix& tm) {
std::map<AggregateId, AggregateHistory> out;
for (const auto& aggregate_demand_and_flow_count : tm.demands()) {
const AggregateId& aggregate = aggregate_demand_and_flow_count.first;
nc::net::Bandwidth demand = aggregate_demand_and_flow_count.second.first;
size_t flow_count = aggregate_demand_and_flow_count.second.second;
out.emplace(std::piecewise_construct, std::forward_as_tuple(aggregate),
std::forward_as_tuple(demand, kSyntheticBinCount,
kSyntheticBinSize, flow_count));
}
return out;
}
// In the initial TM each aggregate's demand is what it would be if it were
// routed on its shortest path.
TrafficMatrix* initial_tm_;
// The optimizer.
RoutingSystem* routing_system_;
// The graph.
const nc::net::GraphStorage* graph_;
// N - 1 deltas for each step to the next one.
std::vector<RoutingConfigurationDelta> deltas_;
// Per-aggregate volumes.
std::map<AggregateId, std::vector<nc::net::Bandwidth>> volumes_;
// Path to fractions of capacity.
std::map<const nc::net::Walk*, std::vector<std::pair<double, double>>>
path_to_fraction_;
};
static void RunWithSimpleTopologyTwoAggregates() {
nc::net::GraphBuilder builder;
std::chrono::microseconds ab_delay(
static_cast<size_t>(FLAGS_ab_link_ms * 1000));
std::chrono::microseconds cd_delay(
static_cast<size_t>(FLAGS_cd_link_ms * 1000));
builder.AddLink({"A", "B",
nc::net::Bandwidth::FromGBitsPerSecond(FLAGS_ab_link_gbps),
ab_delay});
builder.AddLink({"B", "A",
nc::net::Bandwidth::FromGBitsPerSecond(FLAGS_ab_link_gbps),
ab_delay});
builder.AddLink({"A", "C", nc::net::Bandwidth::FromGBitsPerSecond(1),
std::chrono::milliseconds(1)});
builder.AddLink({"C", "A", nc::net::Bandwidth::FromGBitsPerSecond(1),
std::chrono::milliseconds(1)});
builder.AddLink({"C", "D",
nc::net::Bandwidth::FromGBitsPerSecond(FLAGS_cd_link_gbps),
cd_delay});
builder.AddLink({"D", "C",
nc::net::Bandwidth::FromGBitsPerSecond(FLAGS_cd_link_gbps),
cd_delay});
builder.AddLink({"B", "D", nc::net::Bandwidth::FromGBitsPerSecond(1),
std::chrono::milliseconds(1)});
builder.AddLink({"D", "B", nc::net::Bandwidth::FromGBitsPerSecond(1),
std::chrono::milliseconds(1)});
nc::net::GraphStorage graph(builder);
TrafficMatrix initial_tm(&graph);
AggregateId id_one(
{graph.NodeFromStringOrDie("A"), graph.NodeFromStringOrDie("B")});
AggregateId id_two(
{graph.NodeFromStringOrDie("C"), graph.NodeFromStringOrDie("D")});
initial_tm.AddDemand(
id_one, {nc::net::Bandwidth::FromGBitsPerSecond(FLAGS_ab_aggregate_gbps),
FLAGS_ab_aggregate_flows});
initial_tm.AddDemand(
id_two, {nc::net::Bandwidth::FromGBitsPerSecond(FLAGS_cd_aggregate_gbps),
FLAGS_cd_aggregate_flows});
PathProvider path_provider(&graph);
std::unique_ptr<Optimizer> opt;
if (FLAGS_opt == "CTR") {
opt = nc::make_unique<CTROptimizer>(&path_provider, 1.0, true);
} else if (FLAGS_opt == "B4") {
opt = nc::make_unique<B4Optimizer>(&path_provider, false, 1.0);
} else if (FLAGS_opt == "B4(P)") {
opt = nc::make_unique<B4Optimizer>(&path_provider, true, 1.0);
} else if (FLAGS_opt == "MinMax") {
opt = nc::make_unique<MinMaxOptimizer>(&path_provider, 1.0);
}
MeanScaleEstimatorFactory estimator_factory(
{1.1, FLAGS_decay_factor, FLAGS_decay_factor, 10});
RoutingSystemConfig routing_system_config;
routing_system_config.store_to_metrics = false;
RoutingSystem routing_system(routing_system_config, opt.get(),
&estimator_factory);
StabilityEvalHarness harness(&initial_tm, &routing_system, FLAGS_steps);
harness.DumpAggregateVolumes();
harness.DumpLinkFractions();
}
} // namespace ctr
int main(int argc, char** argv) {
gflags::ParseCommandLineFlags(&argc, &argv, true);
// ctr::RunWithSimpleTopology();
ctr::RunWithSimpleTopologyTwoAggregates();
return 0;
}
<commit_msg>fixed compilation error<commit_after>#include <gflags/gflags.h>
#include <stddef.h>
#include <algorithm>
#include <chrono>
#include <iostream>
#include <map>
#include <memory>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
#include "ncode_common/src/common.h"
#include "ncode_common/src/map_util.h"
#include "ncode_common/src/net/net_common.h"
#include "ncode_common/src/net/net_gen.h"
#include "ncode_common/src/strutil.h"
#include "ncode_common/src/viz/grapher.h"
#include "../common.h"
#include "../mean_est/mean_est.h"
#include "../routing_system.h"
#include "ctr.h"
#include "path_provider.h"
DEFINE_double(cd_link_gbps, 1.0, "Capacity of C->D");
DEFINE_double(ab_link_gbps, 1.0, "Capacity of A->B");
DEFINE_double(cd_link_ms, 10, "Delay of C->D");
DEFINE_double(ab_link_ms, 10, "Delay of A->B");
DEFINE_double(cd_aggregate_gbps, 0.9, "Demand of C->D aggregate");
DEFINE_double(ab_aggregate_gbps, 0.9, "Demand of A->B aggregate");
DEFINE_uint64(cd_aggregate_flows, 1000, "Number of C->D flows");
DEFINE_uint64(ab_aggregate_flows, 1000, "Number of A->B flows");
DEFINE_uint64(steps, 20, "Number of steps");
DEFINE_double(decay_factor, 0.0, "How quickly to decay prediction");
DEFINE_string(opt, "CTR", "The optimizer to use");
DEFINE_bool(dampen_ratio, false, "Preserve the flow count / volume ratio?");
namespace ctr {
static constexpr std::chrono::milliseconds kSyntheticBinSize =
std::chrono::milliseconds(10);
static constexpr size_t kSyntheticBinCount = 600;
class StabilityEvalHarness {
public:
StabilityEvalHarness(TrafficMatrix* initial_tm, RoutingSystem* routing_system,
size_t cycle_count)
: initial_tm_(initial_tm),
routing_system_(routing_system),
graph_(routing_system_->graph()) {
Cycle(cycle_count);
}
const std::vector<RoutingConfigurationDelta>& deltas() const {
return deltas_;
}
void PlotLinkFractions(const std::string& out) const {
std::vector<nc::viz::DataSeries2D> series;
for (const auto& path_and_fractions : path_to_fraction_) {
const nc::net::Walk* walk = path_and_fractions.first;
series.emplace_back();
nc::viz::DataSeries2D& data_series = series.back();
data_series.data = path_and_fractions.second;
data_series.label = walk->ToStringNoPorts(*graph_);
}
nc::viz::PlotParameters2D params;
params.x_label = "timestep";
params.y_label = "fraction";
nc::viz::PythonGrapher grapher(out);
grapher.PlotLine(params, series);
}
void DumpLinkFractions() const {
std::cout << path_to_fraction_.size() << "\n";
for (const auto& path_and_fractions : path_to_fraction_) {
const nc::net::Walk* walk = path_and_fractions.first;
std::vector<std::string> to_combine;
for (const auto& times_and_fractions : path_and_fractions.second) {
to_combine.emplace_back(nc::StrCat("(", times_and_fractions.first, ",",
times_and_fractions.second, ")"));
}
std::cout << walk->ToStringNoPorts(*graph_) << " : ("
<< nc::Join(to_combine, ",") << ")\n";
}
}
void DumpAggregateVolumes() const {
std::cout << volumes_.size() << "\n";
for (const auto& aggregate_and_volumes : volumes_) {
const AggregateId& aggregate_id = aggregate_and_volumes.first;
const std::vector<nc::net::Bandwidth>& volumes =
aggregate_and_volumes.second;
std::function<std::string(const nc::net::Bandwidth&)> format_f = [](
const nc::net::Bandwidth& bw) { return std::to_string(bw.Mbps()); };
std::string out = nc::Join(volumes, ",", format_f);
std::cout << aggregate_id.ToString(*graph_) << " : (" << out << ")\n";
}
}
private:
// Produces a traffic matrix that is scaled based on each flow's shortest path
// stretch. If all flows of an aggregate are on a path that is 2x as long as
// the shortest path then their demand will be 1/2 of what it would be if they
// were on the shortest path.
std::unique_ptr<TrafficMatrix> ScaleBasedOnOutput(
const RoutingConfiguration& routing,
const TrafficMatrix& original_tm) const {
std::map<AggregateId, DemandAndFlowCount> out;
for (const auto& aggregate_and_routes : routing.routes()) {
const AggregateId& aggregate_id = aggregate_and_routes.first;
const DemandAndFlowCount& demand_and_flow_count =
nc::FindOrDieNoPrint(routing.demands(), aggregate_id);
const DemandAndFlowCount& initial_demand_and_flow_count =
nc::FindOrDieNoPrint(initial_tm_->demands(), aggregate_id);
size_t flow_count = demand_and_flow_count.second;
nc::net::Bandwidth sp_bandwidth = initial_demand_and_flow_count.first;
nc::net::Delay sp_delay = aggregate_id.GetSPDelay(*graph_);
double total_mbps = 0;
double per_flow_sp_mbps = sp_bandwidth.Mbps() / flow_count;
const std::vector<RouteAndFraction>& routes = aggregate_and_routes.second;
for (const RouteAndFraction& route_and_fraction : routes) {
nc::net::Delay path_delay = route_and_fraction.first->delay();
double sp_ratio =
static_cast<double>(sp_delay.count()) / path_delay.count();
// Each flow in the aggregate will get bandwidth proportional to how far
// away it is from the shortest path.
total_mbps += route_and_fraction.second * flow_count * sp_ratio *
per_flow_sp_mbps;
CHECK(total_mbps == total_mbps);
}
std::mt19937 rnd(1);
std::uniform_real_distribution<double> dist(1, 10);
double new_flow_count = flow_count;
if (FLAGS_dampen_ratio) {
// The demand in the output will not be the same as the one in the input
// to the optimizer because of prediction. Need to dampen the ratio
// based on the original input, not the predicted one.
const DemandAndFlowCount& original_demand_and_flow_count =
nc::FindOrDieNoPrint(original_tm.demands(), aggregate_id);
new_flow_count = total_mbps * flow_count /
original_demand_and_flow_count.first.Mbps();
new_flow_count = std::max(1.0, new_flow_count);
}
out[aggregate_id] = {nc::net::Bandwidth::FromMBitsPerSecond(total_mbps),
new_flow_count};
}
return nc::make_unique<TrafficMatrix>(graph_, out);
}
// Performs a number of runs with the optimizer. Returns n - 1 values, one for
// each delta between a run and its following run.
void Cycle(size_t n) {
std::unique_ptr<TrafficMatrix> prev_tm;
std::unique_ptr<RoutingConfiguration> prev_routing;
for (size_t i = 0; i < n; ++i) {
const TrafficMatrix* tm = prev_tm ? prev_tm.get() : initial_tm_;
UpdateVolumes(*tm);
RoutingSystemUpdateResult update_result =
routing_system_->Update(SyntheticHistoryFromTM(*tm));
auto& routing = update_result.routing;
for (const auto& aggregate_and_routes : routing->routes()) {
for (const auto& path_and_fraction : aggregate_and_routes.second) {
path_to_fraction_[path_and_fraction.first].emplace_back(
i, path_and_fraction.second);
}
}
if (prev_routing) {
deltas_.emplace_back(prev_routing->GetDifference(*routing));
}
prev_tm = ScaleBasedOnOutput(*routing, *tm);
prev_routing = std::move(routing);
}
}
void UpdateVolumes(const TrafficMatrix& tm) {
for (const auto& aggregate_and_demands : tm.demands()) {
const AggregateId& aggregate = aggregate_and_demands.first;
volumes_[aggregate].emplace_back(aggregate_and_demands.second.first);
}
}
std::map<AggregateId, AggregateHistory> SyntheticHistoryFromTM(
const TrafficMatrix& tm) {
std::map<AggregateId, AggregateHistory> out;
for (const auto& aggregate_demand_and_flow_count : tm.demands()) {
const AggregateId& aggregate = aggregate_demand_and_flow_count.first;
nc::net::Bandwidth demand = aggregate_demand_and_flow_count.second.first;
size_t flow_count = aggregate_demand_and_flow_count.second.second;
out.emplace(std::piecewise_construct, std::forward_as_tuple(aggregate),
std::forward_as_tuple(demand, kSyntheticBinCount,
kSyntheticBinSize, flow_count));
}
return out;
}
// In the initial TM each aggregate's demand is what it would be if it were
// routed on its shortest path.
TrafficMatrix* initial_tm_;
// The optimizer.
RoutingSystem* routing_system_;
// The graph.
const nc::net::GraphStorage* graph_;
// N - 1 deltas for each step to the next one.
std::vector<RoutingConfigurationDelta> deltas_;
// Per-aggregate volumes.
std::map<AggregateId, std::vector<nc::net::Bandwidth>> volumes_;
// Path to fractions of capacity.
std::map<const nc::net::Walk*, std::vector<std::pair<double, double>>>
path_to_fraction_;
};
static void RunWithSimpleTopologyTwoAggregates() {
nc::net::GraphBuilder builder;
std::chrono::microseconds ab_delay(
static_cast<size_t>(FLAGS_ab_link_ms * 1000));
std::chrono::microseconds cd_delay(
static_cast<size_t>(FLAGS_cd_link_ms * 1000));
builder.AddLink({"A", "B",
nc::net::Bandwidth::FromGBitsPerSecond(FLAGS_ab_link_gbps),
ab_delay});
builder.AddLink({"B", "A",
nc::net::Bandwidth::FromGBitsPerSecond(FLAGS_ab_link_gbps),
ab_delay});
builder.AddLink({"A", "C", nc::net::Bandwidth::FromGBitsPerSecond(1),
std::chrono::milliseconds(1)});
builder.AddLink({"C", "A", nc::net::Bandwidth::FromGBitsPerSecond(1),
std::chrono::milliseconds(1)});
builder.AddLink({"C", "D",
nc::net::Bandwidth::FromGBitsPerSecond(FLAGS_cd_link_gbps),
cd_delay});
builder.AddLink({"D", "C",
nc::net::Bandwidth::FromGBitsPerSecond(FLAGS_cd_link_gbps),
cd_delay});
builder.AddLink({"B", "D", nc::net::Bandwidth::FromGBitsPerSecond(1),
std::chrono::milliseconds(1)});
builder.AddLink({"D", "B", nc::net::Bandwidth::FromGBitsPerSecond(1),
std::chrono::milliseconds(1)});
nc::net::GraphStorage graph(builder);
TrafficMatrix initial_tm(&graph);
AggregateId id_one(
{graph.NodeFromStringOrDie("A"), graph.NodeFromStringOrDie("B")});
AggregateId id_two(
{graph.NodeFromStringOrDie("C"), graph.NodeFromStringOrDie("D")});
initial_tm.AddDemand(
id_one, {nc::net::Bandwidth::FromGBitsPerSecond(FLAGS_ab_aggregate_gbps),
FLAGS_ab_aggregate_flows});
initial_tm.AddDemand(
id_two, {nc::net::Bandwidth::FromGBitsPerSecond(FLAGS_cd_aggregate_gbps),
FLAGS_cd_aggregate_flows});
PathProvider path_provider(&graph);
std::unique_ptr<Optimizer> opt;
if (FLAGS_opt == "CTR") {
opt = nc::make_unique<CTROptimizer>(&path_provider, 1.0, true);
} else if (FLAGS_opt == "B4") {
opt = nc::make_unique<B4Optimizer>(&path_provider, false, 1.0);
} else if (FLAGS_opt == "B4(P)") {
opt = nc::make_unique<B4Optimizer>(&path_provider, true, 1.0);
} else if (FLAGS_opt == "MinMax") {
opt = nc::make_unique<MinMaxOptimizer>(&path_provider, 1.0);
}
MeanScaleEstimatorFactory estimator_factory(
{1.1, FLAGS_decay_factor, FLAGS_decay_factor, 10});
RoutingSystemConfig routing_system_config;
routing_system_config.store_to_metrics = false;
RoutingSystem routing_system(routing_system_config, opt.get(),
&estimator_factory);
StabilityEvalHarness harness(&initial_tm, &routing_system, FLAGS_steps);
harness.DumpAggregateVolumes();
harness.DumpLinkFractions();
}
} // namespace ctr
int main(int argc, char** argv) {
gflags::ParseCommandLineFlags(&argc, &argv, true);
// ctr::RunWithSimpleTopology();
ctr::RunWithSimpleTopologyTwoAggregates();
return 0;
}
<|endoftext|> |
<commit_before>// $Id$
// -*- C++ -*-
//***************************************************************************
//
// File:
// loadmodule.cc
//
// Purpose:
// LoadModule class for reading and gathering symbolic information
// from a load module. (based on GNU Binutils).
//
// Description:
// [The set of functions, macros, etc. defined in the file]
//
// Author:
// Written by John Mellor-Crummey and Nathan Tallent, Rice University.
//
// Adapted from parts of The Visual Profiler by Curtis L. Janssen
// (exec.cc).
//
//***************************************************************************
#ifdef __GNUC__
#pragma implementation
#endif
//************************* System Include Files ****************************
#include <iostream>
//*************************** User Include Files ****************************
#include "loadmodule.h"
//*************************** Forward Declarations **************************
using namespace std;
//*************************** Forward Declarations **************************
bool minisym_is_interesting(bfd *abfd, asymbol *p);
#define valueof(x) ((x)->section->vma + (x)->value)
int val_forward(const void *x, const void *y)
{
asymbol *xp = *(asymbol **)x;
asymbol *yp = *(asymbol **)y;
long yv = valueof(yp);
long xv = valueof(xp);
if (xv < yv) return -1;
if (xv == yv) return 0;
return 1;
}
//***************************************************************************
/////////////////////////////////////////////////////////////////////////
// LoadModule
LoadModule::LoadModule()
{
debug_ = 0;
type_ = Unknown;
}
LoadModule::~LoadModule()
{
}
bool
LoadModule::line_info() const
{
return true;
}
bool
LoadModule::file_info() const
{
return true;
}
bool
LoadModule::func_info() const
{
return true;
}
/////////////////////////////////////////////////////////////////////////
// BFDLoadModule
extern "C" {
char *cplus_demangle (const char *mangled, int options);
static int demangle_flags = (1 << 0) | (1 << 1);
/* FIXME: DMGL_PARAMS | DMGL_ANSI */
}
int BFDLoadModule::bfdinitialized_ = 0;
BFDLoadModule::BFDLoadModule(const string &name)
{
if (!bfdinitialized_) {
bfd_init();
bfdinitialized_ = 1;
}
bfd_ = 0;
symbols_ = 0;
read(name);
}
BFDLoadModule::~BFDLoadModule()
{
cleanup();
}
void
BFDLoadModule::cleanup(bool clear_cache)
{
name_ = "";
if (bfd_) {
bfd_close(bfd_);
bfd_ = 0;
}
delete[] (char*)symbols_;
symbols_ = 0;
if (clear_cache) locmap_.clear();
}
extern "C" {
static void
BFDLoadModule_find_address_in_section(bfd*b, asection* sect, PTR exec)
{
BFDLoadModule::find_address_in_section(b, sect, exec);
}
}
void
BFDLoadModule::read(const string &name)
{
read_file(name);
}
bool BFDLoadModule::minisyms_;
int BFDLoadModule::dynoffset_;
void
BFDLoadModule::read_file(const string &name, bool clear_cache)
{
cleanup(clear_cache);
name_ = name;
#if 0
cerr << "Reading: " << name << endl;
#endif
bfd_ = bfd_openr(name_.c_str(), 0);
minisyms_ = false;
if (!bfd_) {
cleanup();
return;
}
if (!bfd_check_format(bfd_, bfd_object)) {
cleanup();
return;
}
flagword flags = bfd_get_file_flags(bfd_);
if (flags & EXEC_P) { // BFD is directly executable
type_ = Exe;
} else if (flags & DYNAMIC) { // BFD is a dynamic object
type_ = DSO;
}
if (type_ == DSO) {
long symcount;
PTR minisyms;
unsigned int size;
struct size_sym *symsizes;
asymbol *tmp_symbol, *mk_sym;
int i;
symcount = bfd_read_minisymbols (bfd_, bfd_tttrue, &minisyms, &size);
symbols_ = (asymbol**)(new char[(symcount+1)*sizeof(asymbol *)]);
#if 0
cerr << "Mini symbols semiloaded: " << symcount << endl;
#endif
tmp_symbol = NULL;
asymbol *res = NULL;
int nsyms = 0;
for (i = 0; i < symcount; i++) {
if (res == tmp_symbol) {
tmp_symbol = bfd_make_empty_symbol (bfd_);
}
res = bfd_minisymbol_to_symbol(bfd_, bfd_tttrue,
(PTR)(((char *)minisyms)+i*size),
tmp_symbol);
if (minisym_is_interesting(bfd_, res)) {
symbols_[nsyms++] = res;
} else {
res = NULL;
}
}
qsort(symbols_, nsyms, sizeof(asymbol*), val_forward);
symbols_[nsyms] = NULL;
#if 0
cerr << "Mini symbols loaded: " << nsyms << endl;
#endif
minisyms_ = true;
}
else {
long int symsize = bfd_get_symtab_upper_bound(bfd_);
if (!symsize) {
cleanup();
return;
}
symbols_ = (asymbol**)(new char[symsize]);
if (!symbols_) {
cleanup();
return;
}
int numsym = bfd_canonicalize_symtab(bfd_, symbols_);
#if 0
cerr << "Number of symbols loaded: " << numsym << endl;
#endif
minisyms_ = false;
}
}
bfd_vma BFDLoadModule::pc_ = 0;
const char *BFDLoadModule::filename_ = 0;
const char *BFDLoadModule::functionname_ = 0;
unsigned int BFDLoadModule::line_ = 0;
bool BFDLoadModule::found_ = false;
bool
minisym_is_interesting(bfd *abfd, asymbol *p)
{
symbol_info syminfo;
bfd_get_symbol_info (abfd, p, &syminfo);
return (syminfo.type == 'T') || (syminfo.type == 't');
}
void
BFDLoadModule::find_address_in_section(bfd* abfd, asection* section, PTR exec)
{
BFDLoadModule *e = static_cast<BFDLoadModule*>(exec);
bfd_vma vma;
bfd_size_type size;
if (!e->debug() && e->found_)
return;
if ((bfd_get_section_flags (abfd, section) & SEC_ALLOC) == 0) {
return;
}
vma = bfd_get_section_vma (abfd, section);
size = bfd_get_section_size_before_reloc (section);
// FIXME: these debugging messages should removed or placed within
// debug conditionals
#if 0
cerr << "Section: vma=" << vma << ", size=" << size << ", dynoffset="
<< dynoffset_ << ", flags=" << bfd_get_section_flags (abfd, section)
<< endl;
#endif
const char *tmp_filename = 0;
const char *tmp_funcname = 0;
unsigned int tmp_line = 0;
bool tmp_found = false;
#if 0
cerr << "Looking for pc_: " << e->pc_ << endl;
#endif
if (minisyms_) {
asymbol **p;
unsigned long offset, bestoff;
asymbol *bestsym;
if (e->pc_ >= vma && e->pc_ < vma + size) {
bfd_find_nearest_line (abfd, section, e->symbols_, e->pc_ - vma,
&tmp_filename, &tmp_funcname,
&tmp_line);
#if 0
cerr << "FNL: pc=" << e->pc_ << ", funcname=" << tmp_funcname << endl;
#endif
bestsym = (asymbol *)0;
offset = e->pc_;
bestoff = 0;
for (p = e->symbols_; *p != NULL; p++) {
symbol_info syminfo;
bfd_get_symbol_info (abfd, *p, &syminfo);
#if 0
cerr << "symbol: sym=" << syminfo.value << " offset=" << offset
<< " best=" << bestoff << " name=" << syminfo.name << endl;
#endif
if (offset >= syminfo.value && bestoff < syminfo.value) {
bestoff = syminfo.value;
#if 0
cerr << "better symbol match: sym="<< offset
<< " best=" << bestoff << "name =" << syminfo.name << endl;
#endif
bestsym = (*p);
tmp_funcname = syminfo.name;
}
}
if (bestsym) {
tmp_found = true;
tmp_filename = (char *)0;
tmp_line = 0;
#if 0
cerr << "pc_: " << e->pc_ << ", vma: " << vma << ",size: " << size
<< ", bestoff: " << bestoff << ", funcname: " << tmp_funcname
<< endl;
#endif
}
}
dynoffset_ += size;
}
else {
if (e->pc_ >= vma && e->pc_ < vma + size)
tmp_found = bfd_find_nearest_line (abfd, section, e->symbols_,
e->pc_ - vma, &tmp_filename,
&tmp_funcname, &tmp_line);
}
if (!tmp_found) {
#if 0
cerr << "pc_: " << (void*)e->pc_ << " NOT FOUND" << endl;
#endif
}
if (e->debug() && (tmp_found || tmp_filename || tmp_funcname || tmp_line)) {
cerr << " { bfd sec find: (" << tmp_found << ")"
<< ", file = " << tmp_filename
<< ", func = " << tmp_funcname
<< ", line = " << tmp_line << " }" << endl;
}
if (!e->found_) {
e->found_ = tmp_found;
e->filename_ = tmp_filename;
e->functionname_ = tmp_funcname;
e->line_ = tmp_line;
}
}
time_t
BFDLoadModule::mtime() const
{
if (!bfd_) return 0;
return bfd_get_mtime(bfd_);
}
std::string
BFDLoadModule::name() const
{
return name_;
}
pprof_off_t
BFDLoadModule::textstart() const
{
return 0;
}
string
BFDLoadModule::demangle(const string &name) const
{
char *demangled = cplus_demangle(name.c_str(), demangle_flags);
string r;
if (demangled) {
r = demangled;
free(demangled);
}
else {
r = name;
}
return r;
}
void
BFDLoadModule::find_bfd(pprof_off_t pc, const char **filename,
unsigned int *lineno, const char **funcname) const
{
pc_ = pc;
dynoffset_ = 0;
found_ = false;
functionname_ = 0;
line_ = 0;
filename_ = 0;
bfd_map_over_sections(bfd_, BFDLoadModule_find_address_in_section,
(PTR) this);
if (funcname) *funcname = functionname_;
if (lineno) *lineno = line_;
if (filename) *filename = filename_;
}
int
BFDLoadModule::find(pprof_off_t pc, const char **filename,
unsigned int *lineno, const char **funcname) const
{
if (!bfd_) return 0;
std::map<pprof_off_t,FuncInfo>::iterator ilocmap = locmap_.find(pc);
if (ilocmap != locmap_.end()) {
FuncInfo &funcinfo = (*ilocmap).second;
if (funcinfo.file().size() > 0) *filename = funcinfo.c_file();
else *filename = 0;
if (funcinfo.name().size() > 0) *funcname = funcinfo.c_name();
else *funcname = 0;
*lineno = funcinfo.index();
return 1;
}
find_bfd(pc, filename, lineno, funcname);
if (line_ == 0) {
// possible BFD problem--reinitialize and try again
const_cast<BFDLoadModule*>(this)->read_file(name(),false);
find_bfd(pc, filename, lineno, funcname);
if (debug_ && line_ != 0) {
cerr << "WARNING: BFD lineno == 0 problem detected" << endl;
}
}
if (debug_) {
#if 0
const char* pre = " ";
cerr << pre << "{ bfd find @ " << (void*)pc << ": " << *funcname << endl
<< pre << " [" << *filename << ":" << *lineno << "] }" << endl;
#endif
}
locmap_[pc].set_index(*lineno);
if (*funcname) locmap_[pc].set_name(*funcname);
if (*filename) locmap_[pc].set_file(*filename);
return found_;
}
<commit_msg>'(bfd_boolean)true' seems more elegant than 'bfd_tttrue' (Thanks to Nils Smeds)<commit_after>// $Id$
// -*- C++ -*-
//***************************************************************************
//
// File:
// loadmodule.cc
//
// Purpose:
// LoadModule class for reading and gathering symbolic information
// from a load module. (based on GNU Binutils).
//
// Description:
// [The set of functions, macros, etc. defined in the file]
//
// Author:
// Written by John Mellor-Crummey and Nathan Tallent, Rice University.
//
// Adapted from parts of The Visual Profiler by Curtis L. Janssen
// (exec.cc).
//
//***************************************************************************
#ifdef __GNUC__
#pragma implementation
#endif
//************************* System Include Files ****************************
#include <iostream>
//*************************** User Include Files ****************************
#include "loadmodule.h"
//*************************** Forward Declarations **************************
using namespace std;
//*************************** Forward Declarations **************************
bool minisym_is_interesting(bfd *abfd, asymbol *p);
#define valueof(x) ((x)->section->vma + (x)->value)
int val_forward(const void *x, const void *y)
{
asymbol *xp = *(asymbol **)x;
asymbol *yp = *(asymbol **)y;
long yv = valueof(yp);
long xv = valueof(xp);
if (xv < yv) return -1;
if (xv == yv) return 0;
return 1;
}
//***************************************************************************
/////////////////////////////////////////////////////////////////////////
// LoadModule
LoadModule::LoadModule()
{
debug_ = 0;
type_ = Unknown;
}
LoadModule::~LoadModule()
{
}
bool
LoadModule::line_info() const
{
return true;
}
bool
LoadModule::file_info() const
{
return true;
}
bool
LoadModule::func_info() const
{
return true;
}
/////////////////////////////////////////////////////////////////////////
// BFDLoadModule
extern "C" {
char *cplus_demangle (const char *mangled, int options);
static int demangle_flags = (1 << 0) | (1 << 1);
/* FIXME: DMGL_PARAMS | DMGL_ANSI */
}
int BFDLoadModule::bfdinitialized_ = 0;
BFDLoadModule::BFDLoadModule(const string &name)
{
if (!bfdinitialized_) {
bfd_init();
bfdinitialized_ = 1;
}
bfd_ = 0;
symbols_ = 0;
read(name);
}
BFDLoadModule::~BFDLoadModule()
{
cleanup();
}
void
BFDLoadModule::cleanup(bool clear_cache)
{
name_ = "";
if (bfd_) {
bfd_close(bfd_);
bfd_ = 0;
}
delete[] (char*)symbols_;
symbols_ = 0;
if (clear_cache) locmap_.clear();
}
extern "C" {
static void
BFDLoadModule_find_address_in_section(bfd*b, asection* sect, PTR exec)
{
BFDLoadModule::find_address_in_section(b, sect, exec);
}
}
void
BFDLoadModule::read(const string &name)
{
read_file(name);
}
bool BFDLoadModule::minisyms_;
int BFDLoadModule::dynoffset_;
void
BFDLoadModule::read_file(const string &name, bool clear_cache)
{
cleanup(clear_cache);
name_ = name;
#if 0
cerr << "Reading: " << name << endl;
#endif
bfd_ = bfd_openr(name_.c_str(), 0);
minisyms_ = false;
if (!bfd_) {
cleanup();
return;
}
if (!bfd_check_format(bfd_, bfd_object)) {
cleanup();
return;
}
flagword flags = bfd_get_file_flags(bfd_);
if (flags & EXEC_P) { // BFD is directly executable
type_ = Exe;
} else if (flags & DYNAMIC) { // BFD is a dynamic object
type_ = DSO;
}
if (type_ == DSO) {
long symcount;
PTR minisyms;
unsigned int size;
struct size_sym *symsizes;
asymbol *tmp_symbol, *mk_sym;
int i;
symcount = bfd_read_minisymbols (bfd_, (bfd_boolean)true, &minisyms, &size);
symbols_ = (asymbol**)(new char[(symcount+1)*sizeof(asymbol *)]);
#if 0
cerr << "Mini symbols semiloaded: " << symcount << endl;
#endif
tmp_symbol = NULL;
asymbol *res = NULL;
int nsyms = 0;
for (i = 0; i < symcount; i++) {
if (res == tmp_symbol) {
tmp_symbol = bfd_make_empty_symbol (bfd_);
}
res = bfd_minisymbol_to_symbol(bfd_, (bfd_boolean)true,
(PTR)(((char *)minisyms)+i*size),
tmp_symbol);
if (minisym_is_interesting(bfd_, res)) {
symbols_[nsyms++] = res;
} else {
res = NULL;
}
}
qsort(symbols_, nsyms, sizeof(asymbol*), val_forward);
symbols_[nsyms] = NULL;
#if 0
cerr << "Mini symbols loaded: " << nsyms << endl;
#endif
minisyms_ = true;
}
else {
long int symsize = bfd_get_symtab_upper_bound(bfd_);
if (!symsize) {
cleanup();
return;
}
symbols_ = (asymbol**)(new char[symsize]);
if (!symbols_) {
cleanup();
return;
}
int numsym = bfd_canonicalize_symtab(bfd_, symbols_);
#if 0
cerr << "Number of symbols loaded: " << numsym << endl;
#endif
minisyms_ = false;
}
}
bfd_vma BFDLoadModule::pc_ = 0;
const char *BFDLoadModule::filename_ = 0;
const char *BFDLoadModule::functionname_ = 0;
unsigned int BFDLoadModule::line_ = 0;
bool BFDLoadModule::found_ = false;
bool
minisym_is_interesting(bfd *abfd, asymbol *p)
{
symbol_info syminfo;
bfd_get_symbol_info (abfd, p, &syminfo);
return (syminfo.type == 'T') || (syminfo.type == 't');
}
void
BFDLoadModule::find_address_in_section(bfd* abfd, asection* section, PTR exec)
{
BFDLoadModule *e = static_cast<BFDLoadModule*>(exec);
bfd_vma vma;
bfd_size_type size;
if (!e->debug() && e->found_)
return;
if ((bfd_get_section_flags (abfd, section) & SEC_ALLOC) == 0) {
return;
}
vma = bfd_get_section_vma (abfd, section);
size = bfd_get_section_size_before_reloc (section);
// FIXME: these debugging messages should removed or placed within
// debug conditionals
#if 0
cerr << "Section: vma=" << vma << ", size=" << size << ", dynoffset="
<< dynoffset_ << ", flags=" << bfd_get_section_flags (abfd, section)
<< endl;
#endif
const char *tmp_filename = 0;
const char *tmp_funcname = 0;
unsigned int tmp_line = 0;
bool tmp_found = false;
#if 0
cerr << "Looking for pc_: " << e->pc_ << endl;
#endif
if (minisyms_) {
asymbol **p;
unsigned long offset, bestoff;
asymbol *bestsym;
if (e->pc_ >= vma && e->pc_ < vma + size) {
bfd_find_nearest_line (abfd, section, e->symbols_, e->pc_ - vma,
&tmp_filename, &tmp_funcname,
&tmp_line);
#if 0
cerr << "FNL: pc=" << e->pc_ << ", funcname=" << tmp_funcname << endl;
#endif
bestsym = (asymbol *)0;
offset = e->pc_;
bestoff = 0;
for (p = e->symbols_; *p != NULL; p++) {
symbol_info syminfo;
bfd_get_symbol_info (abfd, *p, &syminfo);
#if 0
cerr << "symbol: sym=" << syminfo.value << " offset=" << offset
<< " best=" << bestoff << " name=" << syminfo.name << endl;
#endif
if (offset >= syminfo.value && bestoff < syminfo.value) {
bestoff = syminfo.value;
#if 0
cerr << "better symbol match: sym="<< offset
<< " best=" << bestoff << "name =" << syminfo.name << endl;
#endif
bestsym = (*p);
tmp_funcname = syminfo.name;
}
}
if (bestsym) {
tmp_found = true;
tmp_filename = (char *)0;
tmp_line = 0;
#if 0
cerr << "pc_: " << e->pc_ << ", vma: " << vma << ",size: " << size
<< ", bestoff: " << bestoff << ", funcname: " << tmp_funcname
<< endl;
#endif
}
}
dynoffset_ += size;
}
else {
if (e->pc_ >= vma && e->pc_ < vma + size)
tmp_found = bfd_find_nearest_line (abfd, section, e->symbols_,
e->pc_ - vma, &tmp_filename,
&tmp_funcname, &tmp_line);
}
if (!tmp_found) {
#if 0
cerr << "pc_: " << (void*)e->pc_ << " NOT FOUND" << endl;
#endif
}
if (e->debug() && (tmp_found || tmp_filename || tmp_funcname || tmp_line)) {
cerr << " { bfd sec find: (" << tmp_found << ")"
<< ", file = " << tmp_filename
<< ", func = " << tmp_funcname
<< ", line = " << tmp_line << " }" << endl;
}
if (!e->found_) {
e->found_ = tmp_found;
e->filename_ = tmp_filename;
e->functionname_ = tmp_funcname;
e->line_ = tmp_line;
}
}
time_t
BFDLoadModule::mtime() const
{
if (!bfd_) return 0;
return bfd_get_mtime(bfd_);
}
std::string
BFDLoadModule::name() const
{
return name_;
}
pprof_off_t
BFDLoadModule::textstart() const
{
return 0;
}
string
BFDLoadModule::demangle(const string &name) const
{
char *demangled = cplus_demangle(name.c_str(), demangle_flags);
string r;
if (demangled) {
r = demangled;
free(demangled);
}
else {
r = name;
}
return r;
}
void
BFDLoadModule::find_bfd(pprof_off_t pc, const char **filename,
unsigned int *lineno, const char **funcname) const
{
pc_ = pc;
dynoffset_ = 0;
found_ = false;
functionname_ = 0;
line_ = 0;
filename_ = 0;
bfd_map_over_sections(bfd_, BFDLoadModule_find_address_in_section,
(PTR) this);
if (funcname) *funcname = functionname_;
if (lineno) *lineno = line_;
if (filename) *filename = filename_;
}
int
BFDLoadModule::find(pprof_off_t pc, const char **filename,
unsigned int *lineno, const char **funcname) const
{
if (!bfd_) return 0;
std::map<pprof_off_t,FuncInfo>::iterator ilocmap = locmap_.find(pc);
if (ilocmap != locmap_.end()) {
FuncInfo &funcinfo = (*ilocmap).second;
if (funcinfo.file().size() > 0) *filename = funcinfo.c_file();
else *filename = 0;
if (funcinfo.name().size() > 0) *funcname = funcinfo.c_name();
else *funcname = 0;
*lineno = funcinfo.index();
return 1;
}
find_bfd(pc, filename, lineno, funcname);
if (line_ == 0) {
// possible BFD problem--reinitialize and try again
const_cast<BFDLoadModule*>(this)->read_file(name(),false);
find_bfd(pc, filename, lineno, funcname);
if (debug_ && line_ != 0) {
cerr << "WARNING: BFD lineno == 0 problem detected" << endl;
}
}
if (debug_) {
#if 0
const char* pre = " ";
cerr << pre << "{ bfd find @ " << (void*)pc << ": " << *funcname << endl
<< pre << " [" << *filename << ":" << *lineno << "] }" << endl;
#endif
}
locmap_[pc].set_index(*lineno);
if (*funcname) locmap_[pc].set_name(*funcname);
if (*filename) locmap_[pc].set_file(*filename);
return found_;
}
<|endoftext|> |
<commit_before>#include <cmath>
#include <allegro5/allegro_primitives.h> // DEBUGTOOL
#include "ingameelements/weapons/hammer.h"
#include "renderer.h"
#include "ingameelements/heroes/reinhardt.h"
#include "ingameelements/projectiles/firestrike.h"
#include "engine.h"
void Hammer::init(uint64_t id_, Gamestate &state, EntityPtr owner_)
{
Weapon::init(id_, state, owner_);
barrierptr = state.make_entity<ReinhardtShield>(state, team, owner_);
firestrikeanim.init(herofolder()+"firestrikebackarm/");
firestrikeanim.active(false);
firestrikedelay.init(firestrikeanim.timer.duration * 0.5,
std::bind(&Hammer::createfirestrike, this, std::placeholders::_1));
firestrikedelay.active = false;
// 6th and 14th frame of an assumed 20 frame animation - ugly but idk better way
firingdelay1.init(firinganim.timer.duration * 6.0/20.0, std::bind(&Hammer::hitarea, this, std::placeholders::_1));
firingdelay1.active = false;
firingdelay2.init(firinganim.timer.duration * 14.0/20.0, std::bind(&Hammer::hitarea, this, std::placeholders::_1));
firingdelay2.active = false;
}
void Hammer::renderbehind(Renderer &renderer, Gamestate &state)
{
if (firinganim.active())
{
return;
}
std::string mainsprite;
Reinhardt &c = state.get<Reinhardt>(state.get<Player>(owner).character);
if (firestrikeanim.active())
{
mainsprite = firestrikeanim.getframepath();
}
else if (barrier(state).active)
{
mainsprite = herofolder()+"shield/back";
}
else
{
mainsprite = herofolder()+"arm/back";
}
ALLEGRO_BITMAP *sprite = renderer.spriteloader.requestsprite(mainsprite);
double spriteoffset_x = renderer.spriteloader.get_spriteoffset_x(mainsprite)*renderer.zoom;
double spriteoffset_y = renderer.spriteloader.get_spriteoffset_y(mainsprite)*renderer.zoom;
double rel_x = (x - renderer.cam_x)*renderer.zoom;
double rel_y = (y - renderer.cam_y)*renderer.zoom;
double attachpt_x = getbackattachpoint_x(state)*renderer.zoom;
double attachpt_y = getbackattachpoint_y(state)*renderer.zoom;
ALLEGRO_BITMAP *outline = renderer.spriteloader.requestspriteoutline(mainsprite);
ALLEGRO_COLOR outlinecolor = al_map_rgb(225, 17, 17);
al_set_target_bitmap(renderer.midground);
if (c.weaponvisible(state))
{
if (c.isflipped)
{
al_draw_scaled_rotated_bitmap(sprite, spriteoffset_x, spriteoffset_y, rel_x-attachpt_x, rel_y-attachpt_y,
-1, 1, (aimdirection+3.1415)*barrier(state).active, 0);
if (state.get<Player>(renderer.myself).team != team)
{
// Draw enemy outline
al_draw_tinted_scaled_rotated_bitmap(outline, outlinecolor, attachpt_x+spriteoffset_x, attachpt_y+spriteoffset_y, rel_x, rel_y,
-1, 1, (aimdirection+3.1415)*barrier(state).active, 0);
}
}
else
{
al_draw_rotated_bitmap(sprite, spriteoffset_x, spriteoffset_y, rel_x-attachpt_x, rel_y-attachpt_y, aimdirection*barrier(state).active, 0);
if (state.get<Player>(renderer.myself).team != team)
{
// Draw enemy outline
al_draw_tinted_rotated_bitmap(outline, outlinecolor, attachpt_x+spriteoffset_x, attachpt_y+spriteoffset_y, rel_x, rel_y, aimdirection*barrier(state).active, 0);
}
}
}
}
void Hammer::render(Renderer &renderer, Gamestate &state)
{
std::string mainsprite;
Reinhardt &c = state.get<Reinhardt>(state.get<Player>(owner).character);
if (firinganim.active())
{
mainsprite = firinganim.getframepath();
}
else if (firestrikeanim.active())
{
mainsprite = herofolder()+"firestrikefrontarm/"+std::to_string(firestrikeanim.getframe());
}
else if (barrier(state).active)
{
mainsprite = herofolder()+"shield/front";
}
else
{
mainsprite = herofolder()+"arm/front";
}
ALLEGRO_BITMAP *sprite = renderer.spriteloader.requestsprite(mainsprite);
double spriteoffset_x = renderer.spriteloader.get_spriteoffset_x(mainsprite)*renderer.zoom;
double spriteoffset_y = renderer.spriteloader.get_spriteoffset_y(mainsprite)*renderer.zoom;
double rel_x = (x - renderer.cam_x)*renderer.zoom;
double rel_y = (y - renderer.cam_y)*renderer.zoom;
double attachpt_x = getattachpoint_x(state)*renderer.zoom;
double attachpt_y = getattachpoint_y(state)*renderer.zoom;
ALLEGRO_BITMAP *outline = renderer.spriteloader.requestspriteoutline(mainsprite);
ALLEGRO_COLOR outlinecolor = al_map_rgb(225, 17, 17);
al_set_target_bitmap(renderer.midground);
if (c.weaponvisible(state))
{
if (c.isflipped)
{
al_draw_scaled_rotated_bitmap(sprite, -attachpt_x+spriteoffset_x, attachpt_y+spriteoffset_y, rel_x, rel_y, -1, 1, 0, 0);
if (state.get<Player>(renderer.myself).team != team)
{
// Draw enemy outline
al_draw_tinted_scaled_rotated_bitmap(outline, outlinecolor, attachpt_x+spriteoffset_x, attachpt_y+spriteoffset_y, rel_x, rel_y, -1, 1, 0, 0);
}
}
else
{
al_draw_bitmap(sprite, rel_x - (attachpt_x+spriteoffset_x), rel_y - (attachpt_y+spriteoffset_y), 0);
if (state.get<Player>(renderer.myself).team != team)
{
// Draw enemy outline
al_draw_tinted_bitmap(outline, outlinecolor, rel_x - (attachpt_x+spriteoffset_x), rel_y - (attachpt_y+spriteoffset_y), 0);
}
}
}
barrier(state).render(renderer, state);
al_draw_rectangle(rel_x + renderer.zoom*30 * (c.isflipped ? -1 : 1), rel_y - renderer.zoom*30,
rel_x + renderer.zoom*59 * (c.isflipped ? -1 : 1), rel_y + renderer.zoom*30, al_map_rgb(255, 0, 0), 0);
}
void Hammer::beginstep(Gamestate &state, double frametime)
{
Weapon::beginstep(state, frametime);
barrier(state).beginstep(state, frametime);
firestrikeanim.update(state, frametime);
firestrikedelay.update(state, frametime);
}
void Hammer::midstep(Gamestate &state, double frametime)
{
Weapon::midstep(state, frametime);
barrier(state).midstep(state, frametime);
}
void Hammer::endstep(Gamestate &state, double frametime)
{
Weapon::endstep(state, frametime);
barrier(state).endstep(state, frametime);
}
void Hammer::wantfireprimary(Gamestate &state)
{
if (state.engine.isserver and not firinganim.active() and not firestrikeanim.active())
{
fireprimary(state);
state.engine.sendbuffer.write<uint8_t>(PRIMARY_FIRED);
state.engine.sendbuffer.write<uint8_t>(state.findplayerid(owner));
}
}
void Hammer::fireprimary(Gamestate &state)
{
firinganim.reset();
firinganim.active(true);
}
void Hammer::wantfiresecondary(Gamestate &state)
{
// Do nothing
}
void Hammer::firesecondary(Gamestate &state)
{
// Do nothing
}
void Hammer::createfirestrike(Gamestate &state)
{
Firestrike &firestrike = state.get<Firestrike&>(state.make_entity<Firestrike>(state, owner));
firestrike.x = x + std::cos(aimdirection) * 40;
firestrike.y = y + std::sin(aimdirection) * 40;
firestrike.hspeed = firestrike.SPEED * std::cos(aimdirection);
firestrike.vspeed = firestrike.SPEED * std::sin(aimdirection);
if (state.currentmap->collideline(x, y, firestrike.x, firestrike.y))
{
firestrike.destroy(state);
}
}
void Hammer::hitarea(Gamestate &state)
{
for (auto &e : state.entitylist)
{
auto &entity = *(e.second);
if (not entity.destroyentity)
{
if (entity.damageableby(team))
{
Reinhardt &c = state.get<Reinhardt>(state.get<Player>(owner).character);
int direction = (c.isflipped ? -1 : 1);
for (int i=0; i<30; ++i)
{
for (int j=0; j<60; ++j)
{
if (entity.collides(state, x + direction*(30 + i), y - 30 + direction*j))
{
Global::logging().print(__FILE__, __LINE__, "Hit some entity");
// We hit something, check if it's protected
double tmpx, tmpy;
if (state.collidelinetarget(state, x, y, state.get<MovingEntity>(entity.id), team,
PENETRATE_CHARACTER, &tmpx, &tmpy).id == entity.id)
{
Global::logging().print(__FILE__, __LINE__, "Damage");
entity.damage(state, DAMAGE);
}
else
{
Global::logging().print(__FILE__, __LINE__, "%i is protected by %i", entity.id, state.collidelinetarget(state, x, y, state.get<MovingEntity>(entity.id), team,
PENETRATE_CHARACTER, &tmpx, &tmpy).id);
}
return;
}
}
}
}
}
}
}
double Hammer::getattachpoint_x(Gamestate &state)
{
return 0;
}
double Hammer::getattachpoint_y(Gamestate &state)
{
return 8;
}
double Hammer::getbackattachpoint_x(Gamestate &state)
{
if (barrier(state).active)
{
return 6 * (state.get<Player&>(owner).getcharacter(state).isflipped ? 1:-1);
}
else
{
return 0;
}
}
double Hammer::getbackattachpoint_y(Gamestate &state)
{
if (barrier(state).active)
{
return 10;
}
else
{
return 8;
}
}
ReinhardtShield& Hammer::barrier(Gamestate &state)
{
return state.get<ReinhardtShield>(barrierptr);
}
void Hammer::destroy(Gamestate &state)
{
barrier(state).destroy(state);
Weapon::destroy(state);
}
void Hammer::interpolate(Entity &prev_entity, Entity &next_entity, double alpha)
{
Weapon::interpolate(prev_entity, next_entity, alpha);
Hammer &prev_e = static_cast<Hammer&>(prev_entity);
Hammer &next_e = static_cast<Hammer&>(next_entity);
firestrikeanim.interpolate(prev_e.firestrikeanim, next_e.firestrikeanim, alpha);
firestrikedelay.interpolate(prev_e.firestrikedelay, next_e.firestrikedelay, alpha);
firinganim.interpolate(prev_e.firinganim, next_e.firinganim, alpha);
firingdelay1.interpolate(prev_e.firingdelay1, next_e.firingdelay1, alpha);
firingdelay2.interpolate(prev_e.firingdelay2, next_e.firingdelay2, alpha);
}<commit_msg>Finished hammer damage.<commit_after>#include <cmath>
#include "ingameelements/weapons/hammer.h"
#include "renderer.h"
#include "ingameelements/heroes/reinhardt.h"
#include "ingameelements/projectiles/firestrike.h"
#include "engine.h"
void Hammer::init(uint64_t id_, Gamestate &state, EntityPtr owner_)
{
Weapon::init(id_, state, owner_);
barrierptr = state.make_entity<ReinhardtShield>(state, team, owner_);
firestrikeanim.init(herofolder()+"firestrikebackarm/");
firestrikeanim.active(false);
firestrikedelay.init(firestrikeanim.timer.duration * 0.5,
std::bind(&Hammer::createfirestrike, this, std::placeholders::_1));
firestrikedelay.active = false;
// 6th and 14th frame of an assumed 20 frame animation - ugly but idk better way
firingdelay1.init(firinganim.timer.duration * 6.0/20.0, std::bind(&Hammer::hitarea, this, std::placeholders::_1));
firingdelay1.active = false;
firingdelay2.init(firinganim.timer.duration * 14.0/20.0, std::bind(&Hammer::hitarea, this, std::placeholders::_1));
firingdelay2.active = false;
}
void Hammer::renderbehind(Renderer &renderer, Gamestate &state)
{
if (firinganim.active())
{
return;
}
std::string mainsprite;
Reinhardt &c = state.get<Reinhardt>(state.get<Player>(owner).character);
if (firestrikeanim.active())
{
mainsprite = firestrikeanim.getframepath();
}
else if (barrier(state).active)
{
mainsprite = herofolder()+"shield/back";
}
else
{
mainsprite = herofolder()+"arm/back";
}
ALLEGRO_BITMAP *sprite = renderer.spriteloader.requestsprite(mainsprite);
double spriteoffset_x = renderer.spriteloader.get_spriteoffset_x(mainsprite)*renderer.zoom;
double spriteoffset_y = renderer.spriteloader.get_spriteoffset_y(mainsprite)*renderer.zoom;
double rel_x = (x - renderer.cam_x)*renderer.zoom;
double rel_y = (y - renderer.cam_y)*renderer.zoom;
double attachpt_x = getbackattachpoint_x(state)*renderer.zoom;
double attachpt_y = getbackattachpoint_y(state)*renderer.zoom;
ALLEGRO_BITMAP *outline = renderer.spriteloader.requestspriteoutline(mainsprite);
ALLEGRO_COLOR outlinecolor = al_map_rgb(225, 17, 17);
al_set_target_bitmap(renderer.midground);
if (c.weaponvisible(state))
{
if (c.isflipped)
{
al_draw_scaled_rotated_bitmap(sprite, spriteoffset_x, spriteoffset_y, rel_x-attachpt_x, rel_y-attachpt_y,
-1, 1, (aimdirection+3.1415)*barrier(state).active, 0);
if (state.get<Player>(renderer.myself).team != team)
{
// Draw enemy outline
al_draw_tinted_scaled_rotated_bitmap(outline, outlinecolor, attachpt_x+spriteoffset_x, attachpt_y+spriteoffset_y, rel_x, rel_y,
-1, 1, (aimdirection+3.1415)*barrier(state).active, 0);
}
}
else
{
al_draw_rotated_bitmap(sprite, spriteoffset_x, spriteoffset_y, rel_x-attachpt_x, rel_y-attachpt_y, aimdirection*barrier(state).active, 0);
if (state.get<Player>(renderer.myself).team != team)
{
// Draw enemy outline
al_draw_tinted_rotated_bitmap(outline, outlinecolor, attachpt_x+spriteoffset_x, attachpt_y+spriteoffset_y, rel_x, rel_y, aimdirection*barrier(state).active, 0);
}
}
}
}
void Hammer::render(Renderer &renderer, Gamestate &state)
{
std::string mainsprite;
Reinhardt &c = state.get<Reinhardt>(state.get<Player>(owner).character);
if (firinganim.active())
{
mainsprite = firinganim.getframepath();
}
else if (firestrikeanim.active())
{
mainsprite = herofolder()+"firestrikefrontarm/"+std::to_string(firestrikeanim.getframe());
}
else if (barrier(state).active)
{
mainsprite = herofolder()+"shield/front";
}
else
{
mainsprite = herofolder()+"arm/front";
}
ALLEGRO_BITMAP *sprite = renderer.spriteloader.requestsprite(mainsprite);
double spriteoffset_x = renderer.spriteloader.get_spriteoffset_x(mainsprite)*renderer.zoom;
double spriteoffset_y = renderer.spriteloader.get_spriteoffset_y(mainsprite)*renderer.zoom;
double rel_x = (x - renderer.cam_x)*renderer.zoom;
double rel_y = (y - renderer.cam_y)*renderer.zoom;
double attachpt_x = getattachpoint_x(state)*renderer.zoom;
double attachpt_y = getattachpoint_y(state)*renderer.zoom;
ALLEGRO_BITMAP *outline = renderer.spriteloader.requestspriteoutline(mainsprite);
ALLEGRO_COLOR outlinecolor = al_map_rgb(225, 17, 17);
al_set_target_bitmap(renderer.midground);
if (c.weaponvisible(state))
{
if (c.isflipped)
{
al_draw_scaled_rotated_bitmap(sprite, -attachpt_x+spriteoffset_x, attachpt_y+spriteoffset_y, rel_x, rel_y, -1, 1, 0, 0);
if (state.get<Player>(renderer.myself).team != team)
{
// Draw enemy outline
al_draw_tinted_scaled_rotated_bitmap(outline, outlinecolor, attachpt_x+spriteoffset_x, attachpt_y+spriteoffset_y, rel_x, rel_y, -1, 1, 0, 0);
}
}
else
{
al_draw_bitmap(sprite, rel_x - (attachpt_x+spriteoffset_x), rel_y - (attachpt_y+spriteoffset_y), 0);
if (state.get<Player>(renderer.myself).team != team)
{
// Draw enemy outline
al_draw_tinted_bitmap(outline, outlinecolor, rel_x - (attachpt_x+spriteoffset_x), rel_y - (attachpt_y+spriteoffset_y), 0);
}
}
}
barrier(state).render(renderer, state);
}
void Hammer::beginstep(Gamestate &state, double frametime)
{
Weapon::beginstep(state, frametime);
barrier(state).beginstep(state, frametime);
firestrikeanim.update(state, frametime);
firestrikedelay.update(state, frametime);
firingdelay1.update(state, frametime);
firingdelay2.update(state, frametime);
}
void Hammer::midstep(Gamestate &state, double frametime)
{
Weapon::midstep(state, frametime);
barrier(state).midstep(state, frametime);
}
void Hammer::endstep(Gamestate &state, double frametime)
{
Weapon::endstep(state, frametime);
barrier(state).endstep(state, frametime);
}
void Hammer::wantfireprimary(Gamestate &state)
{
if (state.engine.isserver and not firinganim.active() and not firestrikeanim.active())
{
fireprimary(state);
state.engine.sendbuffer.write<uint8_t>(PRIMARY_FIRED);
state.engine.sendbuffer.write<uint8_t>(state.findplayerid(owner));
}
}
void Hammer::fireprimary(Gamestate &state)
{
firinganim.reset();
firinganim.active(true);
firingdelay1.reset();
firingdelay1.active = true;
firingdelay2.reset();
firingdelay2.active = true;
}
void Hammer::wantfiresecondary(Gamestate &state)
{
// Do nothing
}
void Hammer::firesecondary(Gamestate &state)
{
// Do nothing
}
void Hammer::createfirestrike(Gamestate &state)
{
Firestrike &firestrike = state.get<Firestrike&>(state.make_entity<Firestrike>(state, owner));
firestrike.x = x + std::cos(aimdirection) * 40;
firestrike.y = y + std::sin(aimdirection) * 40;
firestrike.hspeed = firestrike.SPEED * std::cos(aimdirection);
firestrike.vspeed = firestrike.SPEED * std::sin(aimdirection);
if (state.currentmap->collideline(x, y, firestrike.x, firestrike.y))
{
firestrike.destroy(state);
}
}
void Hammer::hitarea(Gamestate &state)
{
Reinhardt &reinhardt = state.get<Reinhardt>(state.get<Player>(owner).character);
for (auto &e : state.entitylist)
{
auto &entity = *(e.second);
if (not entity.destroyentity)
{
if (entity.damageableby(team))
{
int direction = (reinhardt.isflipped ? -1 : 1);
for (int i=0; i<30; ++i)
{
for (int j=0; j<60; ++j)
{
if (entity.collides(state, x + direction*(30 + i), y - 30 + j))
{
// We hit something, check if it's protected
double tmpx, tmpy;
if (state.collidelinetarget(state, x, y, state.get<MovingEntity>(entity.id), team,
PENETRATE_CHARACTER, &tmpx, &tmpy).id == entity.id)
{
entity.damage(state, DAMAGE);
}
return;
}
}
}
}
}
}
}
double Hammer::getattachpoint_x(Gamestate &state)
{
return 0;
}
double Hammer::getattachpoint_y(Gamestate &state)
{
return 8;
}
double Hammer::getbackattachpoint_x(Gamestate &state)
{
if (barrier(state).active)
{
return 6 * (state.get<Player&>(owner).getcharacter(state).isflipped ? 1:-1);
}
else
{
return 0;
}
}
double Hammer::getbackattachpoint_y(Gamestate &state)
{
if (barrier(state).active)
{
return 10;
}
else
{
return 8;
}
}
ReinhardtShield& Hammer::barrier(Gamestate &state)
{
return state.get<ReinhardtShield>(barrierptr);
}
void Hammer::destroy(Gamestate &state)
{
barrier(state).destroy(state);
Weapon::destroy(state);
}
void Hammer::interpolate(Entity &prev_entity, Entity &next_entity, double alpha)
{
Weapon::interpolate(prev_entity, next_entity, alpha);
Hammer &prev_e = static_cast<Hammer&>(prev_entity);
Hammer &next_e = static_cast<Hammer&>(next_entity);
firestrikeanim.interpolate(prev_e.firestrikeanim, next_e.firestrikeanim, alpha);
firestrikedelay.interpolate(prev_e.firestrikedelay, next_e.firestrikedelay, alpha);
firinganim.interpolate(prev_e.firinganim, next_e.firinganim, alpha);
firingdelay1.interpolate(prev_e.firingdelay1, next_e.firingdelay1, alpha);
firingdelay2.interpolate(prev_e.firingdelay2, next_e.firingdelay2, alpha);
}<|endoftext|> |
<commit_before>/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2019 *
* *
* 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 <openspace/interaction/keybindingmanager.h>
#include <openspace/engine/globals.h>
#include <openspace/scripting/lualibrary.h>
#include <openspace/scripting/scriptengine.h>
#include <ghoul/glm.h>
#include <sstream>
#include "keybindingmanager_lua.inl"
namespace openspace::interaction {
KeybindingManager::KeybindingManager()
: DocumentationGenerator(
"Documentation",
"keybindings",
{
{ "keybindingTemplate", "${WEB}/keybindings/keybinding.hbs" },
{ "mainTemplate", "${WEB}/keybindings/main.hbs" }
},
"${WEB}/keybindings/script.js"
)
{}
void KeybindingManager::keyboardCallback(Key key, KeyModifier modifier, KeyAction action)
{
if (action == KeyAction::Press || action == KeyAction::Repeat) {
// iterate over key bindings
auto ret = _keyLua.equal_range({ key, modifier });
for (auto it = ret.first; it != ret.second; ++it) {
using RS = scripting::ScriptEngine::RemoteScripting;
global::scriptEngine.queueScript(
it->second.command,
it->second.synchronization ? RS::Yes : RS::No
);
}
}
}
void KeybindingManager::resetKeyBindings() {
_keyLua.clear();
}
void KeybindingManager::bindKeyLocal(Key key,
KeyModifier modifier,
std::string luaCommand,
std::string documentation,
std::string name,
std::string guiPath)
{
_keyLua.insert({
{ key, modifier },
{
std::move(luaCommand),
IsSynchronized::No,
std::move(documentation),
std::move(name),
std::move(guiPath)
}
});
}
void KeybindingManager::bindKey(Key key,
KeyModifier modifier,
std::string luaCommand,
std::string documentation,
std::string name,
std::string guiPath)
{
_keyLua.insert({
{ key, modifier },
{
std::move(luaCommand),
IsSynchronized::Yes,
std::move(documentation),
std::move(name),
std::move(guiPath)
}
});
}
void KeybindingManager::removeKeyBinding(const std::string& key) {
// Erase-remove idiom does not work for std::multimap so we have to do this on foot
KeyWithModifier k = stringToKey(key);
for (auto it = _keyLua.begin(); it != _keyLua.end(); ) {
// If the current iterator is the key that we are looking for, delete it
// (std::multimap::erase will return the iterator to the next element for us)
if (it->first == k) {
it = _keyLua.erase(it);
}
else {
// We if it is not, we continue iteration
++it;
}
}
}
std::vector<std::pair<KeyWithModifier, KeybindingManager::KeyInformation>>
KeybindingManager::keyBinding(const std::string& key) const
{
std::vector<std::pair<KeyWithModifier, KeyInformation>> result;
KeyWithModifier k = stringToKey(key);
auto itRange = _keyLua.equal_range(k);
for (auto it = itRange.first; it != itRange.second; ++it) {
result.emplace_back(it->first, it->second);
}
return result;
}
const std::multimap<KeyWithModifier, KeybindingManager::KeyInformation>&
KeybindingManager::keyBindings() const
{
return _keyLua;
}
std::string KeybindingManager::generateJson() const {
std::stringstream json;
json << "[";
bool first = true;
for (const std::pair<const KeyWithModifier, KeyInformation>& p : _keyLua) {
if (!first) {
json << ",";
}
first = false;
json << "{";
json << R"("key": ")" << ghoul::to_string(p.first) << "\",";
json << R"("script": ")" << escapedJson(p.second.command) << "\",";
json << R"("remoteScripting: ")"
<< (p.second.synchronization ? "true," : "false,");
json << R"("documentation": ")" << escapedJson(p.second.documentation) << "\",";
json << R"("name: ")" << escapedJson(p.second.name) << "\"";
json << "}";
}
json << "]";
return json.str();
}
scripting::LuaLibrary KeybindingManager::luaLibrary() {
return {
"",
{
{
"clearKeys",
&luascriptfunctions::clearKeys,
{},
"",
"Clear all key bindings"
},
{
"clearKey",
&luascriptfunctions::clearKey,
{},
"string or strings",
"Unbinds the key or keys that have been provided. This function can be "
"called with a single key or with an array of keys to remove all of the "
"provided keys at once"
},
{
"bindKey",
&luascriptfunctions::bindKey,
{},
"string, string [,string]",
"Binds a key by name to a lua string command to execute both locally "
"and to broadcast to clients if this is the host of a parallel session. "
"The first argument is the key, the second argument is the Lua command "
"that is to be executed, and the optional third argument is a human "
"readable description of the command for documentation purposes."
},
{
"bindKeyLocal",
&luascriptfunctions::bindKeyLocal,
{},
"string, string [,string]",
"Binds a key by name to a lua string command to execute only locally. "
"The first argument is the key, the second argument is the Lua command "
"that is to be executed, and the optional third argument is a human "
"readable description of the command for documentation purposes."
},
{
"getKeyBinding",
&luascriptfunctions::getKeyBindings,
{},
"string",
"Returns a list of information about the keybindings for the provided "
"key. Each element in the list is a table describing the 'Command' that "
"was bound and whether it was a 'Remote' script or not."
}
}
};
}
} // namespace openspace::interaction
<commit_msg>Fix keybinding documentation (closes #813)<commit_after>/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2019 *
* *
* 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 <openspace/interaction/keybindingmanager.h>
#include <openspace/engine/globals.h>
#include <openspace/scripting/lualibrary.h>
#include <openspace/scripting/scriptengine.h>
#include <ghoul/glm.h>
#include <sstream>
#include "keybindingmanager_lua.inl"
namespace openspace::interaction {
KeybindingManager::KeybindingManager()
: DocumentationGenerator(
"Documentation",
"keybindings",
{
{ "keybindingTemplate", "${WEB}/keybindings/keybinding.hbs" },
{ "mainTemplate", "${WEB}/keybindings/main.hbs" }
},
"${WEB}/keybindings/script.js"
)
{}
void KeybindingManager::keyboardCallback(Key key, KeyModifier modifier, KeyAction action)
{
if (action == KeyAction::Press || action == KeyAction::Repeat) {
// iterate over key bindings
auto ret = _keyLua.equal_range({ key, modifier });
for (auto it = ret.first; it != ret.second; ++it) {
using RS = scripting::ScriptEngine::RemoteScripting;
global::scriptEngine.queueScript(
it->second.command,
it->second.synchronization ? RS::Yes : RS::No
);
}
}
}
void KeybindingManager::resetKeyBindings() {
_keyLua.clear();
}
void KeybindingManager::bindKeyLocal(Key key,
KeyModifier modifier,
std::string luaCommand,
std::string documentation,
std::string name,
std::string guiPath)
{
_keyLua.insert({
{ key, modifier },
{
std::move(luaCommand),
IsSynchronized::No,
std::move(documentation),
std::move(name),
std::move(guiPath)
}
});
}
void KeybindingManager::bindKey(Key key,
KeyModifier modifier,
std::string luaCommand,
std::string documentation,
std::string name,
std::string guiPath)
{
_keyLua.insert({
{ key, modifier },
{
std::move(luaCommand),
IsSynchronized::Yes,
std::move(documentation),
std::move(name),
std::move(guiPath)
}
});
}
void KeybindingManager::removeKeyBinding(const std::string& key) {
// Erase-remove idiom does not work for std::multimap so we have to do this on foot
KeyWithModifier k = stringToKey(key);
for (auto it = _keyLua.begin(); it != _keyLua.end(); ) {
// If the current iterator is the key that we are looking for, delete it
// (std::multimap::erase will return the iterator to the next element for us)
if (it->first == k) {
it = _keyLua.erase(it);
}
else {
// We if it is not, we continue iteration
++it;
}
}
}
std::vector<std::pair<KeyWithModifier, KeybindingManager::KeyInformation>>
KeybindingManager::keyBinding(const std::string& key) const
{
std::vector<std::pair<KeyWithModifier, KeyInformation>> result;
KeyWithModifier k = stringToKey(key);
auto itRange = _keyLua.equal_range(k);
for (auto it = itRange.first; it != itRange.second; ++it) {
result.emplace_back(it->first, it->second);
}
return result;
}
const std::multimap<KeyWithModifier, KeybindingManager::KeyInformation>&
KeybindingManager::keyBindings() const
{
return _keyLua;
}
std::string KeybindingManager::generateJson() const {
std::stringstream json;
json << "[";
bool first = true;
for (const std::pair<const KeyWithModifier, KeyInformation>& p : _keyLua) {
if (!first) {
json << ",";
}
first = false;
json << "{";
json << R"("key": ")" << ghoul::to_string(p.first) << "\",";
json << R"("script": ")" << escapedJson(p.second.command) << "\",";
json << R"("remoteScripting": )"
<< (p.second.synchronization ? "true," : "false,");
json << R"("documentation": ")" << escapedJson(p.second.documentation) << "\",";
json << R"("name": ")" << escapedJson(p.second.name) << "\"";
json << "}";
}
json << "]";
return json.str();
}
scripting::LuaLibrary KeybindingManager::luaLibrary() {
return {
"",
{
{
"clearKeys",
&luascriptfunctions::clearKeys,
{},
"",
"Clear all key bindings"
},
{
"clearKey",
&luascriptfunctions::clearKey,
{},
"string or strings",
"Unbinds the key or keys that have been provided. This function can be "
"called with a single key or with an array of keys to remove all of the "
"provided keys at once"
},
{
"bindKey",
&luascriptfunctions::bindKey,
{},
"string, string [,string]",
"Binds a key by name to a lua string command to execute both locally "
"and to broadcast to clients if this is the host of a parallel session. "
"The first argument is the key, the second argument is the Lua command "
"that is to be executed, and the optional third argument is a human "
"readable description of the command for documentation purposes."
},
{
"bindKeyLocal",
&luascriptfunctions::bindKeyLocal,
{},
"string, string [,string]",
"Binds a key by name to a lua string command to execute only locally. "
"The first argument is the key, the second argument is the Lua command "
"that is to be executed, and the optional third argument is a human "
"readable description of the command for documentation purposes."
},
{
"getKeyBinding",
&luascriptfunctions::getKeyBindings,
{},
"string",
"Returns a list of information about the keybindings for the provided "
"key. Each element in the list is a table describing the 'Command' that "
"was bound and whether it was a 'Remote' script or not."
}
}
};
}
} // namespace openspace::interaction
<|endoftext|> |
<commit_before>#include "Database.h"
#include "Exception.h"
#include "is_identifier.h"
/////////////////////////////////////////////////////////////////////////////
const std::map<Field_Id, std::string> &joedb::Database::get_fields
/////////////////////////////////////////////////////////////////////////////
(
Table_Id table_id
) const
{
auto table_it = tables.find(table_id);
if (table_it == tables.end())
throw Exception("get_fields: invalid table_id");
return table_it->second.field_names;
}
/////////////////////////////////////////////////////////////////////////////
const joedb::Type &joedb::Database::get_field_type
/////////////////////////////////////////////////////////////////////////////
(
Table_Id table_id,
Field_Id field_id
) const
{
static Type null_type;
auto table_it = tables.find(table_id);
if (table_it == tables.end())
return null_type;
auto &fields = table_it->second.get_fields();
auto field_it = fields.find(field_id);
if (field_it == fields.end())
return null_type;
return field_it->second.get_type();
}
/////////////////////////////////////////////////////////////////////////////
Record_Id joedb::Database::get_last_record_id(Table_Id table_id) const
/////////////////////////////////////////////////////////////////////////////
{
auto table_it = tables.find(table_id);
if (table_it == tables.end())
return 0;
return table_it->second.freedom.size();
}
/////////////////////////////////////////////////////////////////////////////
bool joedb::Database::is_used
/////////////////////////////////////////////////////////////////////////////
(
Table_Id table_id,
Record_Id record_id
) const
{
auto table_it = tables.find(table_id);
if (table_it == tables.end())
return false;
return table_it->second.freedom.is_used(record_id + 1);
}
#define TYPE_MACRO(type, return_type, type_id, R, W)\
return_type joedb::Database::get_##type_id(Table_Id table_id,\
Record_Id record_id,\
Field_Id field_id) const\
{\
auto table_it = tables.find(table_id);\
if (table_it == tables.end())\
throw Exception("get: invalid table_id");\
return table_it->second.get_##type_id(record_id, field_id);\
}
#include "TYPE_MACRO.h"
#undef TYPE_MACRO
/////////////////////////////////////////////////////////////////////////////
void joedb::Database::create_table(const std::string &name)
/////////////////////////////////////////////////////////////////////////////
{
if (!is_identifier(name))
throw Exception("create_table: invalid identifier");
if (find_table(name))
throw Exception("create_table: name already used");
++current_table_id;
tables.insert(std::make_pair(current_table_id, Table()));
table_names[current_table_id] = name;
}
/////////////////////////////////////////////////////////////////////////////
void joedb::Database::drop_table(Table_Id table_id)
/////////////////////////////////////////////////////////////////////////////
{
auto it = tables.find(table_id);
if (it == tables.end())
throw Exception("drop_table: invalid table_id");
table_names.erase(table_id);
tables.erase(it);
}
/////////////////////////////////////////////////////////////////////////////
void joedb::Database::rename_table
/////////////////////////////////////////////////////////////////////////////
(
Table_Id table_id,
const std::string &name
)
{
if (!is_identifier(name))
throw Exception("rename_table: invalid identifier");
auto table_it = tables.find(table_id);
if (table_it == tables.end())
throw Exception("rename_table: invalid table_id");
if (find_table(name) != 0)
throw Exception("rename_table: name already used");
table_names[table_id] = name;
}
/////////////////////////////////////////////////////////////////////////////
void joedb::Database::add_field
/////////////////////////////////////////////////////////////////////////////
(
Table_Id table_id,
const std::string &name,
Type type
)
{
if (!is_identifier(name))
throw Exception("add_field: invalid identifier");
auto it = tables.find(table_id);
if (it == tables.end())
throw Exception("add_field: invalid table_id");
it->second.add_field(name, type);
}
/////////////////////////////////////////////////////////////////////////////
void joedb::Database::drop_field(Table_Id table_id, Field_Id field_id)
/////////////////////////////////////////////////////////////////////////////
{
auto it = tables.find(table_id);
if (it == tables.end())
throw Exception("drop_field: invalid table_id");
it->second.drop_field(field_id);
}
/////////////////////////////////////////////////////////////////////////////
void joedb::Database::rename_field
/////////////////////////////////////////////////////////////////////////////
(
Table_Id table_id,
Field_Id field_id,
const std::string &name
)
{
if (!is_identifier(name))
throw Exception("rename_field: invalid identifier");
auto table_it = tables.find(table_id);
if (table_it == tables.end())
throw Exception("rename_field: invalid table_id");
auto &field_names = table_it->second.field_names;
auto field_it = field_names.find(field_id);
if (field_it == field_names.end())
throw Exception("rename_field: invalid field_id");
if (table_it->second.find_field(name))
throw Exception("rename_field: name already used");
field_it->second = name;
}
/////////////////////////////////////////////////////////////////////////////
void joedb::Database::insert_into(Table_Id table_id, Record_Id record_id)
/////////////////////////////////////////////////////////////////////////////
{
auto it = tables.find(table_id);
if (it == tables.end())
throw Exception("insert_into: invalid table_id");
if (record_id <= 0 || (max_record_id && record_id > max_record_id))
throw Exception("insert_into: too big");
it->second.insert_record(record_id);
}
/////////////////////////////////////////////////////////////////////////////
void joedb::Database::insert_vector
/////////////////////////////////////////////////////////////////////////////
(
Table_Id table_id,
Record_Id record_id,
Record_Id size
)
{
auto it = tables.find(table_id);
if (it == tables.end())
throw Exception("insert_vector: invalid table_id");
if (record_id <= 0 ||
size <= 0 ||
(max_record_id && (record_id > max_record_id || size > max_record_id)))
throw Exception("insert_vector: too big");
for (Record_Id i = 0; i < size; i++)
it->second.insert_record(record_id + i);
}
/////////////////////////////////////////////////////////////////////////////
void joedb::Database::delete_from
/////////////////////////////////////////////////////////////////////////////
(
Table_Id table_id,
Record_Id record_id
)
{
auto it = tables.find(table_id);
if (it == tables.end())
throw Exception("delete_from: invalid table_id");
it->second.delete_record(record_id);
}
/////////////////////////////////////////////////////////////////////////////
#define TYPE_MACRO(type, return_type, type_id, R, W)\
void joedb::Database::update_##type_id(Table_Id table_id,\
Record_Id record_id,\
Field_Id field_id,\
return_type value)\
{\
auto it = tables.find(table_id);\
if (it == tables.end())\
throw Exception("update: invalid table_id");\
it->second.update_##type_id(record_id, field_id, value);\
}\
void joedb::Database::update_vector_##type_id(Table_Id table_id,\
Record_Id record_id,\
Field_Id field_id,\
Record_Id size,\
const type *value)\
{\
auto it = tables.find(table_id);\
if (it == tables.end())\
throw Exception("update_vector: invalid table_id");\
it->second.update_vector_##type_id(record_id, field_id, size, value);\
}
#include "TYPE_MACRO.h"
#undef TYPE_MACRO
<commit_msg>Inserting vectors of size zero does nothing, but is allowed.<commit_after>#include "Database.h"
#include "Exception.h"
#include "is_identifier.h"
#include <sstream>
/////////////////////////////////////////////////////////////////////////////
const std::map<Field_Id, std::string> &joedb::Database::get_fields
/////////////////////////////////////////////////////////////////////////////
(
Table_Id table_id
) const
{
auto table_it = tables.find(table_id);
if (table_it == tables.end())
throw Exception("get_fields: invalid table_id");
return table_it->second.field_names;
}
/////////////////////////////////////////////////////////////////////////////
const joedb::Type &joedb::Database::get_field_type
/////////////////////////////////////////////////////////////////////////////
(
Table_Id table_id,
Field_Id field_id
) const
{
static Type null_type;
auto table_it = tables.find(table_id);
if (table_it == tables.end())
return null_type;
auto &fields = table_it->second.get_fields();
auto field_it = fields.find(field_id);
if (field_it == fields.end())
return null_type;
return field_it->second.get_type();
}
/////////////////////////////////////////////////////////////////////////////
Record_Id joedb::Database::get_last_record_id(Table_Id table_id) const
/////////////////////////////////////////////////////////////////////////////
{
auto table_it = tables.find(table_id);
if (table_it == tables.end())
return 0;
return table_it->second.freedom.size();
}
/////////////////////////////////////////////////////////////////////////////
bool joedb::Database::is_used
/////////////////////////////////////////////////////////////////////////////
(
Table_Id table_id,
Record_Id record_id
) const
{
auto table_it = tables.find(table_id);
if (table_it == tables.end())
return false;
return table_it->second.freedom.is_used(record_id + 1);
}
#define TYPE_MACRO(type, return_type, type_id, R, W)\
return_type joedb::Database::get_##type_id(Table_Id table_id,\
Record_Id record_id,\
Field_Id field_id) const\
{\
auto table_it = tables.find(table_id);\
if (table_it == tables.end())\
throw Exception("get: invalid table_id");\
return table_it->second.get_##type_id(record_id, field_id);\
}
#include "TYPE_MACRO.h"
#undef TYPE_MACRO
/////////////////////////////////////////////////////////////////////////////
void joedb::Database::create_table(const std::string &name)
/////////////////////////////////////////////////////////////////////////////
{
if (!is_identifier(name))
throw Exception("create_table: invalid identifier");
if (find_table(name))
throw Exception("create_table: name already used");
++current_table_id;
tables.insert(std::make_pair(current_table_id, Table()));
table_names[current_table_id] = name;
}
/////////////////////////////////////////////////////////////////////////////
void joedb::Database::drop_table(Table_Id table_id)
/////////////////////////////////////////////////////////////////////////////
{
auto it = tables.find(table_id);
if (it == tables.end())
throw Exception("drop_table: invalid table_id");
table_names.erase(table_id);
tables.erase(it);
}
/////////////////////////////////////////////////////////////////////////////
void joedb::Database::rename_table
/////////////////////////////////////////////////////////////////////////////
(
Table_Id table_id,
const std::string &name
)
{
if (!is_identifier(name))
throw Exception("rename_table: invalid identifier");
auto table_it = tables.find(table_id);
if (table_it == tables.end())
throw Exception("rename_table: invalid table_id");
if (find_table(name) != 0)
throw Exception("rename_table: name already used");
table_names[table_id] = name;
}
/////////////////////////////////////////////////////////////////////////////
void joedb::Database::add_field
/////////////////////////////////////////////////////////////////////////////
(
Table_Id table_id,
const std::string &name,
Type type
)
{
if (!is_identifier(name))
throw Exception("add_field: invalid identifier");
auto it = tables.find(table_id);
if (it == tables.end())
throw Exception("add_field: invalid table_id");
it->second.add_field(name, type);
}
/////////////////////////////////////////////////////////////////////////////
void joedb::Database::drop_field(Table_Id table_id, Field_Id field_id)
/////////////////////////////////////////////////////////////////////////////
{
auto it = tables.find(table_id);
if (it == tables.end())
throw Exception("drop_field: invalid table_id");
it->second.drop_field(field_id);
}
/////////////////////////////////////////////////////////////////////////////
void joedb::Database::rename_field
/////////////////////////////////////////////////////////////////////////////
(
Table_Id table_id,
Field_Id field_id,
const std::string &name
)
{
if (!is_identifier(name))
throw Exception("rename_field: invalid identifier");
auto table_it = tables.find(table_id);
if (table_it == tables.end())
throw Exception("rename_field: invalid table_id");
auto &field_names = table_it->second.field_names;
auto field_it = field_names.find(field_id);
if (field_it == field_names.end())
throw Exception("rename_field: invalid field_id");
if (table_it->second.find_field(name))
throw Exception("rename_field: name already used");
field_it->second = name;
}
/////////////////////////////////////////////////////////////////////////////
void joedb::Database::insert_into(Table_Id table_id, Record_Id record_id)
/////////////////////////////////////////////////////////////////////////////
{
auto it = tables.find(table_id);
if (it == tables.end())
throw Exception("insert_into: invalid table_id");
if (record_id <= 0 || (max_record_id && record_id > max_record_id))
throw Exception("insert_into: too big");
it->second.insert_record(record_id);
}
/////////////////////////////////////////////////////////////////////////////
void joedb::Database::insert_vector
/////////////////////////////////////////////////////////////////////////////
(
Table_Id table_id,
Record_Id record_id,
Record_Id size
)
{
auto it = tables.find(table_id);
if (it == tables.end())
throw Exception("insert_vector: invalid table_id");
if (record_id <= 0 ||
(max_record_id && (record_id > max_record_id || size > max_record_id)))
{
std::ostringstream error_message;
error_message << "insert_vector: ";
error_message << "record_id = " << record_id << "; ";
error_message << "size = " << size << "; ";
error_message << "max = " << max_record_id;
throw Exception(error_message.str());
}
for (Record_Id i = 0; i < size; i++)
it->second.insert_record(record_id + i);
}
/////////////////////////////////////////////////////////////////////////////
void joedb::Database::delete_from
/////////////////////////////////////////////////////////////////////////////
(
Table_Id table_id,
Record_Id record_id
)
{
auto it = tables.find(table_id);
if (it == tables.end())
throw Exception("delete_from: invalid table_id");
it->second.delete_record(record_id);
}
/////////////////////////////////////////////////////////////////////////////
#define TYPE_MACRO(type, return_type, type_id, R, W)\
void joedb::Database::update_##type_id(Table_Id table_id,\
Record_Id record_id,\
Field_Id field_id,\
return_type value)\
{\
auto it = tables.find(table_id);\
if (it == tables.end())\
throw Exception("update: invalid table_id");\
it->second.update_##type_id(record_id, field_id, value);\
}\
void joedb::Database::update_vector_##type_id(Table_Id table_id,\
Record_Id record_id,\
Field_Id field_id,\
Record_Id size,\
const type *value)\
{\
auto it = tables.find(table_id);\
if (it == tables.end())\
throw Exception("update_vector: invalid table_id");\
it->second.update_vector_##type_id(record_id, field_id, size, value);\
}
#include "TYPE_MACRO.h"
#undef TYPE_MACRO
<|endoftext|> |
<commit_before>/* bzflag
* Copyright (c) 1993 - 2007 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include "SDLPlatformFactory.h"
#include "SDLMedia.h"
#include "SDLDisplay.h"
#include "SDLJoystick.h"
#include "EvdevJoystick.h"
PlatformFactory* PlatformFactory::getInstance()
{
if (!instance)
instance = new SdlPlatformFactory;
return instance;
}
SdlPlatformFactory::SdlPlatformFactory()
{
// do nothing
}
SdlPlatformFactory::~SdlPlatformFactory()
{
// do nothing
}
BzfDisplay* SdlPlatformFactory::createDisplay(const char*, const char*)
{
SDLDisplay* display = new SDLDisplay();
if (!display || !display->isValid()) {
delete display;
return NULL;
}
return display;
}
BzfVisual* SdlPlatformFactory::createVisual(const BzfDisplay* display)
{
return new SDLVisual((const SDLDisplay*)display);
}
BzfWindow* SdlPlatformFactory::createWindow(const BzfDisplay* display,
BzfVisual* visual)
{
return new SDLWindow((const SDLDisplay*)display, (SDLVisual*)visual);
}
BzfMedia* SdlPlatformFactory::createMedia()
{
return new SDLMedia;
}
BzfJoystick* SdlPlatformFactory::createJoystick()
{
/* Use EvdevJoystick instead of SDLJoystick if we can.
* It has minor improvements in axis mapping and joystick
* enumeration, but the big selling point so far is that it
* supports force feedback.
*/
#ifdef HAVE_LINUX_INPUT_H
if (EvdevJoystick::isEvdevAvailable())
return new EvdevJoystick;
#endif
return new SDLJoystick;
}
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>include necessary headers<commit_after>/* bzflag
* Copyright (c) 1993 - 2007 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include "SDLPlatformFactory.h"
#include "SDLMedia.h"
#include "SDLDisplay.h"
#include "SDLJoystick.h"
#include "SDLVisual.h"
#include "SDLWindow.h"
#include "EvdevJoystick.h"
PlatformFactory* PlatformFactory::getInstance()
{
if (!instance)
instance = new SdlPlatformFactory;
return instance;
}
SdlPlatformFactory::SdlPlatformFactory()
{
// do nothing
}
SdlPlatformFactory::~SdlPlatformFactory()
{
// do nothing
}
BzfDisplay* SdlPlatformFactory::createDisplay(const char*, const char*)
{
SDLDisplay* display = new SDLDisplay();
if (!display || !display->isValid()) {
delete display;
return NULL;
}
return display;
}
BzfVisual* SdlPlatformFactory::createVisual(const BzfDisplay* display)
{
return new SDLVisual((const SDLDisplay*)display);
}
BzfWindow* SdlPlatformFactory::createWindow(const BzfDisplay* display,
BzfVisual* visual)
{
return new SDLWindow((const SDLDisplay*)display, (SDLVisual*)visual);
}
BzfMedia* SdlPlatformFactory::createMedia()
{
return new SDLMedia;
}
BzfJoystick* SdlPlatformFactory::createJoystick()
{
/* Use EvdevJoystick instead of SDLJoystick if we can.
* It has minor improvements in axis mapping and joystick
* enumeration, but the big selling point so far is that it
* supports force feedback.
*/
#ifdef HAVE_LINUX_INPUT_H
if (EvdevJoystick::isEvdevAvailable())
return new EvdevJoystick;
#endif
return new SDLJoystick;
}
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|> |
<commit_before>/* bzflag
* Copyright (c) 1993 - 2005 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include "WinPlatformFactory.h"
#ifdef HAVE_SDL
#include "SDLMedia.h"
#include "SDLDisplay.h"
#include "SDLJoystick.h"
#endif
#include "DXJoystick.h"
#ifdef HAVE_DSOUND_H
#include "WinMedia.h"
#endif
#include "WinDisplay.h"
#include "WinVisual.h"
#include "WinWindow.h"
#include "WinJoystick.h"
#include "StateDatabase.h"
PlatformFactory* PlatformFactory::getInstance()
{
if (!instance) instance = new WinPlatformFactory;
return instance;
}
#ifdef HAVE_SDL
SDLWindow* WinPlatformFactory::sdlWindow = NULL;
#endif
WinWindow* WinPlatformFactory::winWindow = NULL;
WinPlatformFactory::WinPlatformFactory()
{
// do nothing
}
WinPlatformFactory::~WinPlatformFactory()
{
// do nothing
}
BzfDisplay *WinPlatformFactory::createDisplay(const char* name,
const char* videoFormat)
{
bool useNative = true;
#ifdef HAVE_SDL
if (BZDB.isSet("SDLVideo") && BZDB.isTrue("SDLVideo"))
useNative = false;
#endif
// Just to stop compiler complaining about un-use of name & videoFormat
if (name == NULL && videoFormat == NULL)
;
BzfDisplay *display;
if (useNative) {
WinDisplay* winDisplay = new WinDisplay(name, videoFormat);
display = winDisplay;
} else {
#ifdef HAVE_SDL
SDLDisplay* sdlDisplay = new SDLDisplay();
display = sdlDisplay;
#else
display = NULL;
#endif
}
if (!display || !display->isValid()) {
delete display;
display = NULL;
}
return display;
}
BzfVisual* WinPlatformFactory::createVisual(
const BzfDisplay* display)
{
bool useNative = true;
#ifdef HAVE_SDL
if (BZDB.isSet("SDLVideo") && BZDB.isTrue("SDLVideo"))
useNative = false;
#endif
if (useNative)
return new WinVisual((const WinDisplay*)display);
else
#ifdef HAVE_SDL
return new SDLVisual((const SDLDisplay*)display);
#else
return NULL;
#endif
}
BzfWindow* WinPlatformFactory::createWindow(
const BzfDisplay* display, BzfVisual* visual)
{
bool useNative = true;
#ifdef HAVE_SDL
if (BZDB.isSet("SDLVideo") && BZDB.isTrue("SDLVideo"))
useNative = false;
#endif
if (useNative) {
winWindow = new WinWindow((const WinDisplay*)display, (WinVisual*)visual);
return winWindow;
} else {
#ifdef HAVE_SDL
sdlWindow = new SDLWindow((const SDLDisplay*)display, (SDLVisual*)visual);
return sdlWindow;
#else
return NULL;
#endif
}
}
BzfMedia* WinPlatformFactory::createMedia()
{
bool useNative = true;
#ifndef HAVE_DSOUND_H
useNative = false;
#endif
#ifdef HAVE_SDL
if (BZDB.isSet("SDLAudio") && BZDB.isTrue("SDLAudio"))
useNative = false;
#endif
if (useNative) {
#ifdef HAVE_DSOUND_H
return new WinMedia(window);
#else
return NULL;
#endif
} else {
#ifdef HAVE_SDL
return new SDLMedia();
#else
return NULL;
#endif
}
}
BzfJoystick* WinPlatformFactory::createJoystick()
{
bool useNative = true;
#ifdef HAVE_SDL
if (BZDB.isSet("SDLJoystick") && BZDB.isTrue("SDLJoystick"))
useNative = false;
#endif
if (useNative) {
#if defined(USE_DINPUT)
return new DXJoystick();
#else
return new WinJoystick();
#endif
} else {
#if defined(HAVE_SDL)
return new SDLJoystick();
#else
return NULL;
#endif
}
}
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>warning<commit_after>/* bzflag
* Copyright (c) 1993 - 2005 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include "WinPlatformFactory.h"
#ifdef HAVE_SDL
#include "SDLMedia.h"
#include "SDLDisplay.h"
#include "SDLJoystick.h"
#endif
#include "DXJoystick.h"
#ifdef HAVE_DSOUND_H
#include "WinMedia.h"
#endif
#include "WinDisplay.h"
#include "WinVisual.h"
#include "WinWindow.h"
#include "WinJoystick.h"
#include "StateDatabase.h"
PlatformFactory* PlatformFactory::getInstance()
{
if (!instance) instance = new WinPlatformFactory;
return instance;
}
#ifdef HAVE_SDL
SDLWindow* WinPlatformFactory::sdlWindow = NULL;
#endif
WinWindow* WinPlatformFactory::winWindow = NULL;
WinPlatformFactory::WinPlatformFactory()
{
// do nothing
}
WinPlatformFactory::~WinPlatformFactory()
{
// do nothing
}
BzfDisplay *WinPlatformFactory::createDisplay(const char* name,
const char* videoFormat)
{
bool useNative = true;
#ifdef HAVE_SDL
if (BZDB.isSet("SDLVideo") && BZDB.isTrue("SDLVideo"))
useNative = false;
#endif
// Just to stop compiler complaining about un-use of name & videoFormat
if (name == NULL && videoFormat == NULL) {};
BzfDisplay *display;
if (useNative) {
WinDisplay* winDisplay = new WinDisplay(name, videoFormat);
display = winDisplay;
} else {
#ifdef HAVE_SDL
SDLDisplay* sdlDisplay = new SDLDisplay();
display = sdlDisplay;
#else
display = NULL;
#endif
}
if (!display || !display->isValid()) {
delete display;
display = NULL;
}
return display;
}
BzfVisual* WinPlatformFactory::createVisual(
const BzfDisplay* display)
{
bool useNative = true;
#ifdef HAVE_SDL
if (BZDB.isSet("SDLVideo") && BZDB.isTrue("SDLVideo"))
useNative = false;
#endif
if (useNative)
return new WinVisual((const WinDisplay*)display);
else
#ifdef HAVE_SDL
return new SDLVisual((const SDLDisplay*)display);
#else
return NULL;
#endif
}
BzfWindow* WinPlatformFactory::createWindow(
const BzfDisplay* display, BzfVisual* visual)
{
bool useNative = true;
#ifdef HAVE_SDL
if (BZDB.isSet("SDLVideo") && BZDB.isTrue("SDLVideo"))
useNative = false;
#endif
if (useNative) {
winWindow = new WinWindow((const WinDisplay*)display, (WinVisual*)visual);
return winWindow;
} else {
#ifdef HAVE_SDL
sdlWindow = new SDLWindow((const SDLDisplay*)display, (SDLVisual*)visual);
return sdlWindow;
#else
return NULL;
#endif
}
}
BzfMedia* WinPlatformFactory::createMedia()
{
bool useNative = true;
#ifndef HAVE_DSOUND_H
useNative = false;
#endif
#ifdef HAVE_SDL
if (BZDB.isSet("SDLAudio") && BZDB.isTrue("SDLAudio"))
useNative = false;
#endif
if (useNative) {
#ifdef HAVE_DSOUND_H
return new WinMedia(window);
#else
return NULL;
#endif
} else {
#ifdef HAVE_SDL
return new SDLMedia();
#else
return NULL;
#endif
}
}
BzfJoystick* WinPlatformFactory::createJoystick()
{
bool useNative = true;
#ifdef HAVE_SDL
if (BZDB.isSet("SDLJoystick") && BZDB.isTrue("SDLJoystick"))
useNative = false;
#endif
if (useNative) {
#if defined(USE_DINPUT)
return new DXJoystick();
#else
return new WinJoystick();
#endif
} else {
#if defined(HAVE_SDL)
return new SDLJoystick();
#else
return NULL;
#endif
}
}
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|> |
<commit_before>/* libs/graphics/ports/SkFontHost_fontconfig.cpp
**
** Copyright 2008, Google Inc.
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
// -----------------------------------------------------------------------------
// This file provides implementations of the font resolution members of
// SkFontHost by using the fontconfig[1] library. Fontconfig is usually found
// on Linux systems and handles configuration, parsing and caching issues
// involved with enumerating and matching fonts.
//
// [1] http://fontconfig.org
// -----------------------------------------------------------------------------
#include <map>
#include <string>
#include <fontconfig/fontconfig.h>
#include "SkFontHost.h"
#include "SkStream.h"
// This is an extern from SkFontHost_FreeType
SkTypeface::Style find_name_and_style(SkStream* stream, SkString* name);
// -----------------------------------------------------------------------------
// The rest of Skia requires that fonts be identified by a unique unsigned id
// and that we be able to load them given the id. What we actually get from
// fontconfig is the filename of the font so we keep a locked map from
// filenames to fileid numbers and back.
//
// Note that there's also a unique id in the SkTypeface. This is unique over
// both filename and style. Thus we encode that id as (fileid << 8) | style.
// Although truetype fonts can support multiple faces in a single file, at the
// moment Skia doesn't.
// -----------------------------------------------------------------------------
static SkMutex global_fc_map_lock;
static std::map<std::string, unsigned> global_fc_map;
static std::map<unsigned, std::string> global_fc_map_inverted;
static std::map<uint32_t, SkTypeface *> global_fc_typefaces;
static unsigned global_fc_map_next_id = 0;
// This is the maximum size of the font cache.
static const unsigned kFontCacheMemoryBudget = 2 * 1024 * 1024; // 2MB
static unsigned UniqueIdToFileId(unsigned uniqueid)
{
return uniqueid >> 8;
}
static SkTypeface::Style UniqueIdToStyle(unsigned uniqueid)
{
return static_cast<SkTypeface::Style>(uniqueid & 0xff);
}
static unsigned FileIdAndStyleToUniqueId(unsigned fileid,
SkTypeface::Style style)
{
SkASSERT((style & 0xff) == style);
return (fileid << 8) | static_cast<int>(style);
}
// -----------------------------------------------------------------------------
// Normally we only return exactly the font asked for. In last-resort cases,
// the request is for one of the basic font names "Sans", "Serif" or
// "Monospace". This function tells you whether a given request is for such a
// fallback.
// -----------------------------------------------------------------------------
static bool IsFallbackFontAllowed(const char* request)
{
return strcmp(request, "Sans") == 0 ||
strcmp(request, "Serif") == 0 ||
strcmp(request, "Monospace") == 0;
}
class FontConfigTypeface : public SkTypeface {
public:
FontConfigTypeface(Style style, uint32_t id)
: SkTypeface(style, id)
{ }
};
// -----------------------------------------------------------------------------
// Find a matching font where @type (one of FC_*) is equal to @value. For a
// list of types, see http://fontconfig.org/fontconfig-devel/x19.html#AEN27.
// The variable arguments are a list of triples, just like the first three
// arguments, and must be NULL terminated.
//
// For example,
// FontMatchString(FC_FILE, FcTypeString, "/usr/share/fonts/myfont.ttf",
// NULL);
// -----------------------------------------------------------------------------
static FcPattern* FontMatch(const char* type, FcType vtype, const void* value,
...)
{
va_list ap;
va_start(ap, value);
FcPattern* pattern = FcPatternCreate();
const char* family_requested = NULL;
for (;;) {
FcValue fcvalue;
fcvalue.type = vtype;
switch (vtype) {
case FcTypeString:
fcvalue.u.s = (FcChar8*) value;
break;
case FcTypeInteger:
fcvalue.u.i = (int)(intptr_t)value;
break;
default:
SkASSERT(!"FontMatch unhandled type");
}
FcPatternAdd(pattern, type, fcvalue, 0);
if (vtype == FcTypeString && strcmp(type, FC_FAMILY) == 0)
family_requested = (const char*) value;
type = va_arg(ap, const char *);
if (!type)
break;
// FcType is promoted to int when passed through ...
vtype = static_cast<FcType>(va_arg(ap, int));
value = va_arg(ap, const void *);
};
va_end(ap);
FcConfigSubstitute(0, pattern, FcMatchPattern);
FcDefaultSubstitute(pattern);
// Font matching:
// CSS often specifies a fallback list of families:
// font-family: a, b, c, serif;
// However, fontconfig will always do its best to find *a* font when asked
// for something so we need a way to tell if the match which it has found is
// "good enough" for us. Otherwise, we can return NULL which gets piped up
// and lets WebKit know to try the next CSS family name. However, fontconfig
// configs allow substitutions (mapping "Arial -> Helvetica" etc) and we
// wish to support that.
//
// Thus, if a specific family is requested we set @family_requested. Then we
// record two strings: the family name after config processing and the
// family name after resolving. If the two are equal, it's a good match.
//
// So consider the case where a user has mapped Arial to Helvetica in their
// config.
// requested family: "Arial"
// post_config_family: "Helvetica"
// post_match_family: "Helvetica"
// -> good match
//
// and for a missing font:
// requested family: "Monaco"
// post_config_family: "Monaco"
// post_match_family: "Times New Roman"
// -> BAD match
//
// However, we special-case fallback fonts; see IsFallbackFontAllowed().
FcChar8* post_config_family;
FcPatternGetString(pattern, FC_FAMILY, 0, &post_config_family);
FcResult result;
FcPattern* match = FcFontMatch(0, pattern, &result);
if (!match) {
FcPatternDestroy(pattern);
return NULL;
}
FcChar8* post_match_family;
FcPatternGetString(match, FC_FAMILY, 0, &post_match_family);
const bool family_names_match =
!family_requested ?
true :
strcasecmp((char *)post_config_family, (char *)post_match_family) == 0;
FcPatternDestroy(pattern);
if (!family_names_match && !IsFallbackFontAllowed(family_requested)) {
FcPatternDestroy(match);
return NULL;
}
return match;
}
// -----------------------------------------------------------------------------
// Check to see if the filename has already been assigned a fileid and, if so,
// use it. Otherwise, assign one. Return the resulting fileid.
// -----------------------------------------------------------------------------
static unsigned FileIdFromFilename(const char* filename)
{
SkAutoMutexAcquire ac(global_fc_map_lock);
std::map<std::string, unsigned>::const_iterator i =
global_fc_map.find(filename);
if (i == global_fc_map.end()) {
const unsigned fileid = global_fc_map_next_id++;
global_fc_map[filename] = fileid;
global_fc_map_inverted[fileid] = filename;
return fileid;
} else {
return i->second;
}
}
// static
SkTypeface* SkFontHost::CreateTypeface(const SkTypeface* familyFace,
const char familyName[],
const void* data, size_t bytelength,
SkTypeface::Style style)
{
const char* resolved_family_name = NULL;
FcPattern* face_match = NULL;
{
SkAutoMutexAcquire ac(global_fc_map_lock);
FcInit();
}
if (familyFace) {
// Here we use the inverted global id map to find the filename from the
// SkTypeface object. Given the filename we can ask fontconfig for the
// familyname of the font.
SkAutoMutexAcquire ac(global_fc_map_lock);
const unsigned fileid = UniqueIdToFileId(familyFace->uniqueID());
std::map<unsigned, std::string>::const_iterator i =
global_fc_map_inverted.find(fileid);
if (i == global_fc_map_inverted.end())
return NULL;
FcInit();
face_match = FontMatch(FC_FILE, FcTypeString, i->second.c_str(),
NULL);
if (!face_match)
return NULL;
FcChar8* family;
if (FcPatternGetString(face_match, FC_FAMILY, 0, &family)) {
FcPatternDestroy(face_match);
return NULL;
}
// At this point, @family is pointing into the @face_match object so we
// cannot release it yet.
resolved_family_name = reinterpret_cast<char*>(family);
} else if (familyName) {
resolved_family_name = familyName;
} else {
return NULL;
}
// At this point, we have a resolved_family_name from somewhere
SkASSERT(resolved_family_name);
const int bold = style & SkTypeface::kBold ?
FC_WEIGHT_BOLD : FC_WEIGHT_NORMAL;
const int italic = style & SkTypeface::kItalic ?
FC_SLANT_ITALIC : FC_SLANT_ROMAN;
FcPattern* match = FontMatch(FC_FAMILY, FcTypeString, resolved_family_name,
FC_WEIGHT, FcTypeInteger, bold,
FC_SLANT, FcTypeInteger, italic,
NULL);
if (face_match)
FcPatternDestroy(face_match);
if (!match)
return NULL;
FcChar8* filename;
if (FcPatternGetString(match, FC_FILE, 0, &filename) != FcResultMatch) {
FcPatternDestroy(match);
return NULL;
}
// Now @filename is pointing into @match
const unsigned fileid = FileIdFromFilename(reinterpret_cast<char*>(filename));
const unsigned id = FileIdAndStyleToUniqueId(fileid, style);
SkTypeface* typeface = SkNEW_ARGS(FontConfigTypeface, (style, id));
FcPatternDestroy(match);
{
SkAutoMutexAcquire ac(global_fc_map_lock);
global_fc_typefaces[id] = typeface;
}
return typeface;
}
// static
SkTypeface* SkFontHost::CreateTypefaceFromStream(SkStream* stream)
{
SkASSERT(!"SkFontHost::CreateTypefaceFromStream unimplemented");
return NULL;
}
// static
SkTypeface* SkFontHost::CreateTypefaceFromFile(const char path[])
{
SkASSERT(!"SkFontHost::CreateTypefaceFromFile unimplemented");
return NULL;
}
// static
bool SkFontHost::ValidFontID(SkFontID uniqueID) {
SkAutoMutexAcquire ac(global_fc_map_lock);
return global_fc_typefaces.find(uniqueID) != global_fc_typefaces.end();
}
// static
SkStream* SkFontHost::OpenStream(uint32_t id)
{
SkAutoMutexAcquire ac(global_fc_map_lock);
const unsigned fileid = UniqueIdToFileId(id);
std::map<unsigned, std::string>::const_iterator i =
global_fc_map_inverted.find(fileid);
if (i == global_fc_map_inverted.end())
return NULL;
return SkNEW_ARGS(SkFILEStream, (i->second.c_str()));
}
size_t SkFontHost::GetFileName(SkFontID fontID, char path[], size_t length,
int32_t* index) {
SkAutoMutexAcquire ac(global_fc_map_lock);
const unsigned fileid = UniqueIdToFileId(id);
std::map<unsigned, std::string>::const_iterator i =
global_fc_map_inverted.find(fileid);
if (i == global_fc_map_inverted.end()) {
return 0;
}
const std::string& str = i->second;
if (path) {
memcpy(path, str.c_str(), SkMin32(str.size(), length));
}
if (index) { // TODO: check if we're in a TTC
*index = 0;
}
return str.size();
}
void SkFontHost::Serialize(const SkTypeface*, SkWStream*) {
SkASSERT(!"SkFontHost::Serialize unimplemented");
}
SkTypeface* SkFontHost::Deserialize(SkStream* stream) {
SkASSERT(!"SkFontHost::Deserialize unimplemented");
return NULL;
}
// static
uint32_t SkFontHost::NextLogicalFont(SkFontID fontID) {
// We don't handle font fallback, WebKit does.
return 0;
}
///////////////////////////////////////////////////////////////////////////////
size_t SkFontHost::ShouldPurgeFontCache(size_t sizeAllocatedSoFar)
{
if (sizeAllocatedSoFar > kFontCacheMemoryBudget)
return sizeAllocatedSoFar - kFontCacheMemoryBudget;
else
return 0; // nothing to do
}
<commit_msg>fix compile-error, mismatch between fontID and id<commit_after>/* libs/graphics/ports/SkFontHost_fontconfig.cpp
**
** Copyright 2008, Google Inc.
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
// -----------------------------------------------------------------------------
// This file provides implementations of the font resolution members of
// SkFontHost by using the fontconfig[1] library. Fontconfig is usually found
// on Linux systems and handles configuration, parsing and caching issues
// involved with enumerating and matching fonts.
//
// [1] http://fontconfig.org
// -----------------------------------------------------------------------------
#include <map>
#include <string>
#include <fontconfig/fontconfig.h>
#include "SkFontHost.h"
#include "SkStream.h"
// This is an extern from SkFontHost_FreeType
SkTypeface::Style find_name_and_style(SkStream* stream, SkString* name);
// -----------------------------------------------------------------------------
// The rest of Skia requires that fonts be identified by a unique unsigned id
// and that we be able to load them given the id. What we actually get from
// fontconfig is the filename of the font so we keep a locked map from
// filenames to fileid numbers and back.
//
// Note that there's also a unique id in the SkTypeface. This is unique over
// both filename and style. Thus we encode that id as (fileid << 8) | style.
// Although truetype fonts can support multiple faces in a single file, at the
// moment Skia doesn't.
// -----------------------------------------------------------------------------
static SkMutex global_fc_map_lock;
static std::map<std::string, unsigned> global_fc_map;
static std::map<unsigned, std::string> global_fc_map_inverted;
static std::map<uint32_t, SkTypeface *> global_fc_typefaces;
static unsigned global_fc_map_next_id = 0;
// This is the maximum size of the font cache.
static const unsigned kFontCacheMemoryBudget = 2 * 1024 * 1024; // 2MB
static unsigned UniqueIdToFileId(unsigned uniqueid)
{
return uniqueid >> 8;
}
static SkTypeface::Style UniqueIdToStyle(unsigned uniqueid)
{
return static_cast<SkTypeface::Style>(uniqueid & 0xff);
}
static unsigned FileIdAndStyleToUniqueId(unsigned fileid,
SkTypeface::Style style)
{
SkASSERT((style & 0xff) == style);
return (fileid << 8) | static_cast<int>(style);
}
// -----------------------------------------------------------------------------
// Normally we only return exactly the font asked for. In last-resort cases,
// the request is for one of the basic font names "Sans", "Serif" or
// "Monospace". This function tells you whether a given request is for such a
// fallback.
// -----------------------------------------------------------------------------
static bool IsFallbackFontAllowed(const char* request)
{
return strcmp(request, "Sans") == 0 ||
strcmp(request, "Serif") == 0 ||
strcmp(request, "Monospace") == 0;
}
class FontConfigTypeface : public SkTypeface {
public:
FontConfigTypeface(Style style, uint32_t id)
: SkTypeface(style, id)
{ }
};
// -----------------------------------------------------------------------------
// Find a matching font where @type (one of FC_*) is equal to @value. For a
// list of types, see http://fontconfig.org/fontconfig-devel/x19.html#AEN27.
// The variable arguments are a list of triples, just like the first three
// arguments, and must be NULL terminated.
//
// For example,
// FontMatchString(FC_FILE, FcTypeString, "/usr/share/fonts/myfont.ttf",
// NULL);
// -----------------------------------------------------------------------------
static FcPattern* FontMatch(const char* type, FcType vtype, const void* value,
...)
{
va_list ap;
va_start(ap, value);
FcPattern* pattern = FcPatternCreate();
const char* family_requested = NULL;
for (;;) {
FcValue fcvalue;
fcvalue.type = vtype;
switch (vtype) {
case FcTypeString:
fcvalue.u.s = (FcChar8*) value;
break;
case FcTypeInteger:
fcvalue.u.i = (int)(intptr_t)value;
break;
default:
SkASSERT(!"FontMatch unhandled type");
}
FcPatternAdd(pattern, type, fcvalue, 0);
if (vtype == FcTypeString && strcmp(type, FC_FAMILY) == 0)
family_requested = (const char*) value;
type = va_arg(ap, const char *);
if (!type)
break;
// FcType is promoted to int when passed through ...
vtype = static_cast<FcType>(va_arg(ap, int));
value = va_arg(ap, const void *);
};
va_end(ap);
FcConfigSubstitute(0, pattern, FcMatchPattern);
FcDefaultSubstitute(pattern);
// Font matching:
// CSS often specifies a fallback list of families:
// font-family: a, b, c, serif;
// However, fontconfig will always do its best to find *a* font when asked
// for something so we need a way to tell if the match which it has found is
// "good enough" for us. Otherwise, we can return NULL which gets piped up
// and lets WebKit know to try the next CSS family name. However, fontconfig
// configs allow substitutions (mapping "Arial -> Helvetica" etc) and we
// wish to support that.
//
// Thus, if a specific family is requested we set @family_requested. Then we
// record two strings: the family name after config processing and the
// family name after resolving. If the two are equal, it's a good match.
//
// So consider the case where a user has mapped Arial to Helvetica in their
// config.
// requested family: "Arial"
// post_config_family: "Helvetica"
// post_match_family: "Helvetica"
// -> good match
//
// and for a missing font:
// requested family: "Monaco"
// post_config_family: "Monaco"
// post_match_family: "Times New Roman"
// -> BAD match
//
// However, we special-case fallback fonts; see IsFallbackFontAllowed().
FcChar8* post_config_family;
FcPatternGetString(pattern, FC_FAMILY, 0, &post_config_family);
FcResult result;
FcPattern* match = FcFontMatch(0, pattern, &result);
if (!match) {
FcPatternDestroy(pattern);
return NULL;
}
FcChar8* post_match_family;
FcPatternGetString(match, FC_FAMILY, 0, &post_match_family);
const bool family_names_match =
!family_requested ?
true :
strcasecmp((char *)post_config_family, (char *)post_match_family) == 0;
FcPatternDestroy(pattern);
if (!family_names_match && !IsFallbackFontAllowed(family_requested)) {
FcPatternDestroy(match);
return NULL;
}
return match;
}
// -----------------------------------------------------------------------------
// Check to see if the filename has already been assigned a fileid and, if so,
// use it. Otherwise, assign one. Return the resulting fileid.
// -----------------------------------------------------------------------------
static unsigned FileIdFromFilename(const char* filename)
{
SkAutoMutexAcquire ac(global_fc_map_lock);
std::map<std::string, unsigned>::const_iterator i =
global_fc_map.find(filename);
if (i == global_fc_map.end()) {
const unsigned fileid = global_fc_map_next_id++;
global_fc_map[filename] = fileid;
global_fc_map_inverted[fileid] = filename;
return fileid;
} else {
return i->second;
}
}
// static
SkTypeface* SkFontHost::CreateTypeface(const SkTypeface* familyFace,
const char familyName[],
const void* data, size_t bytelength,
SkTypeface::Style style)
{
const char* resolved_family_name = NULL;
FcPattern* face_match = NULL;
{
SkAutoMutexAcquire ac(global_fc_map_lock);
FcInit();
}
if (familyFace) {
// Here we use the inverted global id map to find the filename from the
// SkTypeface object. Given the filename we can ask fontconfig for the
// familyname of the font.
SkAutoMutexAcquire ac(global_fc_map_lock);
const unsigned fileid = UniqueIdToFileId(familyFace->uniqueID());
std::map<unsigned, std::string>::const_iterator i =
global_fc_map_inverted.find(fileid);
if (i == global_fc_map_inverted.end())
return NULL;
FcInit();
face_match = FontMatch(FC_FILE, FcTypeString, i->second.c_str(),
NULL);
if (!face_match)
return NULL;
FcChar8* family;
if (FcPatternGetString(face_match, FC_FAMILY, 0, &family)) {
FcPatternDestroy(face_match);
return NULL;
}
// At this point, @family is pointing into the @face_match object so we
// cannot release it yet.
resolved_family_name = reinterpret_cast<char*>(family);
} else if (familyName) {
resolved_family_name = familyName;
} else {
return NULL;
}
// At this point, we have a resolved_family_name from somewhere
SkASSERT(resolved_family_name);
const int bold = style & SkTypeface::kBold ?
FC_WEIGHT_BOLD : FC_WEIGHT_NORMAL;
const int italic = style & SkTypeface::kItalic ?
FC_SLANT_ITALIC : FC_SLANT_ROMAN;
FcPattern* match = FontMatch(FC_FAMILY, FcTypeString, resolved_family_name,
FC_WEIGHT, FcTypeInteger, bold,
FC_SLANT, FcTypeInteger, italic,
NULL);
if (face_match)
FcPatternDestroy(face_match);
if (!match)
return NULL;
FcChar8* filename;
if (FcPatternGetString(match, FC_FILE, 0, &filename) != FcResultMatch) {
FcPatternDestroy(match);
return NULL;
}
// Now @filename is pointing into @match
const unsigned fileid = FileIdFromFilename(reinterpret_cast<char*>(filename));
const unsigned id = FileIdAndStyleToUniqueId(fileid, style);
SkTypeface* typeface = SkNEW_ARGS(FontConfigTypeface, (style, id));
FcPatternDestroy(match);
{
SkAutoMutexAcquire ac(global_fc_map_lock);
global_fc_typefaces[id] = typeface;
}
return typeface;
}
// static
SkTypeface* SkFontHost::CreateTypefaceFromStream(SkStream* stream)
{
SkASSERT(!"SkFontHost::CreateTypefaceFromStream unimplemented");
return NULL;
}
// static
SkTypeface* SkFontHost::CreateTypefaceFromFile(const char path[])
{
SkASSERT(!"SkFontHost::CreateTypefaceFromFile unimplemented");
return NULL;
}
// static
bool SkFontHost::ValidFontID(SkFontID uniqueID) {
SkAutoMutexAcquire ac(global_fc_map_lock);
return global_fc_typefaces.find(uniqueID) != global_fc_typefaces.end();
}
// static
SkStream* SkFontHost::OpenStream(uint32_t id)
{
SkAutoMutexAcquire ac(global_fc_map_lock);
const unsigned fileid = UniqueIdToFileId(id);
std::map<unsigned, std::string>::const_iterator i =
global_fc_map_inverted.find(fileid);
if (i == global_fc_map_inverted.end())
return NULL;
return SkNEW_ARGS(SkFILEStream, (i->second.c_str()));
}
size_t SkFontHost::GetFileName(SkFontID fontID, char path[], size_t length,
int32_t* index) {
SkAutoMutexAcquire ac(global_fc_map_lock);
const unsigned fileid = UniqueIdToFileId(fontID);
std::map<unsigned, std::string>::const_iterator i =
global_fc_map_inverted.find(fileid);
if (i == global_fc_map_inverted.end()) {
return 0;
}
const std::string& str = i->second;
if (path) {
memcpy(path, str.c_str(), SkMin32(str.size(), length));
}
if (index) { // TODO: check if we're in a TTC
*index = 0;
}
return str.size();
}
void SkFontHost::Serialize(const SkTypeface*, SkWStream*) {
SkASSERT(!"SkFontHost::Serialize unimplemented");
}
SkTypeface* SkFontHost::Deserialize(SkStream* stream) {
SkASSERT(!"SkFontHost::Deserialize unimplemented");
return NULL;
}
// static
uint32_t SkFontHost::NextLogicalFont(SkFontID fontID) {
// We don't handle font fallback, WebKit does.
return 0;
}
///////////////////////////////////////////////////////////////////////////////
size_t SkFontHost::ShouldPurgeFontCache(size_t sizeAllocatedSoFar)
{
if (sizeAllocatedSoFar > kFontCacheMemoryBudget)
return sizeAllocatedSoFar - kFontCacheMemoryBudget;
else
return 0; // nothing to do
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011-2018 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include <config/bitcoin-config.h>
#endif
#include <fs.h>
#include <qt/intro.h>
#include <qt/forms/ui_intro.h>
#include <qt/guiconstants.h>
#include <qt/guiutil.h>
#include <interfaces/node.h>
#include <util/system.h>
#include <QFileDialog>
#include <QSettings>
#include <QMessageBox>
#include <cmath>
/* Total required space (in GB) depending on user choice (prune, not prune) */
static uint64_t requiredSpace;
/* Check free space asynchronously to prevent hanging the UI thread.
Up to one request to check a path is in flight to this thread; when the check()
function runs, the current path is requested from the associated Intro object.
The reply is sent back through a signal.
This ensures that no queue of checking requests is built up while the user is
still entering the path, and that always the most recently entered path is checked as
soon as the thread becomes available.
*/
class FreespaceChecker : public QObject
{
Q_OBJECT
public:
explicit FreespaceChecker(Intro *intro);
enum Status {
ST_OK,
ST_ERROR
};
public Q_SLOTS:
void check();
Q_SIGNALS:
void reply(int status, const QString &message, quint64 available);
private:
Intro *intro;
};
#include <qt/intro.moc>
FreespaceChecker::FreespaceChecker(Intro *_intro)
{
this->intro = _intro;
}
void FreespaceChecker::check()
{
QString dataDirStr = intro->getPathToCheck();
fs::path dataDir = GUIUtil::qstringToBoostPath(dataDirStr);
uint64_t freeBytesAvailable = 0;
int replyStatus = ST_OK;
QString replyMessage = tr("A new data directory will be created.");
/* Find first parent that exists, so that fs::space does not fail */
fs::path parentDir = dataDir;
fs::path parentDirOld = fs::path();
while(parentDir.has_parent_path() && !fs::exists(parentDir))
{
parentDir = parentDir.parent_path();
/* Check if we make any progress, break if not to prevent an infinite loop here */
if (parentDirOld == parentDir)
break;
parentDirOld = parentDir;
}
try {
freeBytesAvailable = fs::space(parentDir).available;
if(fs::exists(dataDir))
{
if(fs::is_directory(dataDir))
{
QString separator = "<code>" + QDir::toNativeSeparators("/") + tr("name") + "</code>";
replyStatus = ST_OK;
replyMessage = tr("Directory already exists. Add %1 if you intend to create a new directory here.").arg(separator);
} else {
replyStatus = ST_ERROR;
replyMessage = tr("Path already exists, and is not a directory.");
}
}
} catch (const fs::filesystem_error&)
{
/* Parent directory does not exist or is not accessible */
replyStatus = ST_ERROR;
replyMessage = tr("Cannot create data directory here.");
}
Q_EMIT reply(replyStatus, replyMessage, freeBytesAvailable);
}
Intro::Intro(QWidget *parent, uint64_t blockchain_size, uint64_t chain_state_size) :
QDialog(parent),
ui(new Ui::Intro),
thread(nullptr),
signalled(false),
m_blockchain_size(blockchain_size),
m_chain_state_size(chain_state_size)
{
ui->setupUi(this);
ui->welcomeLabel->setText(ui->welcomeLabel->text().arg(tr(PACKAGE_NAME)));
ui->storageLabel->setText(ui->storageLabel->text().arg(tr(PACKAGE_NAME)));
ui->lblExplanation1->setText(ui->lblExplanation1->text()
.arg(tr(PACKAGE_NAME))
.arg(m_blockchain_size)
.arg(2017)
.arg(tr("Qtum"))
);
ui->lblExplanation2->setText(ui->lblExplanation2->text().arg(tr(PACKAGE_NAME)));
uint64_t pruneTarget = std::max<int64_t>(0, gArgs.GetArg("-prune", 0));
requiredSpace = m_blockchain_size;
QString storageRequiresMsg = tr("At least %1 GB of data will be stored in this directory, and it will grow over time.");
if (pruneTarget) {
uint64_t prunedGBs = std::ceil(pruneTarget * 1024 * 1024.0 / GB_BYTES);
if (prunedGBs <= requiredSpace) {
requiredSpace = prunedGBs;
storageRequiresMsg = tr("Approximately %1 GB of data will be stored in this directory.");
}
ui->lblExplanation3->setVisible(true);
} else {
ui->lblExplanation3->setVisible(false);
}
requiredSpace += m_chain_state_size;
ui->sizeWarningLabel->setText(
tr("%1 will download and store a copy of the Qtum block chain.").arg(tr(PACKAGE_NAME)) + " " +
storageRequiresMsg.arg(requiredSpace) + " " +
tr("The wallet will also be stored in this directory.")
);
startThread();
}
Intro::~Intro()
{
delete ui;
/* Ensure thread is finished before it is deleted */
thread->quit();
thread->wait();
}
QString Intro::getDataDirectory()
{
return ui->dataDirectory->text();
}
void Intro::setDataDirectory(const QString &dataDir)
{
ui->dataDirectory->setText(dataDir);
if(dataDir == getDefaultDataDirectory())
{
ui->dataDirDefault->setChecked(true);
ui->dataDirectory->setEnabled(false);
ui->ellipsisButton->setEnabled(false);
} else {
ui->dataDirCustom->setChecked(true);
ui->dataDirectory->setEnabled(true);
ui->ellipsisButton->setEnabled(true);
}
}
QString Intro::getDefaultDataDirectory()
{
return GUIUtil::boostPathToQString(GetDefaultDataDir());
}
bool Intro::pickDataDirectory(interfaces::Node& node)
{
QSettings settings;
/* If data directory provided on command line, no need to look at settings
or show a picking dialog */
if(!gArgs.GetArg("-datadir", "").empty())
return true;
/* 1) Default data directory for operating system */
QString dataDir = getDefaultDataDirectory();
/* 2) Allow QSettings to override default dir */
dataDir = settings.value("strDataDir", dataDir).toString();
if(!fs::exists(GUIUtil::qstringToBoostPath(dataDir)) || gArgs.GetBoolArg("-choosedatadir", DEFAULT_CHOOSE_DATADIR) || settings.value("fReset", false).toBool() || gArgs.GetBoolArg("-resetguisettings", false))
{
/* Use selectParams here to guarantee Params() can be used by node interface */
try {
node.selectParams(gArgs.GetChainName());
} catch (const std::exception&) {
return false;
}
/* If current default data directory does not exist, let the user choose one */
Intro intro(0, node.getAssumedBlockchainSize(), node.getAssumedChainStateSize());
intro.setDataDirectory(dataDir);
intro.setWindowIcon(QIcon(":icons/bitcoin"));
while(true)
{
if(!intro.exec())
{
/* Cancel clicked */
return false;
}
dataDir = intro.getDataDirectory();
try {
if (TryCreateDirectories(GUIUtil::qstringToBoostPath(dataDir))) {
// If a new data directory has been created, make wallets subdirectory too
TryCreateDirectories(GUIUtil::qstringToBoostPath(dataDir) / "wallets");
}
break;
} catch (const fs::filesystem_error&) {
QMessageBox::critical(nullptr, tr(PACKAGE_NAME),
tr("Error: Specified data directory \"%1\" cannot be created.").arg(dataDir));
/* fall through, back to choosing screen */
}
}
settings.setValue("strDataDir", dataDir);
settings.setValue("fReset", false);
}
/* Only override -datadir if different from the default, to make it possible to
* override -datadir in the bitcoin.conf file in the default data directory
* (to be consistent with bitcoind behavior)
*/
if(dataDir != getDefaultDataDirectory()) {
node.softSetArg("-datadir", GUIUtil::qstringToBoostPath(dataDir).string()); // use OS locale for path setting
}
return true;
}
void Intro::setStatus(int status, const QString &message, quint64 bytesAvailable)
{
switch(status)
{
case FreespaceChecker::ST_OK:
ui->errorMessage->setText(message);
ui->errorMessage->setStyleSheet("");
break;
case FreespaceChecker::ST_ERROR:
ui->errorMessage->setText(tr("Error") + ": " + message);
ui->errorMessage->setStyleSheet("QLabel { color: #800000 }");
break;
}
/* Indicate number of bytes available */
if(status == FreespaceChecker::ST_ERROR)
{
ui->freeSpace->setText("");
} else {
QString freeString = tr("%n GB of free space available", "", bytesAvailable/GB_BYTES);
if(bytesAvailable < requiredSpace * GB_BYTES)
{
freeString += " " + tr("(of %n GB needed)", "", requiredSpace);
ui->freeSpace->setStyleSheet("QLabel { color: #800000 }");
} else {
ui->freeSpace->setStyleSheet("");
}
ui->freeSpace->setText(freeString + ".");
}
/* Don't allow confirm in ERROR state */
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(status != FreespaceChecker::ST_ERROR);
}
void Intro::on_dataDirectory_textChanged(const QString &dataDirStr)
{
/* Disable OK button until check result comes in */
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
checkPath(dataDirStr);
}
void Intro::on_ellipsisButton_clicked()
{
QString dir = QDir::toNativeSeparators(QFileDialog::getExistingDirectory(nullptr, "Choose data directory", ui->dataDirectory->text()));
if(!dir.isEmpty())
ui->dataDirectory->setText(dir);
}
void Intro::on_dataDirDefault_clicked()
{
setDataDirectory(getDefaultDataDirectory());
}
void Intro::on_dataDirCustom_clicked()
{
ui->dataDirectory->setEnabled(true);
ui->ellipsisButton->setEnabled(true);
setDataDirectory(QDir::homePath());
}
void Intro::startThread()
{
thread = new QThread(this);
FreespaceChecker *executor = new FreespaceChecker(this);
executor->moveToThread(thread);
connect(executor, &FreespaceChecker::reply, this, &Intro::setStatus);
connect(this, &Intro::requestCheck, executor, &FreespaceChecker::check);
/* make sure executor object is deleted in its own thread */
connect(thread, &QThread::finished, executor, &QObject::deleteLater);
thread->start();
}
void Intro::checkPath(const QString &dataDir)
{
mutex.lock();
pathToCheck = dataDir;
if(!signalled)
{
signalled = true;
Q_EMIT requestCheck();
}
mutex.unlock();
}
QString Intro::getPathToCheck()
{
QString retval;
mutex.lock();
retval = pathToCheck;
signalled = false; /* new request can be queued now */
mutex.unlock();
return retval;
}
<commit_msg>Set custom datadir to home for OSX only<commit_after>// Copyright (c) 2011-2018 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include <config/bitcoin-config.h>
#endif
#include <fs.h>
#include <qt/intro.h>
#include <qt/forms/ui_intro.h>
#include <qt/guiconstants.h>
#include <qt/guiutil.h>
#include <interfaces/node.h>
#include <util/system.h>
#include <QFileDialog>
#include <QSettings>
#include <QMessageBox>
#include <cmath>
/* Total required space (in GB) depending on user choice (prune, not prune) */
static uint64_t requiredSpace;
/* Check free space asynchronously to prevent hanging the UI thread.
Up to one request to check a path is in flight to this thread; when the check()
function runs, the current path is requested from the associated Intro object.
The reply is sent back through a signal.
This ensures that no queue of checking requests is built up while the user is
still entering the path, and that always the most recently entered path is checked as
soon as the thread becomes available.
*/
class FreespaceChecker : public QObject
{
Q_OBJECT
public:
explicit FreespaceChecker(Intro *intro);
enum Status {
ST_OK,
ST_ERROR
};
public Q_SLOTS:
void check();
Q_SIGNALS:
void reply(int status, const QString &message, quint64 available);
private:
Intro *intro;
};
#include <qt/intro.moc>
FreespaceChecker::FreespaceChecker(Intro *_intro)
{
this->intro = _intro;
}
void FreespaceChecker::check()
{
QString dataDirStr = intro->getPathToCheck();
fs::path dataDir = GUIUtil::qstringToBoostPath(dataDirStr);
uint64_t freeBytesAvailable = 0;
int replyStatus = ST_OK;
QString replyMessage = tr("A new data directory will be created.");
/* Find first parent that exists, so that fs::space does not fail */
fs::path parentDir = dataDir;
fs::path parentDirOld = fs::path();
while(parentDir.has_parent_path() && !fs::exists(parentDir))
{
parentDir = parentDir.parent_path();
/* Check if we make any progress, break if not to prevent an infinite loop here */
if (parentDirOld == parentDir)
break;
parentDirOld = parentDir;
}
try {
freeBytesAvailable = fs::space(parentDir).available;
if(fs::exists(dataDir))
{
if(fs::is_directory(dataDir))
{
QString separator = "<code>" + QDir::toNativeSeparators("/") + tr("name") + "</code>";
replyStatus = ST_OK;
replyMessage = tr("Directory already exists. Add %1 if you intend to create a new directory here.").arg(separator);
} else {
replyStatus = ST_ERROR;
replyMessage = tr("Path already exists, and is not a directory.");
}
}
} catch (const fs::filesystem_error&)
{
/* Parent directory does not exist or is not accessible */
replyStatus = ST_ERROR;
replyMessage = tr("Cannot create data directory here.");
}
Q_EMIT reply(replyStatus, replyMessage, freeBytesAvailable);
}
Intro::Intro(QWidget *parent, uint64_t blockchain_size, uint64_t chain_state_size) :
QDialog(parent),
ui(new Ui::Intro),
thread(nullptr),
signalled(false),
m_blockchain_size(blockchain_size),
m_chain_state_size(chain_state_size)
{
ui->setupUi(this);
ui->welcomeLabel->setText(ui->welcomeLabel->text().arg(tr(PACKAGE_NAME)));
ui->storageLabel->setText(ui->storageLabel->text().arg(tr(PACKAGE_NAME)));
ui->lblExplanation1->setText(ui->lblExplanation1->text()
.arg(tr(PACKAGE_NAME))
.arg(m_blockchain_size)
.arg(2017)
.arg(tr("Qtum"))
);
ui->lblExplanation2->setText(ui->lblExplanation2->text().arg(tr(PACKAGE_NAME)));
uint64_t pruneTarget = std::max<int64_t>(0, gArgs.GetArg("-prune", 0));
requiredSpace = m_blockchain_size;
QString storageRequiresMsg = tr("At least %1 GB of data will be stored in this directory, and it will grow over time.");
if (pruneTarget) {
uint64_t prunedGBs = std::ceil(pruneTarget * 1024 * 1024.0 / GB_BYTES);
if (prunedGBs <= requiredSpace) {
requiredSpace = prunedGBs;
storageRequiresMsg = tr("Approximately %1 GB of data will be stored in this directory.");
}
ui->lblExplanation3->setVisible(true);
} else {
ui->lblExplanation3->setVisible(false);
}
requiredSpace += m_chain_state_size;
ui->sizeWarningLabel->setText(
tr("%1 will download and store a copy of the Qtum block chain.").arg(tr(PACKAGE_NAME)) + " " +
storageRequiresMsg.arg(requiredSpace) + " " +
tr("The wallet will also be stored in this directory.")
);
startThread();
}
Intro::~Intro()
{
delete ui;
/* Ensure thread is finished before it is deleted */
thread->quit();
thread->wait();
}
QString Intro::getDataDirectory()
{
return ui->dataDirectory->text();
}
void Intro::setDataDirectory(const QString &dataDir)
{
ui->dataDirectory->setText(dataDir);
if(dataDir == getDefaultDataDirectory())
{
ui->dataDirDefault->setChecked(true);
ui->dataDirectory->setEnabled(false);
ui->ellipsisButton->setEnabled(false);
} else {
ui->dataDirCustom->setChecked(true);
ui->dataDirectory->setEnabled(true);
ui->ellipsisButton->setEnabled(true);
}
}
QString Intro::getDefaultDataDirectory()
{
return GUIUtil::boostPathToQString(GetDefaultDataDir());
}
bool Intro::pickDataDirectory(interfaces::Node& node)
{
QSettings settings;
/* If data directory provided on command line, no need to look at settings
or show a picking dialog */
if(!gArgs.GetArg("-datadir", "").empty())
return true;
/* 1) Default data directory for operating system */
QString dataDir = getDefaultDataDirectory();
/* 2) Allow QSettings to override default dir */
dataDir = settings.value("strDataDir", dataDir).toString();
if(!fs::exists(GUIUtil::qstringToBoostPath(dataDir)) || gArgs.GetBoolArg("-choosedatadir", DEFAULT_CHOOSE_DATADIR) || settings.value("fReset", false).toBool() || gArgs.GetBoolArg("-resetguisettings", false))
{
/* Use selectParams here to guarantee Params() can be used by node interface */
try {
node.selectParams(gArgs.GetChainName());
} catch (const std::exception&) {
return false;
}
/* If current default data directory does not exist, let the user choose one */
Intro intro(0, node.getAssumedBlockchainSize(), node.getAssumedChainStateSize());
intro.setDataDirectory(dataDir);
intro.setWindowIcon(QIcon(":icons/bitcoin"));
while(true)
{
if(!intro.exec())
{
/* Cancel clicked */
return false;
}
dataDir = intro.getDataDirectory();
try {
if (TryCreateDirectories(GUIUtil::qstringToBoostPath(dataDir))) {
// If a new data directory has been created, make wallets subdirectory too
TryCreateDirectories(GUIUtil::qstringToBoostPath(dataDir) / "wallets");
}
break;
} catch (const fs::filesystem_error&) {
QMessageBox::critical(nullptr, tr(PACKAGE_NAME),
tr("Error: Specified data directory \"%1\" cannot be created.").arg(dataDir));
/* fall through, back to choosing screen */
}
}
settings.setValue("strDataDir", dataDir);
settings.setValue("fReset", false);
}
/* Only override -datadir if different from the default, to make it possible to
* override -datadir in the bitcoin.conf file in the default data directory
* (to be consistent with bitcoind behavior)
*/
if(dataDir != getDefaultDataDirectory()) {
node.softSetArg("-datadir", GUIUtil::qstringToBoostPath(dataDir).string()); // use OS locale for path setting
}
return true;
}
void Intro::setStatus(int status, const QString &message, quint64 bytesAvailable)
{
switch(status)
{
case FreespaceChecker::ST_OK:
ui->errorMessage->setText(message);
ui->errorMessage->setStyleSheet("");
break;
case FreespaceChecker::ST_ERROR:
ui->errorMessage->setText(tr("Error") + ": " + message);
ui->errorMessage->setStyleSheet("QLabel { color: #800000 }");
break;
}
/* Indicate number of bytes available */
if(status == FreespaceChecker::ST_ERROR)
{
ui->freeSpace->setText("");
} else {
QString freeString = tr("%n GB of free space available", "", bytesAvailable/GB_BYTES);
if(bytesAvailable < requiredSpace * GB_BYTES)
{
freeString += " " + tr("(of %n GB needed)", "", requiredSpace);
ui->freeSpace->setStyleSheet("QLabel { color: #800000 }");
} else {
ui->freeSpace->setStyleSheet("");
}
ui->freeSpace->setText(freeString + ".");
}
/* Don't allow confirm in ERROR state */
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(status != FreespaceChecker::ST_ERROR);
}
void Intro::on_dataDirectory_textChanged(const QString &dataDirStr)
{
/* Disable OK button until check result comes in */
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
checkPath(dataDirStr);
}
void Intro::on_ellipsisButton_clicked()
{
QString dir = QDir::toNativeSeparators(QFileDialog::getExistingDirectory(nullptr, "Choose data directory", ui->dataDirectory->text()));
if(!dir.isEmpty())
ui->dataDirectory->setText(dir);
}
void Intro::on_dataDirDefault_clicked()
{
setDataDirectory(getDefaultDataDirectory());
}
void Intro::on_dataDirCustom_clicked()
{
ui->dataDirectory->setEnabled(true);
ui->ellipsisButton->setEnabled(true);
#ifdef MAC_OSX
setDataDirectory(QDir::homePath()+"/Qtum");
#endif
}
void Intro::startThread()
{
thread = new QThread(this);
FreespaceChecker *executor = new FreespaceChecker(this);
executor->moveToThread(thread);
connect(executor, &FreespaceChecker::reply, this, &Intro::setStatus);
connect(this, &Intro::requestCheck, executor, &FreespaceChecker::check);
/* make sure executor object is deleted in its own thread */
connect(thread, &QThread::finished, executor, &QObject::deleteLater);
thread->start();
}
void Intro::checkPath(const QString &dataDir)
{
mutex.lock();
pathToCheck = dataDir;
if(!signalled)
{
signalled = true;
Q_EMIT requestCheck();
}
mutex.unlock();
}
QString Intro::getPathToCheck()
{
QString retval;
mutex.lock();
retval = pathToCheck;
signalled = false; /* new request can be queued now */
mutex.unlock();
return retval;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011-2014 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "intro.h"
#include "ui_intro.h"
#include "guiutil.h"
#include "util.h"
#include <boost/filesystem.hpp>
#include <QFileDialog>
#include <QSettings>
#include <QMessageBox>
/* Minimum free space (in bytes) needed for data directory */
static const uint64_t GB_BYTES = 1000000000LL;
static const uint64_t BLOCK_CHAIN_SIZE = 20LL * GB_BYTES;
/* Check free space asynchronously to prevent hanging the UI thread.
Up to one request to check a path is in flight to this thread; when the check()
function runs, the current path is requested from the associated Intro object.
The reply is sent back through a signal.
This ensures that no queue of checking requests is built up while the user is
still entering the path, and that always the most recently entered path is checked as
soon as the thread becomes available.
*/
class FreespaceChecker : public QObject
{
Q_OBJECT
public:
FreespaceChecker(Intro *intro);
enum Status {
ST_OK,
ST_ERROR
};
public slots:
void check();
signals:
void reply(int status, const QString &message, quint64 available);
private:
Intro *intro;
};
#include "intro.moc"
FreespaceChecker::FreespaceChecker(Intro *intro)
{
this->intro = intro;
}
void FreespaceChecker::check()
{
namespace fs = boost::filesystem;
QString dataDirStr = intro->getPathToCheck();
fs::path dataDir = GUIUtil::qstringToBoostPath(dataDirStr);
uint64_t freeBytesAvailable = 0;
int replyStatus = ST_OK;
QString replyMessage = tr("A new data directory will be created.");
/* Find first parent that exists, so that fs::space does not fail */
fs::path parentDir = dataDir;
fs::path parentDirOld = fs::path();
while(parentDir.has_parent_path() && !fs::exists(parentDir))
{
parentDir = parentDir.parent_path();
/* Check if we make any progress, break if not to prevent an infinite loop here */
if (parentDirOld == parentDir)
break;
parentDirOld = parentDir;
}
try {
freeBytesAvailable = fs::space(parentDir).available;
if(fs::exists(dataDir))
{
if(fs::is_directory(dataDir))
{
QString separator = "<code>" + QDir::toNativeSeparators("/") + tr("name") + "</code>";
replyStatus = ST_OK;
replyMessage = tr("Directory already exists. Add %1 if you intend to create a new directory here.").arg(separator);
} else {
replyStatus = ST_ERROR;
replyMessage = tr("Path already exists, and is not a directory.");
}
}
} catch(fs::filesystem_error &e)
{
/* Parent directory does not exist or is not accessible */
replyStatus = ST_ERROR;
replyMessage = tr("Cannot create data directory here.");
}
emit reply(replyStatus, replyMessage, freeBytesAvailable);
}
Intro::Intro(QWidget *parent) :
QDialog(parent),
ui(new Ui::Intro),
thread(0),
signalled(false)
{
ui->setupUi(this);
ui->sizeWarningLabel->setText(ui->sizeWarningLabel->text().arg(BLOCK_CHAIN_SIZE/GB_BYTES));
startThread();
}
Intro::~Intro()
{
delete ui;
/* Ensure thread is finished before it is deleted */
emit stopThread();
thread->wait();
}
QString Intro::getDataDirectory()
{
return ui->dataDirectory->text();
}
void Intro::setDataDirectory(const QString &dataDir)
{
ui->dataDirectory->setText(dataDir);
if(dataDir == getDefaultDataDirectory())
{
ui->dataDirDefault->setChecked(true);
ui->dataDirectory->setEnabled(false);
ui->ellipsisButton->setEnabled(false);
} else {
ui->dataDirCustom->setChecked(true);
ui->dataDirectory->setEnabled(true);
ui->ellipsisButton->setEnabled(true);
}
}
QString Intro::getDefaultDataDirectory()
{
return GUIUtil::boostPathToQString(GetDefaultDataDir());
}
void Intro::pickDataDirectory()
{
namespace fs = boost::filesystem;
QSettings settings;
/* If data directory provided on command line, no need to look at settings
or show a picking dialog */
if(!GetArg("-datadir", "").empty())
return;
/* 1) Default data directory for operating system */
QString dataDir = getDefaultDataDirectory();
/* 2) Allow QSettings to override default dir */
dataDir = settings.value("strDataDir", dataDir).toString();
if(!fs::exists(GUIUtil::qstringToBoostPath(dataDir)) || GetBoolArg("-choosedatadir", false))
{
/* If current default data directory does not exist, let the user choose one */
Intro intro;
intro.setDataDirectory(dataDir);
intro.setWindowIcon(QIcon(":icons/bitcoin"));
while(true)
{
if(!intro.exec())
{
/* Cancel clicked */
exit(0);
}
dataDir = intro.getDataDirectory();
try {
TryCreateDirectory(GUIUtil::qstringToBoostPath(dataDir));
break;
} catch(fs::filesystem_error &e) {
QMessageBox::critical(0, tr("Fastcoin Core"),
tr("Error: Specified data directory \"%1\" cannot be created.").arg(dataDir));
/* fall through, back to choosing screen */
}
}
settings.setValue("strDataDir", dataDir);
}
/* Only override -datadir if different from the default, to make it possible to
* override -datadir in the bitcoin.conf file in the default data directory
* (to be consistent with bitcoind behavior)
*/
if(dataDir != getDefaultDataDirectory())
SoftSetArg("-datadir", GUIUtil::qstringToBoostPath(dataDir).string()); // use OS locale for path setting
}
void Intro::setStatus(int status, const QString &message, quint64 bytesAvailable)
{
switch(status)
{
case FreespaceChecker::ST_OK:
ui->errorMessage->setText(message);
ui->errorMessage->setStyleSheet("");
break;
case FreespaceChecker::ST_ERROR:
ui->errorMessage->setText(tr("Error") + ": " + message);
ui->errorMessage->setStyleSheet("QLabel { color: #800000 }");
break;
}
/* Indicate number of bytes available */
if(status == FreespaceChecker::ST_ERROR)
{
ui->freeSpace->setText("");
} else {
QString freeString = tr("%n GB of free space available", "", bytesAvailable/GB_BYTES);
if(bytesAvailable < BLOCK_CHAIN_SIZE)
{
freeString += " " + tr("(of %n GB needed)", "", BLOCK_CHAIN_SIZE/GB_BYTES);
ui->freeSpace->setStyleSheet("QLabel { color: #800000 }");
} else {
ui->freeSpace->setStyleSheet("");
}
ui->freeSpace->setText(freeString + ".");
}
/* Don't allow confirm in ERROR state */
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(status != FreespaceChecker::ST_ERROR);
}
void Intro::on_dataDirectory_textChanged(const QString &dataDirStr)
{
/* Disable OK button until check result comes in */
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
checkPath(dataDirStr);
}
void Intro::on_ellipsisButton_clicked()
{
QString dir = QDir::toNativeSeparators(QFileDialog::getExistingDirectory(0, "Choose data directory", ui->dataDirectory->text()));
if(!dir.isEmpty())
ui->dataDirectory->setText(dir);
}
void Intro::on_dataDirDefault_clicked()
{
setDataDirectory(getDefaultDataDirectory());
}
void Intro::on_dataDirCustom_clicked()
{
ui->dataDirectory->setEnabled(true);
ui->ellipsisButton->setEnabled(true);
}
void Intro::startThread()
{
thread = new QThread(this);
FreespaceChecker *executor = new FreespaceChecker(this);
executor->moveToThread(thread);
connect(executor, SIGNAL(reply(int,QString,quint64)), this, SLOT(setStatus(int,QString,quint64)));
connect(this, SIGNAL(requestCheck()), executor, SLOT(check()));
/* make sure executor object is deleted in its own thread */
connect(this, SIGNAL(stopThread()), executor, SLOT(deleteLater()));
connect(this, SIGNAL(stopThread()), thread, SLOT(quit()));
thread->start();
}
void Intro::checkPath(const QString &dataDir)
{
mutex.lock();
pathToCheck = dataDir;
if(!signalled)
{
signalled = true;
emit requestCheck();
}
mutex.unlock();
}
QString Intro::getPathToCheck()
{
QString retval;
mutex.lock();
retval = pathToCheck;
signalled = false; /* new request can be queued now */
mutex.unlock();
return retval;
}
<commit_msg>Update intro.cpp<commit_after>// Copyright (c) 2011-2014 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "intro.h"
#include "ui_intro.h"
#include "guiutil.h"
#include "util.h"
#include <boost/filesystem.hpp>
#include <QFileDialog>
#include <QSettings>
#include <QMessageBox>
/* Minimum free space (in bytes) needed for data directory */
static const uint64_t GB_BYTES = 1000000000LL;
static const uint64_t BLOCK_CHAIN_SIZE = 20LL * GB_BYTES;
/* Check free space asynchronously to prevent hanging the UI thread.
Up to one request to check a path is in flight to this thread; when the check()
function runs, the current path is requested from the associated Intro object.
The reply is sent back through a signal.
This ensures that no queue of checking requests is built up while the user is
still entering the path, and that always the most recently entered path is checked as
soon as the thread becomes available.
*/
class FreespaceChecker : public QObject
{
Q_OBJECT
public:
FreespaceChecker(Intro *intro);
enum Status {
ST_OK,
ST_ERROR
};
public slots:
void check();
signals:
void reply(int status, const QString &message, quint64 available);
private:
Intro *intro;
};
#include "intro.moc"
FreespaceChecker::FreespaceChecker(Intro *intro)
{
this->intro = intro;
}
void FreespaceChecker::check()
{
namespace fs = boost::filesystem;
QString dataDirStr = intro->getPathToCheck();
fs::path dataDir = GUIUtil::qstringToBoostPath(dataDirStr);
uint64_t freeBytesAvailable = 0;
int replyStatus = ST_OK;
QString replyMessage = tr("A new data directory will be created.");
/* Find first parent that exists, so that fs::space does not fail */
fs::path parentDir = dataDir;
fs::path parentDirOld = fs::path();
while(parentDir.has_parent_path() && !fs::exists(parentDir))
{
parentDir = parentDir.parent_path();
/* Check if we make any progress, break if not to prevent an infinite loop here */
if (parentDirOld == parentDir)
break;
parentDirOld = parentDir;
}
try {
freeBytesAvailable = fs::space(parentDir).available;
if(fs::exists(dataDir))
{
if(fs::is_directory(dataDir))
{
QString separator = "<code>" + QDir::toNativeSeparators("/") + tr("name") + "</code>";
replyStatus = ST_OK;
replyMessage = tr("Directory already exists. Add %1 if you intend to create a new directory here.").arg(separator);
} else {
replyStatus = ST_ERROR;
replyMessage = tr("Path already exists, and is not a directory.");
}
}
} catch(fs::filesystem_error &e)
{
/* Parent directory does not exist or is not accessible */
replyStatus = ST_ERROR;
replyMessage = tr("Cannot create data directory here.");
}
emit reply(replyStatus, replyMessage, freeBytesAvailable);
}
Intro::Intro(QWidget *parent) :
QDialog(parent),
ui(new Ui::Intro),
thread(0),
signalled(false)
{
ui->setupUi(this);
ui->sizeWarningLabel->setText(ui->sizeWarningLabel->text().arg(BLOCK_CHAIN_SIZE/GB_BYTES));
startThread();
}
Intro::~Intro()
{
delete ui;
/* Ensure thread is finished before it is deleted */
emit stopThread();
thread->wait();
}
QString Intro::getDataDirectory()
{
return ui->dataDirectory->text();
}
void Intro::setDataDirectory(const QString &dataDir)
{
ui->dataDirectory->setText(dataDir);
if(dataDir == getDefaultDataDirectory())
{
ui->dataDirDefault->setChecked(true);
ui->dataDirectory->setEnabled(false);
ui->ellipsisButton->setEnabled(false);
} else {
ui->dataDirCustom->setChecked(true);
ui->dataDirectory->setEnabled(true);
ui->ellipsisButton->setEnabled(true);
}
}
QString Intro::getDefaultDataDirectory()
{
return GUIUtil::boostPathToQString(GetDefaultDataDir());
}
void Intro::pickDataDirectory()
{
namespace fs = boost::filesystem;
QSettings settings;
/* If data directory provided on command line, no need to look at settings
or show a picking dialog */
if(!GetArg("-datadir", "").empty())
return;
/* 1) Default data directory for operating system */
QString dataDir = getDefaultDataDirectory();
/* 2) Allow QSettings to override default dir */
dataDir = settings.value("strDataDir", dataDir).toString();
if(!fs::exists(GUIUtil::qstringToBoostPath(dataDir)) || GetBoolArg("-choosedatadir", false))
{
/* If current default data directory does not exist, let the user choose one */
Intro intro;
intro.setDataDirectory(dataDir);
intro.setWindowIcon(QIcon(":icons/bitcoin"));
while(true)
{
if(!intro.exec())
{
/* Cancel clicked */
exit(0);
}
dataDir = intro.getDataDirectory();
try {
TryCreateDirectory(GUIUtil::qstringToBoostPath(dataDir));
break;
} catch(fs::filesystem_error &e) {
QMessageBox::critical(0, tr("Fastcoin Core"),
tr("Error: Specified data directory \"%1\" cannot be created.").arg(dataDir));
/* fall through, back to choosing screen */
}
}
settings.setValue("strDataDir", dataDir);
}
/* Only override -datadir if different from the default, to make it possible to
* override -datadir in the bitcoin.conf file in the default data directory
* (to be consistent with bitcoind behavior)
*/
if(dataDir != getDefaultDataDirectory())
SoftSetArg("-datadir", GUIUtil::qstringToBoostPath(dataDir).string()); // use OS locale for path setting
}
void Intro::setStatus(int status, const QString &message, quint64 bytesAvailable)
{
switch(status)
{
case FreespaceChecker::ST_OK:
ui->errorMessage->setText(message);
ui->errorMessage->setStyleSheet("");
break;
case FreespaceChecker::ST_ERROR:
ui->errorMessage->setText(tr("Error") + ": " + message);
ui->errorMessage->setStyleSheet("QLabel { color: #800000 }");
break;
}
/* Indicate number of bytes available */
if(status == FreespaceChecker::ST_ERROR)
{
ui->freeSpace->setText("");
} else {
QString freeString = tr("%n GB of free space available", "", bytesAvailable/GB_BYTES);
if(bytesAvailable < BLOCK_CHAIN_SIZE)
{
freeString += " " + tr("(of %n GB needed)", "", BLOCK_CHAIN_SIZE/GB_BYTES);
ui->freeSpace->setStyleSheet("QLabel { color: #800000 }");
} else {
ui->freeSpace->setStyleSheet("");
}
ui->freeSpace->setText(freeString + ".");
}
/* Don't allow confirm in ERROR state */
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(status != FreespaceChecker::ST_ERROR);
}
void Intro::on_dataDirectory_textChanged(const QString &dataDirStr)
{
/* Disable OK button until check result comes in */
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
checkPath(dataDirStr);
}
void Intro::on_ellipsisButton_clicked()
{
QString dir = QDir::toNativeSeparators(QFileDialog::getExistingDirectory(0, "Choose data directory", ui->dataDirectory->text()));
if(!dir.isEmpty())
ui->dataDirectory->setText(dir);
}
void Intro::on_dataDirDefault_clicked()
{
setDataDirectory(getDefaultDataDirectory());
}
void Intro::on_dataDirCustom_clicked()
{
ui->dataDirectory->setEnabled(true);
ui->ellipsisButton->setEnabled(true);
}
void Intro::startThread()
{
thread = new QThread(this);
FreespaceChecker *executor = new FreespaceChecker(this);
executor->moveToThread(thread);
connect(executor, SIGNAL(reply(int,QString,quint64)), this, SLOT(setStatus(int,QString,quint64)));
connect(this, SIGNAL(requestCheck()), executor, SLOT(check()));
/* make sure executor object is deleted in its own thread */
connect(this, SIGNAL(stopThread()), executor, SLOT(deleteLater()));
connect(this, SIGNAL(stopThread()), thread, SLOT(quit()));
thread->start();
}
void Intro::checkPath(const QString &dataDir)
{
mutex.lock();
pathToCheck = dataDir;
if(!signalled)
{
signalled = true;
emit requestCheck();
}
mutex.unlock();
}
QString Intro::getPathToCheck()
{
QString retval;
mutex.lock();
retval = pathToCheck;
signalled = false; /* new request can be queued now */
mutex.unlock();
return retval;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: documentdefinition.hxx,v $
*
* $Revision: 1.26 $
*
* last change: $Author: rt $ $Date: 2008-01-30 08:34:51 $
*
* 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 _DBA_COREDATAACCESS_DOCUMENTDEFINITION_HXX_
#define _DBA_COREDATAACCESS_DOCUMENTDEFINITION_HXX_
#ifndef _CPPUHELPER_PROPSHLP_HXX
#include <cppuhelper/propshlp.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef DBA_CONTENTHELPER_HXX
#include "ContentHelper.hxx"
#endif
#ifndef COMPHELPER_PROPERTYSTATECONTAINER_HXX
#include <comphelper/propertystatecontainer.hxx>
#endif
#ifndef _COMPHELPER_PROPERTY_ARRAY_HELPER_HXX_
#include <comphelper/proparrhlp.hxx>
#endif
#ifndef _DBASHARED_APITOOLS_HXX_
#include "apitools.hxx"
#endif
#ifndef _COMPHELPER_UNO3_HXX_
#include <comphelper/uno3.hxx>
#endif
#ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_
#include <com/sun/star/sdbc/XConnection.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XCOMPONENTLOADER_HPP_
#include <com/sun/star/frame/XComponentLoader.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XCONTROLLER_HPP_
#include <com/sun/star/frame/XController.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_XSTATECHANGELISTENER_HPP_
#include <com/sun/star/embed/XStateChangeListener.hpp>
#endif
//........................................................................
namespace dbaccess
{
//........................................................................
class OInterceptor;
class OEmbeddedClientHelper;
//==========================================================================
//= ODocumentDefinition - a database "document" which is simply a link to a real
//= document
//==========================================================================
typedef ::cppu::ImplHelper1< ::com::sun::star::embed::XComponentSupplier
> ODocumentDefinition_Base;
class ODocumentDefinition
:public OContentHelper
,public ::comphelper::OPropertyStateContainer
,public ::comphelper::OPropertyArrayUsageHelper< ODocumentDefinition >
,public ODocumentDefinition_Base
{
::com::sun::star::uno::Reference< ::com::sun::star::embed::XEmbeddedObject> m_xEmbeddedObject;
::com::sun::star::uno::Reference< ::com::sun::star::embed::XStateChangeListener > m_xListener;
::com::sun::star::uno::Reference< ::com::sun::star::frame::XFramesSupplier > m_xDesktop;
::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection > m_xLastKnownConnection;
OInterceptor* m_pInterceptor;
sal_Bool m_bForm; // <TRUE/> if it is a form
sal_Bool m_bOpenInDesign;
sal_Bool m_bInExecute;
OEmbeddedClientHelper* m_pClientHelper;
protected:
virtual ~ODocumentDefinition();
public:
ODocumentDefinition(
const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxContainer
,const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >&
,const TContentPtr& _pImpl
,sal_Bool _bForm
,const ::com::sun::star::uno::Sequence< sal_Int8 >& _aClassID = ::com::sun::star::uno::Sequence< sal_Int8 >()
,const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection>& _xConnection = ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection>()
);
// com::sun::star::lang::XTypeProvider
DECLARE_TYPEPROVIDER( );
// ::com::sun::star::uno::XInterface
DECLARE_XINTERFACE( )
// ::com::sun::star::lang::XServiceInfo
DECLARE_SERVICE_INFO_STATIC();
// ::com::sun::star::beans::XPropertySet
virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo( ) throw(::com::sun::star::uno::RuntimeException);
// XComponentSupplier
virtual ::com::sun::star::uno::Reference< ::com::sun::star::util::XCloseable > SAL_CALL getComponent( ) throw (::com::sun::star::uno::RuntimeException);
// OPropertySetHelper
virtual ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper();
// XCommandProcessor
virtual ::com::sun::star::uno::Any SAL_CALL execute( const ::com::sun::star::ucb::Command& aCommand, sal_Int32 CommandId, const ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XCommandEnvironment >& Environment ) throw (::com::sun::star::uno::Exception, ::com::sun::star::ucb::CommandAbortedException, ::com::sun::star::uno::RuntimeException) ;
// XRename
virtual void SAL_CALL rename( const ::rtl::OUString& newName ) throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::container::ElementExistException, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage> getStorage() const;
sal_Bool save(sal_Bool _bApprove);
sal_Bool saveAs();
void closeObject();
sal_Bool isModified();
void fillReportData();
inline sal_Bool isNewReport() const { return !m_bForm && !m_pImpl->m_aProps.bAsTemplate; }
/** prepares closing the document component
The method suspends the controller associated with the document, and saves the document
if necessary.
@return
<TRUE/> if and only if the document component can be closed
*/
bool prepareClose();
static ::com::sun::star::uno::Sequence< sal_Int8 > getDefaultDocumentTypeClassId();
/** does necessary initializations after our embedded object has been switched to ACTIVE
@param _bOpenedInDesignMode
determines whether the embedded object has been opened for designing it or for data display
*/
void impl_onActivateEmbeddedObject();
/** initializes a newly created view/controller which is displaying our embedded object
Has only to be called if the respective embedded object has been loaded for design (and
not for data entry)
@param _rxController
the controller which belongs to the XModel of our (active) embedded object
*/
void impl_initObjectEditView( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XController >& _rxController );
/** removes the given frame from the desktop's frame collection
@raises ::com::sun::star::uno::RuntimeException
*/
void impl_removeFrameFromDesktop_throw( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& _rxFrame );
static ::rtl::OUString GetDocumentServiceFromMediaType( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage
,const ::rtl::OUString& sEntName
,const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _xORB
,::com::sun::star::uno::Sequence< sal_Int8 >& _rClassId
);
protected:
// OPropertyArrayUsageHelper
virtual ::cppu::IPropertyArrayHelper* createArrayHelper( ) const;
virtual void getPropertyDefaultByHandle( sal_Int32 _nHandle, ::com::sun::star::uno::Any& _rDefault ) const;
// helper
virtual void SAL_CALL disposing();
private:
/** fills the load arguments
*/
::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >
fillLoadArgs(
const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection>& _xConnection,
const bool _bSuppressMacros,
const bool _bReadOnly,
const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _rAdditionalArgs,
::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _out_rEmbeddedObjectDescriptor
);
/** loads the EmbeddedObject if not already loaded
@param _aClassID
If set, it will be used to create the embedded object.
*/
void loadEmbeddedObject(
const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection>& _xConnection,
const ::com::sun::star::uno::Sequence< sal_Int8 >& _aClassID,
const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _rAdditionalArgs,
const bool _bSuppressMacros,
const bool _bReadOnly
);
/** loads the embedded object, if not already loaded. No new object can be created with this method.
*/
void loadEmbeddedObject()
{
loadEmbeddedObject(
NULL,
::com::sun::star::uno::Sequence< sal_Int8 >(),
::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >(),
false,
false
);
}
/** loads the embedded object for preview. Macros will be suppressed, and the document will
be read-only.
*/
void loadEmbeddedObjectForPreview()
{
loadEmbeddedObject(
NULL,
::com::sun::star::uno::Sequence< sal_Int8 >(),
::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >(),
true,
true
);
}
/** searches for read-only flag in the args of the model and sets it to the given value,
if the value was not found, it will be appended.
@param _bReadOnly
If <TRUE/> the document will be switched to readonly mode
*/
void updateDocumentTitle();
void registerProperties();
//-------------------------------------------------------------------------
//- commands
//-------------------------------------------------------------------------
void onCommandGetDocumentInfo( ::com::sun::star::uno::Any& _rInfo );
void onCommandInsert( const ::rtl::OUString& _sURL, const ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XCommandEnvironment >& Environment ) throw( ::com::sun::star::uno::Exception );
void onCommandPreview( ::com::sun::star::uno::Any& _rImage );
void onCommandOpenSomething( const ::com::sun::star::uno::Any& _rArgument, const bool _bActivate,
const ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XCommandEnvironment >& _rxEnvironment, ::com::sun::star::uno::Any& _out_rComponent );
};
//........................................................................
} // namespace dbaccess
//........................................................................
#endif // _DBA_COREDATAACCESS_DOCUMENTDEFINITION_HXX_
<commit_msg>INTEGRATION: CWS custommeta (1.24.26); FILE MERGED 2008/02/01 10:33:44 mst 1.24.26.2: RESYNC: (1.24-1.26); FILE MERGED 2008/01/29 13:14:59 mst 1.24.26.1: - dbaccess/source/ui/app/AppDetailPageHelper.cxx: + adapt to ODocumentInfoPreview interface change + use XDocumentProperties instead of XDocumentInfo + incidentally, fixes bug: document information was not displayed at all - dbaccess/source/core/dataaccess/documentdefinition.{hxx,cxx}: + renamed ODocumentDefinition::onCommandGetDocumentInfo to onCommandGetDocumentProperties<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: documentdefinition.hxx,v $
*
* $Revision: 1.27 $
*
* last change: $Author: obo $ $Date: 2008-02-26 14:38:02 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _DBA_COREDATAACCESS_DOCUMENTDEFINITION_HXX_
#define _DBA_COREDATAACCESS_DOCUMENTDEFINITION_HXX_
#ifndef _CPPUHELPER_PROPSHLP_HXX
#include <cppuhelper/propshlp.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef DBA_CONTENTHELPER_HXX
#include "ContentHelper.hxx"
#endif
#ifndef COMPHELPER_PROPERTYSTATECONTAINER_HXX
#include <comphelper/propertystatecontainer.hxx>
#endif
#ifndef _COMPHELPER_PROPERTY_ARRAY_HELPER_HXX_
#include <comphelper/proparrhlp.hxx>
#endif
#ifndef _DBASHARED_APITOOLS_HXX_
#include "apitools.hxx"
#endif
#ifndef _COMPHELPER_UNO3_HXX_
#include <comphelper/uno3.hxx>
#endif
#ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_
#include <com/sun/star/sdbc/XConnection.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XCOMPONENTLOADER_HPP_
#include <com/sun/star/frame/XComponentLoader.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XCONTROLLER_HPP_
#include <com/sun/star/frame/XController.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_XSTATECHANGELISTENER_HPP_
#include <com/sun/star/embed/XStateChangeListener.hpp>
#endif
//........................................................................
namespace dbaccess
{
//........................................................................
class OInterceptor;
class OEmbeddedClientHelper;
//==========================================================================
//= ODocumentDefinition - a database "document" which is simply a link to a real
//= document
//==========================================================================
typedef ::cppu::ImplHelper1< ::com::sun::star::embed::XComponentSupplier
> ODocumentDefinition_Base;
class ODocumentDefinition
:public OContentHelper
,public ::comphelper::OPropertyStateContainer
,public ::comphelper::OPropertyArrayUsageHelper< ODocumentDefinition >
,public ODocumentDefinition_Base
{
::com::sun::star::uno::Reference< ::com::sun::star::embed::XEmbeddedObject> m_xEmbeddedObject;
::com::sun::star::uno::Reference< ::com::sun::star::embed::XStateChangeListener > m_xListener;
::com::sun::star::uno::Reference< ::com::sun::star::frame::XFramesSupplier > m_xDesktop;
::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection > m_xLastKnownConnection;
OInterceptor* m_pInterceptor;
sal_Bool m_bForm; // <TRUE/> if it is a form
sal_Bool m_bOpenInDesign;
sal_Bool m_bInExecute;
OEmbeddedClientHelper* m_pClientHelper;
protected:
virtual ~ODocumentDefinition();
public:
ODocumentDefinition(
const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxContainer
,const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >&
,const TContentPtr& _pImpl
,sal_Bool _bForm
,const ::com::sun::star::uno::Sequence< sal_Int8 >& _aClassID = ::com::sun::star::uno::Sequence< sal_Int8 >()
,const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection>& _xConnection = ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection>()
);
// com::sun::star::lang::XTypeProvider
DECLARE_TYPEPROVIDER( );
// ::com::sun::star::uno::XInterface
DECLARE_XINTERFACE( )
// ::com::sun::star::lang::XServiceInfo
DECLARE_SERVICE_INFO_STATIC();
// ::com::sun::star::beans::XPropertySet
virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo( ) throw(::com::sun::star::uno::RuntimeException);
// XComponentSupplier
virtual ::com::sun::star::uno::Reference< ::com::sun::star::util::XCloseable > SAL_CALL getComponent( ) throw (::com::sun::star::uno::RuntimeException);
// OPropertySetHelper
virtual ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper();
// XCommandProcessor
virtual ::com::sun::star::uno::Any SAL_CALL execute( const ::com::sun::star::ucb::Command& aCommand, sal_Int32 CommandId, const ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XCommandEnvironment >& Environment ) throw (::com::sun::star::uno::Exception, ::com::sun::star::ucb::CommandAbortedException, ::com::sun::star::uno::RuntimeException) ;
// XRename
virtual void SAL_CALL rename( const ::rtl::OUString& newName ) throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::container::ElementExistException, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage> getStorage() const;
sal_Bool save(sal_Bool _bApprove);
sal_Bool saveAs();
void closeObject();
sal_Bool isModified();
void fillReportData();
inline sal_Bool isNewReport() const { return !m_bForm && !m_pImpl->m_aProps.bAsTemplate; }
/** prepares closing the document component
The method suspends the controller associated with the document, and saves the document
if necessary.
@return
<TRUE/> if and only if the document component can be closed
*/
bool prepareClose();
static ::com::sun::star::uno::Sequence< sal_Int8 > getDefaultDocumentTypeClassId();
/** does necessary initializations after our embedded object has been switched to ACTIVE
@param _bOpenedInDesignMode
determines whether the embedded object has been opened for designing it or for data display
*/
void impl_onActivateEmbeddedObject();
/** initializes a newly created view/controller which is displaying our embedded object
Has only to be called if the respective embedded object has been loaded for design (and
not for data entry)
@param _rxController
the controller which belongs to the XModel of our (active) embedded object
*/
void impl_initObjectEditView( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XController >& _rxController );
/** removes the given frame from the desktop's frame collection
@raises ::com::sun::star::uno::RuntimeException
*/
void impl_removeFrameFromDesktop_throw( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& _rxFrame );
static ::rtl::OUString GetDocumentServiceFromMediaType( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage
,const ::rtl::OUString& sEntName
,const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _xORB
,::com::sun::star::uno::Sequence< sal_Int8 >& _rClassId
);
protected:
// OPropertyArrayUsageHelper
virtual ::cppu::IPropertyArrayHelper* createArrayHelper( ) const;
virtual void getPropertyDefaultByHandle( sal_Int32 _nHandle, ::com::sun::star::uno::Any& _rDefault ) const;
// helper
virtual void SAL_CALL disposing();
private:
/** fills the load arguments
*/
::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >
fillLoadArgs(
const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection>& _xConnection,
const bool _bSuppressMacros,
const bool _bReadOnly,
const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _rAdditionalArgs,
::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _out_rEmbeddedObjectDescriptor
);
/** loads the EmbeddedObject if not already loaded
@param _aClassID
If set, it will be used to create the embedded object.
*/
void loadEmbeddedObject(
const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection>& _xConnection,
const ::com::sun::star::uno::Sequence< sal_Int8 >& _aClassID,
const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _rAdditionalArgs,
const bool _bSuppressMacros,
const bool _bReadOnly
);
/** loads the embedded object, if not already loaded. No new object can be created with this method.
*/
void loadEmbeddedObject()
{
loadEmbeddedObject(
NULL,
::com::sun::star::uno::Sequence< sal_Int8 >(),
::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >(),
false,
false
);
}
/** loads the embedded object for preview. Macros will be suppressed, and the document will
be read-only.
*/
void loadEmbeddedObjectForPreview()
{
loadEmbeddedObject(
NULL,
::com::sun::star::uno::Sequence< sal_Int8 >(),
::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >(),
true,
true
);
}
/** searches for read-only flag in the args of the model and sets it to the given value,
if the value was not found, it will be appended.
@param _bReadOnly
If <TRUE/> the document will be switched to readonly mode
*/
void updateDocumentTitle();
void registerProperties();
//-------------------------------------------------------------------------
//- commands
//-------------------------------------------------------------------------
void onCommandGetDocumentProperties( ::com::sun::star::uno::Any& _rProps );
void onCommandInsert( const ::rtl::OUString& _sURL, const ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XCommandEnvironment >& Environment ) throw( ::com::sun::star::uno::Exception );
void onCommandPreview( ::com::sun::star::uno::Any& _rImage );
void onCommandOpenSomething( const ::com::sun::star::uno::Any& _rArgument, const bool _bActivate,
const ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XCommandEnvironment >& _rxEnvironment, ::com::sun::star::uno::Any& _out_rComponent );
};
//........................................................................
} // namespace dbaccess
//........................................................................
#endif // _DBA_COREDATAACCESS_DOCUMENTDEFINITION_HXX_
<|endoftext|> |
<commit_before>/*!
* Copyright (c) 2017 by Contributors
* \file opencl_module.cc
*/
#include <dmlc/memory_io.h>
#include <tvm/runtime/registry.h>
#include <vector>
#include <string>
#include <unordered_map>
#include "./opencl_common.h"
#include "./opencl_module.h"
namespace tvm {
namespace runtime {
class OpenCLWrappedFunc {
public:
// initialize the OpenCL function.
void Init(OpenCLModuleNode* m,
std::shared_ptr<ModuleNode> sptr,
OpenCLModuleNode::KTRefEntry entry,
std::string func_name,
std::vector<size_t> arg_size,
const std::vector<std::string>& thread_axis_tags) {
w_ = m->GetGlobalWorkspace().get();
m_ = m;
sptr_ = sptr;
entry_ = entry;
func_name_ = func_name;
arg_size_ = arg_size;
thread_axis_cfg_.Init(arg_size.size(), thread_axis_tags);
}
// invoke the function with void arguments
void operator()(TVMArgs args,
TVMRetValue* rv,
void** void_args) const {
cl::OpenCLThreadEntry* t = w_->GetThreadEntry();
// get the kernel from thread local kernel table.
if (entry_.kernel_id >= t->kernel_table.size()) {
t->kernel_table.resize(entry_.kernel_id + 1);
}
const auto& e = t->kernel_table[entry_.kernel_id];
cl_kernel kernel = e.kernel;
if (kernel == nullptr || e.version != entry_.version) {
kernel = m_->InstallKernel(w_, t, func_name_, entry_);
}
// setup arguments.
for (cl_uint i = 0; i < arg_size_.size(); ++i) {
OPENCL_CALL(clSetKernelArg(kernel, i, arg_size_[i], void_args[i]));
}
cl_command_queue queue = w_->GetQueue(t->context);
ThreadWorkLoad wl = thread_axis_cfg_.Extract(args);
cl_uint work_dim = static_cast<cl_uint>(thread_axis_cfg_.work_dim());
for (cl_uint i = 0; i < work_dim; ++i) {
wl.work_size[i] *= wl.work_size[i + 3];
}
// launch kernel
OPENCL_CALL(clEnqueueNDRangeKernel(
queue, kernel, work_dim, nullptr,
wl.work_size,
wl.work_size + 3,
0, nullptr, nullptr));
}
private:
// global workspace.
cl::OpenCLWorkspace* w_;
// The module
OpenCLModuleNode* m_;
// resource handle
std::shared_ptr<ModuleNode> sptr_;
// global kernel id in the kernel table.
OpenCLModuleNode::KTRefEntry entry_;
// The name of the function.
std::string func_name_;
// convert code for void argument
std::vector<size_t> arg_size_;
// thread axis config
ThreadAxisConfig thread_axis_cfg_;
};
OpenCLModuleNode::~OpenCLModuleNode() {
{
// free the kernel ids in global table.
std::lock_guard<std::mutex> lock(workspace_->mu);
for (auto& kv : kid_map_) {
workspace_->free_kernel_ids.push_back(kv.second.kernel_id);
}
}
// free the kernels
for (cl_kernel k : kernels_) {
OPENCL_CALL(clReleaseKernel(k));
}
if (program_) {
OPENCL_CALL(clReleaseProgram(program_));
}
}
const std::shared_ptr<cl::OpenCLWorkspace>& OpenCLModuleNode::GetGlobalWorkspace() {
return cl::OpenCLWorkspace::Global();
}
const char* OpenCLModuleNode::type_key() const {
return "opencl";
}
PackedFunc OpenCLModuleNode::GetFunction(
const std::string& name,
const std::shared_ptr<ModuleNode>& sptr_to_self) {
CHECK_EQ(sptr_to_self.get(), this);
CHECK_NE(name, symbol::tvm_module_main)
<< "Device function do not have main";
auto it = fmap_.find(name);
if (it == fmap_.end()) return PackedFunc();
const FunctionInfo& info = it->second;
OpenCLWrappedFunc f;
std::vector<size_t> arg_size(info.arg_types.size());
for (size_t i = 0; i < info.arg_types.size(); ++i) {
TVMType t = info.arg_types[i];
CHECK_EQ(t.lanes, 1U);
if (t.code == kHandle) {
// specially store pointer type size in OpenCL driver
arg_size[i] = sizeof(void*);
} else {
uint32_t bits = t.bits;
CHECK_EQ(bits % 8, 0U);
arg_size[i] = bits / 8;
}
}
// initialize the wrapped func.
f.Init(this, sptr_to_self, kid_map_.at(name),
name, arg_size, info.thread_axis_tags);
return PackFuncVoidAddr(f, info.arg_types);
}
void OpenCLModuleNode::SaveToFile(const std::string& file_name,
const std::string& format) {
std::string fmt = GetFileFormat(file_name, format);
CHECK_EQ(fmt, fmt_)
<< "Can only save to format=" << fmt_;
std::string meta_file = GetMetaFilePath(file_name);
SaveMetaDataToFile(meta_file, fmap_);
SaveBinaryToFile(file_name, data_);
}
void OpenCLModuleNode::SaveToBinary(dmlc::Stream* stream) {
stream->Write(fmt_);
stream->Write(fmap_);
stream->Write(data_);
}
std::string OpenCLModuleNode::GetSource(const std::string& format) {
if (format == fmt_) return data_;
if (fmt_ == "cl") {
return data_;
} else {
return source_;
}
}
void OpenCLModuleNode::Init() {
workspace_ = GetGlobalWorkspace();
workspace_->Init();
CHECK(workspace_->context != nullptr) << "No OpenCL device";
if (fmt_ == "cl") {
const char* s = data_.c_str();
size_t len = data_.length();
cl_int err;
program_ = clCreateProgramWithSource(
workspace_->context, 1, &s, &len, &err);
OPENCL_CHECK_ERROR(err);
} else if (fmt_ == "xclbin" || fmt_ == "awsxclbin") {
const unsigned char* s = (const unsigned char *)data_.c_str();
size_t len = data_.length();
cl_int err;
program_ = clCreateProgramWithBinary(
workspace_->context, 1, &(workspace_->devices[0]), &len, &s, NULL, &err);
if (err != CL_SUCCESS) {
LOG(ERROR) << "OpenCL Error: " << cl::CLGetErrorString(err);
}
} else {
LOG(FATAL) << "Unknown OpenCL format " << fmt_;
}
device_built_flag_.resize(workspace_->devices.size(), false);
// initialize the kernel id, need to lock global table.
std::lock_guard<std::mutex> lock(workspace_->mu);
for (const auto& kv : fmap_) {
const std::string& key = kv.first;
KTRefEntry e;
if (workspace_->free_kernel_ids.size() != 0) {
e.kernel_id = workspace_->free_kernel_ids.back();
workspace_->free_kernel_ids.pop_back();
} else {
e.kernel_id = workspace_->num_registered_kernels++;
}
e.version = workspace_->timestamp++;
kid_map_[key] = e;
}
}
cl_kernel OpenCLModuleNode::InstallKernel(cl::OpenCLWorkspace* w,
cl::OpenCLThreadEntry* t,
const std::string& func_name,
const KTRefEntry& e) {
std::lock_guard<std::mutex> lock(build_lock_);
int device_id = t->context.device_id;
if (!device_built_flag_[device_id]) {
// build program
cl_int err;
cl_device_id dev = w->devices[device_id];
err = clBuildProgram(program_, 1, &dev, nullptr, nullptr, nullptr);
if (err != CL_SUCCESS) {
size_t len;
std::string log;
clGetProgramBuildInfo(
program_, dev, CL_PROGRAM_BUILD_LOG, 0, nullptr, &len);
log.resize(len);
clGetProgramBuildInfo(
program_, dev, CL_PROGRAM_BUILD_LOG, len, &log[0], nullptr);
LOG(FATAL) << "OpenCL build error for device=" << dev << log;
}
device_built_flag_[device_id] = true;
}
// build kernel
cl_int err;
cl_kernel kernel = clCreateKernel(program_, func_name.c_str(), &err);
OPENCL_CHECK_ERROR(err);
t->kernel_table[e.kernel_id].kernel = kernel;
t->kernel_table[e.kernel_id].version = e.version;
kernels_.push_back(kernel);
return kernel;
}
Module OpenCLModuleCreate(
std::string data,
std::string fmt,
std::unordered_map<std::string, FunctionInfo> fmap,
std::string source) {
std::shared_ptr<OpenCLModuleNode> n =
std::make_shared<OpenCLModuleNode>(data, fmt, fmap, source);
n->Init();
return Module(n);
}
// Load module from module.
Module OpenCLModuleLoadFile(const std::string& file_name,
const std::string& format) {
std::string data;
std::unordered_map<std::string, FunctionInfo> fmap;
std::string fmt = GetFileFormat(file_name, format);
std::string meta_file = GetMetaFilePath(file_name);
LoadBinaryFromFile(file_name, &data);
LoadMetaDataFromFile(meta_file, &fmap);
return OpenCLModuleCreate(data, fmt, fmap, std::string());
}
Module OpenCLModuleLoadBinary(void* strm) {
dmlc::Stream* stream = static_cast<dmlc::Stream*>(strm);
std::string data;
std::unordered_map<std::string, FunctionInfo> fmap;
std::string fmt;
stream->Read(&fmt);
stream->Read(&fmap);
stream->Read(&data);
return OpenCLModuleCreate(data, fmt, fmap, std::string());
}
TVM_REGISTER_GLOBAL("module.loadfile_cl")
.set_body([](TVMArgs args, TVMRetValue* rv) {
*rv = OpenCLModuleLoadFile(args[0], args[1]);
});
TVM_REGISTER_GLOBAL("module.loadfile_clbin")
.set_body([](TVMArgs args, TVMRetValue* rv) {
*rv = OpenCLModuleLoadFile(args[0], args[1]);
});
TVM_REGISTER_GLOBAL("module.loadbinary_opencl")
.set_body([](TVMArgs args, TVMRetValue* rv) {
*rv = OpenCLModuleLoadBinary(args[0]);
});
} // namespace runtime
} // namespace tvm
<commit_msg>[RUNTIME][OPENCL] Create program lazily when the program is built (#1408)<commit_after>/*!
* Copyright (c) 2017 by Contributors
* \file opencl_module.cc
*/
#include <dmlc/memory_io.h>
#include <tvm/runtime/registry.h>
#include <vector>
#include <string>
#include <unordered_map>
#include "./opencl_common.h"
#include "./opencl_module.h"
namespace tvm {
namespace runtime {
class OpenCLWrappedFunc {
public:
// initialize the OpenCL function.
void Init(OpenCLModuleNode* m,
std::shared_ptr<ModuleNode> sptr,
OpenCLModuleNode::KTRefEntry entry,
std::string func_name,
std::vector<size_t> arg_size,
const std::vector<std::string>& thread_axis_tags) {
w_ = m->GetGlobalWorkspace().get();
m_ = m;
sptr_ = sptr;
entry_ = entry;
func_name_ = func_name;
arg_size_ = arg_size;
thread_axis_cfg_.Init(arg_size.size(), thread_axis_tags);
}
// invoke the function with void arguments
void operator()(TVMArgs args,
TVMRetValue* rv,
void** void_args) const {
cl::OpenCLThreadEntry* t = w_->GetThreadEntry();
// get the kernel from thread local kernel table.
if (entry_.kernel_id >= t->kernel_table.size()) {
t->kernel_table.resize(entry_.kernel_id + 1);
}
const auto& e = t->kernel_table[entry_.kernel_id];
cl_kernel kernel = e.kernel;
if (kernel == nullptr || e.version != entry_.version) {
kernel = m_->InstallKernel(w_, t, func_name_, entry_);
}
// setup arguments.
for (cl_uint i = 0; i < arg_size_.size(); ++i) {
OPENCL_CALL(clSetKernelArg(kernel, i, arg_size_[i], void_args[i]));
}
cl_command_queue queue = w_->GetQueue(t->context);
ThreadWorkLoad wl = thread_axis_cfg_.Extract(args);
cl_uint work_dim = static_cast<cl_uint>(thread_axis_cfg_.work_dim());
for (cl_uint i = 0; i < work_dim; ++i) {
wl.work_size[i] *= wl.work_size[i + 3];
}
// launch kernel
OPENCL_CALL(clEnqueueNDRangeKernel(
queue, kernel, work_dim, nullptr,
wl.work_size,
wl.work_size + 3,
0, nullptr, nullptr));
}
private:
// global workspace.
cl::OpenCLWorkspace* w_;
// The module
OpenCLModuleNode* m_;
// resource handle
std::shared_ptr<ModuleNode> sptr_;
// global kernel id in the kernel table.
OpenCLModuleNode::KTRefEntry entry_;
// The name of the function.
std::string func_name_;
// convert code for void argument
std::vector<size_t> arg_size_;
// thread axis config
ThreadAxisConfig thread_axis_cfg_;
};
OpenCLModuleNode::~OpenCLModuleNode() {
{
// free the kernel ids in global table.
std::lock_guard<std::mutex> lock(workspace_->mu);
for (auto& kv : kid_map_) {
workspace_->free_kernel_ids.push_back(kv.second.kernel_id);
}
}
// free the kernels
for (cl_kernel k : kernels_) {
OPENCL_CALL(clReleaseKernel(k));
}
if (program_) {
OPENCL_CALL(clReleaseProgram(program_));
}
}
const std::shared_ptr<cl::OpenCLWorkspace>& OpenCLModuleNode::GetGlobalWorkspace() {
return cl::OpenCLWorkspace::Global();
}
const char* OpenCLModuleNode::type_key() const {
return "opencl";
}
PackedFunc OpenCLModuleNode::GetFunction(
const std::string& name,
const std::shared_ptr<ModuleNode>& sptr_to_self) {
CHECK_EQ(sptr_to_self.get(), this);
CHECK_NE(name, symbol::tvm_module_main)
<< "Device function do not have main";
auto it = fmap_.find(name);
if (it == fmap_.end()) return PackedFunc();
const FunctionInfo& info = it->second;
OpenCLWrappedFunc f;
std::vector<size_t> arg_size(info.arg_types.size());
for (size_t i = 0; i < info.arg_types.size(); ++i) {
TVMType t = info.arg_types[i];
CHECK_EQ(t.lanes, 1U);
if (t.code == kHandle) {
// specially store pointer type size in OpenCL driver
arg_size[i] = sizeof(void*);
} else {
uint32_t bits = t.bits;
CHECK_EQ(bits % 8, 0U);
arg_size[i] = bits / 8;
}
}
// initialize the wrapped func.
f.Init(this, sptr_to_self, kid_map_.at(name),
name, arg_size, info.thread_axis_tags);
return PackFuncVoidAddr(f, info.arg_types);
}
void OpenCLModuleNode::SaveToFile(const std::string& file_name,
const std::string& format) {
std::string fmt = GetFileFormat(file_name, format);
CHECK_EQ(fmt, fmt_)
<< "Can only save to format=" << fmt_;
std::string meta_file = GetMetaFilePath(file_name);
SaveMetaDataToFile(meta_file, fmap_);
SaveBinaryToFile(file_name, data_);
}
void OpenCLModuleNode::SaveToBinary(dmlc::Stream* stream) {
stream->Write(fmt_);
stream->Write(fmap_);
stream->Write(data_);
}
std::string OpenCLModuleNode::GetSource(const std::string& format) {
if (format == fmt_) return data_;
if (fmt_ == "cl") {
return data_;
} else {
return source_;
}
}
void OpenCLModuleNode::Init() {
workspace_ = GetGlobalWorkspace();
workspace_->Init();
CHECK(workspace_->context != nullptr) << "No OpenCL device";
device_built_flag_.resize(workspace_->devices.size(), false);
// initialize the kernel id, need to lock global table.
std::lock_guard<std::mutex> lock(workspace_->mu);
for (const auto& kv : fmap_) {
const std::string& key = kv.first;
KTRefEntry e;
if (workspace_->free_kernel_ids.size() != 0) {
e.kernel_id = workspace_->free_kernel_ids.back();
workspace_->free_kernel_ids.pop_back();
} else {
e.kernel_id = workspace_->num_registered_kernels++;
}
e.version = workspace_->timestamp++;
kid_map_[key] = e;
}
}
cl_kernel OpenCLModuleNode::InstallKernel(cl::OpenCLWorkspace* w,
cl::OpenCLThreadEntry* t,
const std::string& func_name,
const KTRefEntry& e) {
std::lock_guard<std::mutex> lock(build_lock_);
int device_id = t->context.device_id;
if (!device_built_flag_[device_id]) {
// create program
if (fmt_ == "cl") {
if (program_ == nullptr) {
const char* s = data_.c_str();
size_t len = data_.length();
cl_int err;
program_ = clCreateProgramWithSource(w->context, 1, &s, &len, &err);
OPENCL_CHECK_ERROR(err);
}
} else if (fmt_ == "xclbin" || fmt_ == "awsxclbin") {
const unsigned char* s = (const unsigned char *)data_.c_str();
size_t len = data_.length();
cl_int err;
cl_device_id dev = w->devices[device_id];
program_ = clCreateProgramWithBinary(w->context, 1, &dev, &len, &s, NULL, &err);
OPENCL_CHECK_ERROR(err);
} else {
LOG(FATAL) << "Unknown OpenCL format " << fmt_;
}
// build program
cl_int err;
cl_device_id dev = w->devices[device_id];
err = clBuildProgram(program_, 1, &dev, nullptr, nullptr, nullptr);
if (err != CL_SUCCESS) {
size_t len;
std::string log;
clGetProgramBuildInfo(
program_, dev, CL_PROGRAM_BUILD_LOG, 0, nullptr, &len);
log.resize(len);
clGetProgramBuildInfo(
program_, dev, CL_PROGRAM_BUILD_LOG, len, &log[0], nullptr);
LOG(FATAL) << "OpenCL build error for device=" << dev << log;
}
device_built_flag_[device_id] = true;
}
// build kernel
cl_int err;
cl_kernel kernel = clCreateKernel(program_, func_name.c_str(), &err);
OPENCL_CHECK_ERROR(err);
t->kernel_table[e.kernel_id].kernel = kernel;
t->kernel_table[e.kernel_id].version = e.version;
kernels_.push_back(kernel);
return kernel;
}
Module OpenCLModuleCreate(
std::string data,
std::string fmt,
std::unordered_map<std::string, FunctionInfo> fmap,
std::string source) {
std::shared_ptr<OpenCLModuleNode> n =
std::make_shared<OpenCLModuleNode>(data, fmt, fmap, source);
n->Init();
return Module(n);
}
// Load module from module.
Module OpenCLModuleLoadFile(const std::string& file_name,
const std::string& format) {
std::string data;
std::unordered_map<std::string, FunctionInfo> fmap;
std::string fmt = GetFileFormat(file_name, format);
std::string meta_file = GetMetaFilePath(file_name);
LoadBinaryFromFile(file_name, &data);
LoadMetaDataFromFile(meta_file, &fmap);
return OpenCLModuleCreate(data, fmt, fmap, std::string());
}
Module OpenCLModuleLoadBinary(void* strm) {
dmlc::Stream* stream = static_cast<dmlc::Stream*>(strm);
std::string data;
std::unordered_map<std::string, FunctionInfo> fmap;
std::string fmt;
stream->Read(&fmt);
stream->Read(&fmap);
stream->Read(&data);
return OpenCLModuleCreate(data, fmt, fmap, std::string());
}
TVM_REGISTER_GLOBAL("module.loadfile_cl")
.set_body([](TVMArgs args, TVMRetValue* rv) {
*rv = OpenCLModuleLoadFile(args[0], args[1]);
});
TVM_REGISTER_GLOBAL("module.loadfile_clbin")
.set_body([](TVMArgs args, TVMRetValue* rv) {
*rv = OpenCLModuleLoadFile(args[0], args[1]);
});
TVM_REGISTER_GLOBAL("module.loadbinary_opencl")
.set_body([](TVMArgs args, TVMRetValue* rv) {
*rv = OpenCLModuleLoadBinary(args[0]);
});
} // namespace runtime
} // namespace tvm
<|endoftext|> |
<commit_before>#include "renderer.hpp"
#include <algorithm>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include "addr_space.hpp"
#include "address.hpp"
#include "const.hpp"
#include "cpu.hpp"
#include "cursor.hpp"
#include "instruction.hpp"
#include "printer.hpp"
#include "ram.hpp"
#include "util.hpp"
using namespace std;
/*
* Only public method. Also static. It creates new object every time
* it gets called.
*/
vector<vector<string>> Renderer::renderState(const Printer &printerIn,
const Ram &ramIn,
const Cpu &cpuIn,
const Cursor &cursorIn,
const View &viewIn) {
Renderer instance(printerIn, ramIn, cpuIn, cursorIn, viewIn);
vector<vector<string>> out;
for (vector<string> line : viewIn.lines) {
out.push_back(instance.insertActualValues(line));
}
return out;
}
vector<string> Renderer::insertActualValues(vector<string> lineIn) {
vector<bool> highlightedChars = getHighlightedLocations(lineIn);
vector<string> lineOut;
for (string cIn : lineIn) {
string sOut;
bool charIsALightbulb = ALL_INDICATORS.count(cIn);
if (charIsALightbulb) {
sOut = getLightbulb(cIn);
} else {
sOut = cIn;
}
lineOut.push_back(sOut);
}
return insertEscSeqences(lineOut, highlightedChars);
}
vector<string> Renderer::insertEscSeqences(
vector<string> lineWithoutEscapeSeqences, vector<bool> highlightedChars) {
vector<string> lineOut;
bool insideHighlightBlock = false;
for (size_t i = 0; i < lineWithoutEscapeSeqences.size(); i++) {
bool firstCharInsideBlock = highlightedChars[i] && !insideHighlightBlock;
if (firstCharInsideBlock) {
lineOut.insert(lineOut.end(), HIGHLIGHT_ESC_VEC.begin(),
HIGHLIGHT_ESC_VEC.end());
insideHighlightBlock = true;
}
bool firstCharOutsideBlock = !highlightedChars[i] && insideHighlightBlock;
if (firstCharOutsideBlock) {
lineOut.insert(lineOut.end(), HIGHLIGHT_END_ESC_VEC.begin(),
HIGHLIGHT_END_ESC_VEC.end());
insideHighlightBlock = false;
}
lineOut.push_back(lineWithoutEscapeSeqences[i]);
}
return lineOut;
}
/////////////////////////////////
/// GET HIGHLIGHTED LOCATIONS ///
/////////////////////////////////
vector<bool> Renderer::getHighlightedLocations(vector<string> lineIn) {
vector<bool> highlightedLocations (lineIn.size(), false);
highlightPc(highlightedLocations, lineIn);
if (executionEnded()) {
return highlightedLocations;
}
highlightCursor(highlightedLocations, lineIn);
Instruction *inst = getInstruction();
bool cursorOnData = inst == NULL;
if (cursorOnData) {
highlightPointingInstructions(highlightedLocations, lineIn);
return highlightedLocations;
}
highlightOperator(highlightedLocations, lineIn, inst);
if (inst->adr.space == CODE) {
highlightCodeWord(highlightedLocations, lineIn, inst);
} else if (inst->adr.space == DATA) {
highlightDataWord(highlightedLocations, lineIn, inst);
}
return highlightedLocations;
}
void Renderer::highlightPc(vector<bool> &highlightedLocations,
vector<string> &lineIn) {
if (executionHasntStarted() || pcHighlighted) {
return;
}
for (size_t i = 0; i < lineIn.size(); i++) {
if (lineIn[i] == CODE_ADR_INDICATOR) {
int index = switchIndex[CODE_ADR_INDICATOR];
if (pcPointingToAddress(index)) {
highlightedLocations[i] = true;
pcHighlighted = true;
return;
}
}
}
}
void Renderer::highlightCursor(vector<bool> &highlightedLocations,
vector<string> &lineIn) {
if (!executionHasntStarted() || cursorHighlighted) {
return;
}
if (cursor.getAddressSpace() == CODE) {
findCursor(highlightedLocations, lineIn, CODE_INDICATOR);
} else if (cursor.getAddressSpace() == DATA) {
findCursor(highlightedLocations, lineIn, DATA_INDICATOR);
}
}
void Renderer::findCursor(vector<bool> &highlightedLocations,
vector<string> &lineIn, string c) {
int indexDelta = 0;
for (size_t i = 0; i < lineIn.size(); i++) {
if (lineIn[i] == c) {
int lightbulbIndex = switchIndex[c] + indexDelta++;
if (cursor.getAbsoluteBitIndex() == lightbulbIndex) {
highlightedLocations[i] = true;
cursorHighlighted = true;
return;
}
}
}
}
void Renderer::highlightPointingInstructions(vector<bool> &highlightedLocations,
vector<string> &lineIn) {
set<int> *pointingInstructions = getIndexesOfPointingInstructions();
for (size_t i = 0; i < lineIn.size(); i++) {
if (lineIn[i] == CODE_INDICATOR) {
int addressValue = switchIndex[CODE_INDICATOR] / WORD_SIZE;
if (pointingInstructions->count(addressValue)) {
highlightedLocations[i] = true;
}
}
}
}
void Renderer::highlightOperator(vector<bool> &highlightedLocations,
vector<string> &lineIn,
Instruction *inst) {
string exclude;
if (inst->isLogic()) {
exclude = LOGIC_OPS_INDICATOR[min(inst->logicIndex, 8)];
}
if (inst->index == INC_DEC_OPS_INDEX) {
if (inst->logicIndex <= 7) {
exclude = "INC";
} else {
exclude = "DEC";
}
}
string label = " " + inst->label;
label.append(11 - inst->label.length(), ' ');
highlightLabel(highlightedLocations, lineIn, Util::stringToVecOfString(label),
Util::stringToVecOfString(exclude));
}
void Renderer::highlightCodeWord(vector<bool> &highlightedLocations,
vector<string> &lineIn,
Instruction *inst) {
if (inst->adr.val == LAST_ADDRESS) {
vector<string> stopLabel = Util::stringToVecOfString(LAST_CODE_ADDR_LABEL);
highlightLabel(highlightedLocations, lineIn, stopLabel, {});
return;
}
highlightWord(highlightedLocations, lineIn, CODE_INDICATOR, CODE);
}
void Renderer::highlightDataWord(vector<bool> &highlightedLocations,
vector<string> &lineIn,
Instruction *inst) {
if (inst->adr.val == LAST_ADDRESS) {
vector<string> inOutLabel = Util::stringToVecOfString(LAST_DATA_ADDR_LABEL);
highlightLabel(highlightedLocations, lineIn, inOutLabel, {});
return;
}
highlightWord(highlightedLocations, lineIn, DATA_INDICATOR, DATA);
}
void Renderer::highlightWord(vector<bool> &highlightedLocations,
vector<string> &lineIn, string indicator,
AddrSpace addrSpace) {
for (size_t i = 0; i < lineIn.size(); i++) {
if (lineIn[i] == indicator) {
int addressValue = switchIndex[indicator] / WORD_SIZE;
Address adr = Address(addrSpace, Util::getBoolNibb(addressValue));
if (instructionPointingToAddress(adr)) {
highlightedLocations[i] = !highlightedLocations[i];
}
}
}
}
void Renderer::highlightLabel(vector<bool> &highlightedLocations,
vector<string> &lineIn,
vector<string> label,
vector<string> exclude) {
auto it = search(begin(lineIn), end(lineIn), begin(label), end(label));
int labelPosition = it - lineIn.begin();
bool notFound = it == end(lineIn);
if (notFound) {
return;
}
size_t excludePosition = numeric_limits<size_t>::max();
if (!exclude.empty()) {
it = search(begin(label), end(label), begin(exclude), end(exclude));
excludePosition = it - label.begin();
}
for (size_t i = labelPosition; i < labelPosition + label.size(); i++) {
bool highlight = (i < labelPosition + excludePosition ||
i >= labelPosition + excludePosition + exclude.size());
if (highlight) {
highlightedLocations[i] = true;
}
}
}
/////////////////////
/// GET LIGHTBULB ///
/////////////////////
string Renderer::getLightbulb(string cIn) {
int i = switchIndex[cIn]++;
if (cIn == CODE_INDICATOR) {
return getCodeBit(i);
} else if (cIn == DATA_INDICATOR) {
return getDataBit(i);
} else if (cIn == REGISTER_INDICATOR) {
return view.getLightbulb(cpu.getRegister().at(i));
} else if (cIn == CODE_ADR_INDICATOR) {
return getAdrIndicator(CODE, i);
} else if (cIn == DATA_ADR_INDICATOR) {
return getAdrIndicator(DATA, i);
} else if (cIn == OUTPUT_INDICATOR) {
return getFormattedOutput(i);
}
cerr << "There was an error parsing a drawing file.";
cerr << " Problem with char" << cIn << ". Will ignore it.";
return " ";
}
string Renderer::getCodeBit(int i) {
return getBit(CODE, i);
}
string Renderer::getDataBit(int i) {
return getBit(DATA, i);
}
string Renderer::getBit(AddrSpace space, int i) {
pair<int, int> coord = convertIndexToCoordinates(i);
bool state = ram.state.at(space).at(coord.second).at(coord.first);
return view.getLightbulb(state);
}
pair<int, int> Renderer::convertIndexToCoordinates(int index) {
int y = index / WORD_SIZE;
int x = index % WORD_SIZE;
return pair<int, int>(x, y);
}
bool Renderer::pcPointingToAddress(int adr) {
if (executionHasntStarted()) {
return false;
}
return Util::getInt(cpu.getPc()) == adr;
}
string Renderer::getAdrIndicator(AddrSpace addrSpace, int index) {
Address indicatorsAddress = Address(addrSpace, Util::getBoolNibb(index));
bool addressReferenced = isAddressReferencedFirstOrder(indicatorsAddress);
return view.getLightbulb(addressReferenced);
}
string Renderer::getFormattedOutput(int i) {
if (printer.getPrinterOutput().length() <= (unsigned) i) {
return " ";
} else {
return string(1, printer.getPrinterOutput().at(i));
}
}
///////////////////////
/// GET INSTRUCTION ///
///////////////////////
Instruction* Renderer::getInstruction() {
bool noActiveInstruction = !machineActive() &&
cursor.getAddressSpace() == DATA;
if (noActiveInstruction) {
return NULL;
}
if (instruction.size() == 0) {
instruction.push_back(initializeInstruction());
}
return &instruction[0];
}
bool Renderer::machineActive() {
return !(executionHasntStarted() || executionEnded());
}
bool Renderer::executionHasntStarted() {
return cpu.getCycle() == 0;
}
bool Renderer::executionEnded() {
return Util::getInt(cpu.getPc()) == RAM_SIZE;
}
Instruction Renderer::initializeInstruction() {
if (machineActive()) {
return cpu.getInstruction();
} else {
return Instruction(cursor.getWord(), EMPTY_WORD, &ram);
}
}
bool Renderer::instructionHasId(int id) {
Instruction *inst = getInstruction();
if (inst == NULL) {
return false;
}
return inst->index == id;
}
/*
* Is instruction pointing to passed address in passed address space.
*/
bool Renderer::instructionPointingToAddress(Address adr) {
Instruction *inst = getInstruction();
if (inst == NULL) {
return false;
}
return inst->adr == adr;
}
set<int>* Renderer::getIndexesOfPointingInstructions() {
if (pointingInstructions.empty()) {
pointingInstructions = generatePointingInstructions();
if (pointingInstructions.empty()) {
pointingInstructions.insert(-1);
}
}
return &pointingInstructions;
}
set<int> Renderer::generatePointingInstructions() {
vector<Instruction> *allInstructions = getEffectiveInstructions();
set<int> out;
int i = 0;
for (Instruction inst : *allInstructions) {
if (inst.adr == cursor.getAddress()) {
out.insert(i);
}
i++;
}
return out;
}
vector<Instruction>* Renderer::getEffectiveInstructions() {
if (!effectiveInstructionsInitialized) {
vector<Instruction> *allInstructions = getAllInstructions();
int lastNonemptyInst = -1;
int i = 0;
for (Instruction inst : *allInstructions) {
if (inst.val != EMPTY_WORD) {
lastNonemptyInst = i;
}
i++;
}
bool somePresent = lastNonemptyInst != -1;
if (somePresent) {
effectiveInstructions = vector<Instruction>(
allInstructions->begin(),
allInstructions->begin() + lastNonemptyInst+1);
}
effectiveInstructionsInitialized = true;
}
return &effectiveInstructions;
}
vector<Instruction>* Renderer::getAllInstructions() {
if (allInstructions.empty()) {
for (vector<bool> word : ram.state.at(CODE)) {
Instruction inst = Instruction(word, cpu.getRegister(), &ram);
allInstructions.push_back(inst);
}
}
return &allInstructions;
}
bool Renderer::isAddressReferencedFirstOrder(Address adr) {
vector<Instruction> *instructions = getAllInstructions();
for (Instruction inst : *instructions) {
vector<Address> aaa = inst.firstOrderAdr;
bool isReferenced = find(aaa.begin(), aaa.end(), adr) != aaa.end();
if (isReferenced) {
return true;
}
}
return false;
}<commit_msg>Address indicator isn't turn on by empty instructions<commit_after>#include "renderer.hpp"
#include <algorithm>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include "addr_space.hpp"
#include "address.hpp"
#include "const.hpp"
#include "cpu.hpp"
#include "cursor.hpp"
#include "instruction.hpp"
#include "printer.hpp"
#include "ram.hpp"
#include "util.hpp"
using namespace std;
/*
* Only public method. Also static. It creates new object every time
* it gets called.
*/
vector<vector<string>> Renderer::renderState(const Printer &printerIn,
const Ram &ramIn,
const Cpu &cpuIn,
const Cursor &cursorIn,
const View &viewIn) {
Renderer instance(printerIn, ramIn, cpuIn, cursorIn, viewIn);
vector<vector<string>> out;
for (vector<string> line : viewIn.lines) {
out.push_back(instance.insertActualValues(line));
}
return out;
}
vector<string> Renderer::insertActualValues(vector<string> lineIn) {
vector<bool> highlightedChars = getHighlightedLocations(lineIn);
vector<string> lineOut;
for (string cIn : lineIn) {
string sOut;
bool charIsALightbulb = ALL_INDICATORS.count(cIn);
if (charIsALightbulb) {
sOut = getLightbulb(cIn);
} else {
sOut = cIn;
}
lineOut.push_back(sOut);
}
return insertEscSeqences(lineOut, highlightedChars);
}
vector<string> Renderer::insertEscSeqences(
vector<string> lineWithoutEscapeSeqences, vector<bool> highlightedChars) {
vector<string> lineOut;
bool insideHighlightBlock = false;
for (size_t i = 0; i < lineWithoutEscapeSeqences.size(); i++) {
bool firstCharInsideBlock = highlightedChars[i] && !insideHighlightBlock;
if (firstCharInsideBlock) {
lineOut.insert(lineOut.end(), HIGHLIGHT_ESC_VEC.begin(),
HIGHLIGHT_ESC_VEC.end());
insideHighlightBlock = true;
}
bool firstCharOutsideBlock = !highlightedChars[i] && insideHighlightBlock;
if (firstCharOutsideBlock) {
lineOut.insert(lineOut.end(), HIGHLIGHT_END_ESC_VEC.begin(),
HIGHLIGHT_END_ESC_VEC.end());
insideHighlightBlock = false;
}
lineOut.push_back(lineWithoutEscapeSeqences[i]);
}
return lineOut;
}
/////////////////////////////////
/// GET HIGHLIGHTED LOCATIONS ///
/////////////////////////////////
vector<bool> Renderer::getHighlightedLocations(vector<string> lineIn) {
vector<bool> highlightedLocations (lineIn.size(), false);
highlightPc(highlightedLocations, lineIn);
if (executionEnded()) {
return highlightedLocations;
}
highlightCursor(highlightedLocations, lineIn);
Instruction *inst = getInstruction();
bool cursorOnData = inst == NULL;
if (cursorOnData) {
highlightPointingInstructions(highlightedLocations, lineIn);
return highlightedLocations;
}
highlightOperator(highlightedLocations, lineIn, inst);
if (inst->adr.space == CODE) {
highlightCodeWord(highlightedLocations, lineIn, inst);
} else if (inst->adr.space == DATA) {
highlightDataWord(highlightedLocations, lineIn, inst);
}
return highlightedLocations;
}
void Renderer::highlightPc(vector<bool> &highlightedLocations,
vector<string> &lineIn) {
if (executionHasntStarted() || pcHighlighted) {
return;
}
for (size_t i = 0; i < lineIn.size(); i++) {
if (lineIn[i] == CODE_ADR_INDICATOR) {
int index = switchIndex[CODE_ADR_INDICATOR];
if (pcPointingToAddress(index)) {
highlightedLocations[i] = true;
pcHighlighted = true;
return;
}
}
}
}
void Renderer::highlightCursor(vector<bool> &highlightedLocations,
vector<string> &lineIn) {
if (!executionHasntStarted() || cursorHighlighted) {
return;
}
if (cursor.getAddressSpace() == CODE) {
findCursor(highlightedLocations, lineIn, CODE_INDICATOR);
} else if (cursor.getAddressSpace() == DATA) {
findCursor(highlightedLocations, lineIn, DATA_INDICATOR);
}
}
void Renderer::findCursor(vector<bool> &highlightedLocations,
vector<string> &lineIn, string c) {
int indexDelta = 0;
for (size_t i = 0; i < lineIn.size(); i++) {
if (lineIn[i] == c) {
int lightbulbIndex = switchIndex[c] + indexDelta++;
if (cursor.getAbsoluteBitIndex() == lightbulbIndex) {
highlightedLocations[i] = true;
cursorHighlighted = true;
return;
}
}
}
}
void Renderer::highlightPointingInstructions(vector<bool> &highlightedLocations,
vector<string> &lineIn) {
set<int> *pointingInstructions = getIndexesOfPointingInstructions();
for (size_t i = 0; i < lineIn.size(); i++) {
if (lineIn[i] == CODE_INDICATOR) {
int addressValue = switchIndex[CODE_INDICATOR] / WORD_SIZE;
if (pointingInstructions->count(addressValue)) {
highlightedLocations[i] = true;
}
}
}
}
void Renderer::highlightOperator(vector<bool> &highlightedLocations,
vector<string> &lineIn,
Instruction *inst) {
string exclude;
if (inst->isLogic()) {
exclude = LOGIC_OPS_INDICATOR[min(inst->logicIndex, 8)];
}
if (inst->index == INC_DEC_OPS_INDEX) {
if (inst->logicIndex <= 7) {
exclude = "INC";
} else {
exclude = "DEC";
}
}
string label = " " + inst->label;
label.append(11 - inst->label.length(), ' ');
highlightLabel(highlightedLocations, lineIn, Util::stringToVecOfString(label),
Util::stringToVecOfString(exclude));
}
void Renderer::highlightCodeWord(vector<bool> &highlightedLocations,
vector<string> &lineIn,
Instruction *inst) {
if (inst->adr.val == LAST_ADDRESS) {
vector<string> stopLabel = Util::stringToVecOfString(LAST_CODE_ADDR_LABEL);
highlightLabel(highlightedLocations, lineIn, stopLabel, {});
return;
}
highlightWord(highlightedLocations, lineIn, CODE_INDICATOR, CODE);
}
void Renderer::highlightDataWord(vector<bool> &highlightedLocations,
vector<string> &lineIn,
Instruction *inst) {
if (inst->adr.val == LAST_ADDRESS) {
vector<string> inOutLabel = Util::stringToVecOfString(LAST_DATA_ADDR_LABEL);
highlightLabel(highlightedLocations, lineIn, inOutLabel, {});
return;
}
highlightWord(highlightedLocations, lineIn, DATA_INDICATOR, DATA);
}
void Renderer::highlightWord(vector<bool> &highlightedLocations,
vector<string> &lineIn, string indicator,
AddrSpace addrSpace) {
for (size_t i = 0; i < lineIn.size(); i++) {
if (lineIn[i] == indicator) {
int addressValue = switchIndex[indicator] / WORD_SIZE;
Address adr = Address(addrSpace, Util::getBoolNibb(addressValue));
if (instructionPointingToAddress(adr)) {
highlightedLocations[i] = !highlightedLocations[i];
}
}
}
}
void Renderer::highlightLabel(vector<bool> &highlightedLocations,
vector<string> &lineIn,
vector<string> label,
vector<string> exclude) {
auto it = search(begin(lineIn), end(lineIn), begin(label), end(label));
int labelPosition = it - lineIn.begin();
bool notFound = it == end(lineIn);
if (notFound) {
return;
}
size_t excludePosition = numeric_limits<size_t>::max();
if (!exclude.empty()) {
it = search(begin(label), end(label), begin(exclude), end(exclude));
excludePosition = it - label.begin();
}
for (size_t i = labelPosition; i < labelPosition + label.size(); i++) {
bool highlight = (i < labelPosition + excludePosition ||
i >= labelPosition + excludePosition + exclude.size());
if (highlight) {
highlightedLocations[i] = true;
}
}
}
/////////////////////
/// GET LIGHTBULB ///
/////////////////////
string Renderer::getLightbulb(string cIn) {
int i = switchIndex[cIn]++;
if (cIn == CODE_INDICATOR) {
return getCodeBit(i);
} else if (cIn == DATA_INDICATOR) {
return getDataBit(i);
} else if (cIn == REGISTER_INDICATOR) {
return view.getLightbulb(cpu.getRegister().at(i));
} else if (cIn == CODE_ADR_INDICATOR) {
return getAdrIndicator(CODE, i);
} else if (cIn == DATA_ADR_INDICATOR) {
return getAdrIndicator(DATA, i);
} else if (cIn == OUTPUT_INDICATOR) {
return getFormattedOutput(i);
}
cerr << "There was an error parsing a drawing file.";
cerr << " Problem with char" << cIn << ". Will ignore it.";
return " ";
}
string Renderer::getCodeBit(int i) {
return getBit(CODE, i);
}
string Renderer::getDataBit(int i) {
return getBit(DATA, i);
}
string Renderer::getBit(AddrSpace space, int i) {
pair<int, int> coord = convertIndexToCoordinates(i);
bool state = ram.state.at(space).at(coord.second).at(coord.first);
return view.getLightbulb(state);
}
pair<int, int> Renderer::convertIndexToCoordinates(int index) {
int y = index / WORD_SIZE;
int x = index % WORD_SIZE;
return pair<int, int>(x, y);
}
bool Renderer::pcPointingToAddress(int adr) {
if (executionHasntStarted()) {
return false;
}
return Util::getInt(cpu.getPc()) == adr;
}
string Renderer::getAdrIndicator(AddrSpace addrSpace, int index) {
Address indicatorsAddress = Address(addrSpace, Util::getBoolNibb(index));
bool addressReferenced = isAddressReferencedFirstOrder(indicatorsAddress);
return view.getLightbulb(addressReferenced);
}
string Renderer::getFormattedOutput(int i) {
if (printer.getPrinterOutput().length() <= (unsigned) i) {
return " ";
} else {
return string(1, printer.getPrinterOutput().at(i));
}
}
///////////////////////
/// GET INSTRUCTION ///
///////////////////////
Instruction* Renderer::getInstruction() {
bool noActiveInstruction = !machineActive() &&
cursor.getAddressSpace() == DATA;
if (noActiveInstruction) {
return NULL;
}
if (instruction.size() == 0) {
instruction.push_back(initializeInstruction());
}
return &instruction[0];
}
bool Renderer::machineActive() {
return !(executionHasntStarted() || executionEnded());
}
bool Renderer::executionHasntStarted() {
return cpu.getCycle() == 0;
}
bool Renderer::executionEnded() {
return Util::getInt(cpu.getPc()) == RAM_SIZE;
}
Instruction Renderer::initializeInstruction() {
if (machineActive()) {
return cpu.getInstruction();
} else {
return Instruction(cursor.getWord(), EMPTY_WORD, &ram);
}
}
bool Renderer::instructionHasId(int id) {
Instruction *inst = getInstruction();
if (inst == NULL) {
return false;
}
return inst->index == id;
}
/*
* Is instruction pointing to passed address in passed address space.
*/
bool Renderer::instructionPointingToAddress(Address adr) {
Instruction *inst = getInstruction();
if (inst == NULL) {
return false;
}
return inst->adr == adr;
}
set<int>* Renderer::getIndexesOfPointingInstructions() {
if (pointingInstructions.empty()) {
pointingInstructions = generatePointingInstructions();
if (pointingInstructions.empty()) {
pointingInstructions.insert(-1);
}
}
return &pointingInstructions;
}
set<int> Renderer::generatePointingInstructions() {
vector<Instruction> *allInstructions = getEffectiveInstructions();
set<int> out;
int i = 0;
for (Instruction inst : *allInstructions) {
if (inst.adr == cursor.getAddress()) {
out.insert(i);
}
i++;
}
return out;
}
/*
* Doesn't include empty instructions from last non-empty on.
*/
vector<Instruction>* Renderer::getEffectiveInstructions() {
if (!effectiveInstructionsInitialized) {
vector<Instruction> *allInstructions = getAllInstructions();
int lastNonemptyInst = -1;
int i = 0;
for (Instruction inst : *allInstructions) {
if (inst.val != EMPTY_WORD) {
lastNonemptyInst = i;
}
i++;
}
bool somePresent = lastNonemptyInst != -1;
if (somePresent) {
effectiveInstructions = vector<Instruction>(
allInstructions->begin(),
allInstructions->begin() + lastNonemptyInst+1);
}
effectiveInstructionsInitialized = true;
}
return &effectiveInstructions;
}
vector<Instruction>* Renderer::getAllInstructions() {
if (allInstructions.empty()) {
for (vector<bool> word : ram.state.at(CODE)) {
Instruction inst = Instruction(word, cpu.getRegister(), &ram);
allInstructions.push_back(inst);
}
}
return &allInstructions;
}
bool Renderer::isAddressReferencedFirstOrder(Address adr) {
vector<Instruction> *instructions = getEffectiveInstructions();
for (Instruction inst : *instructions) {
vector<Address> aaa = inst.firstOrderAdr;
bool isReferenced = find(aaa.begin(), aaa.end(), adr) != aaa.end();
if (isReferenced) {
return true;
}
}
return false;
}<|endoftext|> |
<commit_before>#include <map>
#include <string>
#include <iostream>
#include <docopt/docopt.h>
#include "serve.hpp"
#include "simple_commands.hpp"
int main(int argc, char * argv[])
{
static const char usage[] =
R"(Remote SimGrid command-line tool.
Usage:
rsg serve <platform-file> [--port=<port>] [-- <sg-options>...]
rsg add-actor <actor-name> <sg-host>
[--hostname=<host>] [--port=<port>] [--no-autoconnect]
[--] <command> [<command-args>...]
rsg start [--hostname=<host>] [--port=<port>]
rsg status [--hostname=<host>] [--port=<port>] [--retry-timeout=<ms>]
rsg kill [--hostname=<host>] [--reason=<reason>] [--port=<port>]
rsg --help
Options:
-h --hostname <host> Server's hostname [default: 127.0.0.1].
-p --port <port> Server's TCP port [default: 35000].
--retry-timeout <ms> If set, retry connection until timeout in milliseconds.
)";
// Parse CLI arguments.
auto args = docopt::docopt(usage, { argv + 1, argv + argc }, true);
// Check argument validity
std::string server_hostname = args["--hostname"].asString();
int server_port = args["--port"].asLong();
// Debug printing, should be removed.
/*std::cout << "Arguments:" << std::endl;
for(auto const & arg : args) {
std::cout << " " << arg.first << ": " << arg.second << std::endl;
}*/
// Manage subcommands.
int return_code = 0;
if (args["serve"].asBool())
{
std::string platform_file = args["<platform-file>"].asString();
std::vector<std::string> simgrid_options = args["<sg-options>"].asStringList();
return_code = serve(platform_file, server_port, simgrid_options);
}
else if (args["kill"].asBool())
{
std::string kill_reason = "";
if (args["--reason"].isString())
kill_reason = args["--reason"].asString();
return_code = kill(server_hostname, server_port, kill_reason);
}
else if (args["start"].asBool())
{
return_code = start(server_hostname, server_port);
}
else if (args["status"].asBool())
{
int retry_timeout_ms = 0;
if (args["--retry-timeout"].isString())
retry_timeout_ms = args["--retry-timeout"].asLong();
return_code = status(server_hostname, server_port, retry_timeout_ms);
}
else if (args["add-actor"].asBool())
{
std::string actor_name = args["<actor-name>"].asString();
std::string vhost_name = args["<sg-host>"].asString();
bool autoconnect = !args["--no-autoconnect"].asBool();
std::string command = args["<command>"].asString();
std::vector<std::string> command_args = args["<command-args>"].asStringList();
return_code = add_actor(server_hostname, server_port, actor_name, vhost_name,
autoconnect, command, command_args);
}
return return_code;
}
<commit_msg>[rsg] serve --daemon<commit_after>#include <map>
#include <string>
#include <iostream>
#include <string.h>
#include <docopt/docopt.h>
#include "serve.hpp"
#include "simple_commands.hpp"
int main(int argc, char * argv[])
{
static const char usage[] =
R"(Remote SimGrid command-line tool.
Usage:
rsg serve <platform-file> [--port=<port>] [--daemon] [-- <sg-options>...]
rsg add-actor <actor-name> <sg-host>
[--hostname=<host>] [--port=<port>] [--no-autoconnect]
[--] <command> [<command-args>...]
rsg start [--hostname=<host>] [--port=<port>]
rsg status [--hostname=<host>] [--port=<port>] [--retry-timeout=<ms>]
rsg kill [--hostname=<host>] [--reason=<reason>] [--port=<port>]
rsg --help
Options:
-h --hostname <host> Server's hostname [default: 127.0.0.1].
-p --port <port> Server's TCP port [default: 35000].
-d --daemon Run as a deamon — i.e., in background.
--retry-timeout <ms> If set, retry connection until timeout in milliseconds.
)";
// Parse CLI arguments.
auto args = docopt::docopt(usage, { argv + 1, argv + argc }, true);
// Check argument validity
std::string server_hostname = args["--hostname"].asString();
int server_port = args["--port"].asLong();
// Debug printing, should be removed.
/*std::cout << "Arguments:" << std::endl;
for(auto const & arg : args) {
std::cout << " " << arg.first << ": " << arg.second << std::endl;
}*/
// Manage subcommands.
int return_code = 0;
if (args["serve"].asBool())
{
std::string platform_file = args["<platform-file>"].asString();
std::vector<std::string> simgrid_options = args["<sg-options>"].asStringList();
if (args["--daemon"].asBool()) {
if (daemon(1, 1) != 0) {
printf("Could not daemon: %s\n", strerror(errno));
return 1;
}
}
return_code = serve(platform_file, server_port, simgrid_options);
}
else if (args["kill"].asBool())
{
std::string kill_reason = "";
if (args["--reason"].isString())
kill_reason = args["--reason"].asString();
return_code = kill(server_hostname, server_port, kill_reason);
}
else if (args["start"].asBool())
{
return_code = start(server_hostname, server_port);
}
else if (args["status"].asBool())
{
int retry_timeout_ms = 0;
if (args["--retry-timeout"].isString())
retry_timeout_ms = args["--retry-timeout"].asLong();
return_code = status(server_hostname, server_port, retry_timeout_ms);
}
else if (args["add-actor"].asBool())
{
std::string actor_name = args["<actor-name>"].asString();
std::string vhost_name = args["<sg-host>"].asString();
bool autoconnect = !args["--no-autoconnect"].asBool();
std::string command = args["<command>"].asString();
std::vector<std::string> command_args = args["<command-args>"].asStringList();
return_code = add_actor(server_hostname, server_port, actor_name, vhost_name,
autoconnect, command, command_args);
}
return return_code;
}
<|endoftext|> |
<commit_before>//
// src/main_utils/parse_list_argument.h
// tbd
//
// Created by inoahdev on 1/26/18.
// Copyright © 2018 inoahdev. All rights reserved.
//
#include <cerrno>
#include "../mach-o/utils/tbd.h"
#include "../misc/current_directory.h"
#include "../misc/recurse.h"
#include "parse_list_argument.h"
#include "tbd_print_field_information.h"
#include "tbd_with_options.h"
namespace main_utils {
bool parse_list_argument(const char *argument, int &index, int argc, const char *argv[]) noexcept {
auto option = &argument[1];
if (option[0] == '-') {
option++;
}
if (strcmp(option, "list-architectures") == 0) {
if (index != 1) {
fprintf(stderr, "Option (%s) needs to be run by itself or with a path to a mach-o file\n", argument);
return 1;
}
// Two modes exist for --list-architectures, either list out the
// architecture-info table, or list the architectures of a single
// provided path to a mach-o file
if (index == argc - 1) {
auto architecture_info = macho::get_architecture_info_table();
fputs(architecture_info->name, stdout);
architecture_info++;
while (architecture_info->name != nullptr) {
fprintf(stdout, ", %s", architecture_info->name);
architecture_info++;
}
} else {
index++;
// Don't allow other arguments
// to --list-architectures
if (index + 2 <= argc) {
fprintf(stderr, "Unrecognized argument: %s\n", argv[index + 1]);
return 1;
}
auto file = macho::file();
auto path = misc::path_with_current_directory(argv[index]);
struct stat sbuf;
if (stat(path.c_str(), &sbuf) != 0) {
fprintf(stderr, "Failed to retrieve information on object at provided path, failing with error: %s\n", strerror(errno));
return 1;
}
if (!S_ISREG(sbuf.st_mode)) {
fputs("Object at provided path is not a regular file\n", stderr);
return 1;
}
switch (file.open(path.c_str())) {
case macho::file::open_result::ok:
break;
case macho::file::open_result::not_a_macho:
fputs("File at provided path is not a mach-o\n", stderr);
return 1;
case macho::file::open_result::invalid_macho:
fputs("File at provided path is an invalid mach-o\n", stderr);
return 1;
case macho::file::open_result::failed_to_open_stream:
fprintf(stderr, "Failed to open stream for file at provided path, failing with error: %s\n", strerror(errno));
return 1;
case macho::file::open_result::failed_to_retrieve_information:
fprintf(stderr, "Failed to retrieve information on object at provided path, failing with error: %s\n", strerror(errno));
return 1;
case macho::file::open_result::stream_seek_error:
case macho::file::open_result::stream_read_error:
fputs("Encountered an error while parsing file at provided path\n", stderr);
return 1;
case macho::file::open_result::zero_containers:
fputs("Mach-o file at provided path has zero architectures\n", stderr);
return 1;
case macho::file::open_result::too_many_containers:
fputs("Mach-o file at provided path has too many architectures for its file-size\n", stderr);
return 1;
case macho::file::open_result::containers_goes_past_end_of_file:
fputs("Mach-o file at provided path's architectures goes past end of file\n", stderr);
return 1;
case macho::file::open_result::overlapping_containers:
fputs("Mach-o file at provided path has overlapping architectures\n", stderr);
return 1;
case macho::file::open_result::invalid_container:
fputs("Mach-o file at provided path has an invalid architecture\n", stderr);
return 1;
}
// Store architecture names in a vector before printing
// so we can handle any errors encountered first
auto cndex = 0;
auto names = std::vector<const char *>();
for (const auto &container : file.containers) {
const auto container_subtype = macho::subtype_from_cputype(macho::cputype(container.header.cputype), container.header.cpusubtype);
if (container_subtype == macho::subtype::none) {
fprintf(stderr, "Unrecognized cpu-subtype for architecture at index %d\n", cndex);
return 1;
}
const auto architecture_info = macho::architecture_info_from_cputype(macho::cputype(container.header.cputype), container_subtype);
if (!architecture_info) {
fprintf(stderr, "Unrecognized cputype information for architecture at index %d\n", cndex);
return 1;
}
cndex++;
}
fputs(names.front(), stdout);
for (auto iter = names.cbegin() + 1; iter != names.cend(); iter++) {
fprintf(stdout, ", %s", *iter);
}
}
fputc('\n', stdout);
return 0;
} else if (strcmp(option, "list-macho-dynamic-libraries") == 0) {
if (index != 1) {
fprintf(stderr, "Option (%s) needs to be run by itself or with a path to a mach-o file\n", argument);
return 1;
}
// Two different modes exist for --list-macho-dynamic-libraries;
// either recurse current-directory with default options, or
// recurse provided director(ies) with provided options
index++;
if (index != argc) {
auto paths = std::vector<std::pair<struct main_utils::tbd_with_options::options, std::string>>();
struct main_utils::tbd_with_options::options options;
options.recurse_directories_at_path = true;
for (; index != argc; index++) {
const auto &argument = argv[index];
const auto &argument_front = argument[0];
if (argument_front == '-') {
auto option = &argument[1];
if (option[0] == '\0') {
fputs("Please provide a valid option\n", stderr);
}
if (option[0] == '-') {
option++;
}
if (strcmp(option, "dont-print-warnings") == 0) {
options.ignore_warnings = true;
} else if (strcmp(option, "r") == 0) {
if (index + 1 != argc) {
if (strcmp(argv[index + 1], "once") == 0) {
index++;
} else if (strcmp(argv[index + 1], "all") == 0) {
options.recurse_subdirectories_at_path = true;
index++;
}
}
} else {
fprintf(stderr, "Unrecognized argument: %s\n", argument);
return 1;
}
continue;
}
auto path = misc::path_with_current_directory(argv[index]);
struct stat sbuf;
if (stat(path.c_str(), &sbuf) != 0) {
if (index == argc - 1) {
fprintf(stderr, "Failed to retrieve information on file at provided path, failing with error: %s\n", strerror(errno));
} else {
fprintf(stderr, "Failed to retrieve information on file (at path %s), failing with error: %s\n", path.c_str(), strerror(errno));
}
return 1;
}
if (!S_ISDIR(sbuf.st_mode)) {
if (index == argc - 1) {
fputs("Object at provided path is not a directory\n", stderr);
} else {
fprintf(stderr, "Object (at path %s) is not a directory\n", path.c_str());
}
return 1;
}
paths.emplace_back(options, std::move(path));
options.clear();
}
if (paths.empty()) {
fputs("No directories have been provided to recurse in\n", stderr);
return 1;
}
const auto &back = paths.back();
for (const auto &pair : paths) {
const auto &options = pair.first;
const auto &path = pair.second;
auto recurse_options = misc::recurse::options();
if (!options.ignore_warnings) {
recurse_options.print_warnings = true;
}
if (options.recurse_subdirectories_at_path) {
recurse_options.recurse_subdirectories = true;
}
auto filetypes = misc::recurse::filetypes();
filetypes.dynamic_library = true;
const auto recursion_result = misc::recurse::macho_files(path.c_str(), filetypes, recurse_options, [](const macho::file &file, const std::string &path) {
fprintf(stderr, "%s\n", path.c_str());
return true;
});
switch (recursion_result) {
case misc::recurse::operation_result::ok:
break;
case misc::recurse::operation_result::failed_to_open_directory:
if (paths.size() != 1) {
fprintf(stderr, "Failed to open directory (at path %s), failing with error: %s\n", path.c_str(), strerror(errno));
} else {
fprintf(stderr, "Failed to open directory at provided path, failing with error: %s\n", strerror(errno));
}
break;
case misc::recurse::operation_result::found_no_matching_files:
if (options.recurse_subdirectories_at_path) {
if (paths.size() != 1) {
fprintf(stderr, "Found no mach-o dynamic library files while recursing through directory and its sub-directories at path: %s\n", path.c_str());
} else {
fputs("Found no mach-o dynamic library files while recursing through directory and its sub-directories at provided path\n", stderr);
}
} else {
if (paths.size() != 1) {
fprintf(stderr, "Found no mach-o dynamic library files while recursing through directory at path: %s\n", path.c_str());
} else {
fputs("Found no mach-o dynamic library files while recursing through directory at provided path\n", stderr);
}
}
break;
default:
break;
}
// Print a newline between each pair
if (pair != back) {
fputc('\n', stdout);
}
}
} else {
auto path = misc::retrieve_current_directory();
auto recurse_options = misc::recurse::options();
recurse_options.print_warnings = true;
recurse_options.recurse_subdirectories = true;
auto filetypes = misc::recurse::filetypes();
filetypes.dynamic_library = true;
const auto recursion_result = misc::recurse::macho_files(path, filetypes, recurse_options, [](const macho::file &file, const std::string &path) {
fprintf(stderr, "%s\n", path.c_str());
return true;
});
switch (recursion_result) {
case misc::recurse::operation_result::ok:
break;
case misc::recurse::operation_result::failed_to_open_directory:
fprintf(stderr, "Failed to open directory at current-directory, failing with error: %s\n", strerror(errno));
break;
case misc::recurse::operation_result::found_no_matching_files:
fputs("Found no mach-o dynamic library files while recursing through directory and its sub-directories at provided path\n", stderr);
break;
default:
break;
}
}
return 0;
} else if (strcmp(option, "list-objc-constraint") == 0) {
if (index != 1 || index != argc - 1) {
fprintf(stderr, "Option (%s) needs to be run by itself\n", argument);
return 1;
}
fputs("none\nretain_release\nretain_release_or_gc\nretain_release_for_simulator\ngc\n", stderr);
return 0;
} else if (strcmp(option, "list-platform") == 0) {
if (index != 1 || index != argc - 1) {
fprintf(stderr, "Option (%s) needs to be run by itself\n", argument);
return 1;
}
main_utils::print_tbd_platforms();
return 0;
} else if (strcmp(option, "list-recurse") == 0) {
if (index != 1 || index != argc - 1) {
fprintf(stderr, "Option (%s) needs to be run by itself\n", argument);
return 1;
}
fputs("once, Recurse through all of a directory's files (default)\n", stdout);
fputs("all, Recurse through all of a directory's files and sub-directories\n", stdout);
return 0;
} else if (strcmp(option, "list-tbd-flags") == 0) {
if (index != 1 || index != argc - 1) {
fprintf(stderr, "Option (%s) needs to be run by itself\n", argument);
return 1;
}
fputs("flat_namespace\n", stdout);
fputs("not_app_extension_safe\n", stdout);
return 0;
} else if (strcmp(option, "list-tbd-versions") == 0) {
if (index != 1 || index != argc - 1) {
fprintf(stderr, "Option (%s) needs to be run by itself\n", argument);
return 1;
}
main_utils::print_tbd_versions();
return 0;
} else {
return false;
}
return true;
}
}
<commit_msg>Fix handling of return values and errors when parsing list arguments<commit_after>//
// src/main_utils/parse_list_argument.h
// tbd
//
// Created by inoahdev on 1/26/18.
// Copyright © 2018 inoahdev. All rights reserved.
//
#include <cerrno>
#include "../mach-o/utils/tbd.h"
#include "../misc/current_directory.h"
#include "../misc/recurse.h"
#include "parse_list_argument.h"
#include "tbd_print_field_information.h"
#include "tbd_with_options.h"
namespace main_utils {
bool parse_list_argument(const char *argument, int &index, int argc, const char *argv[]) noexcept {
auto option = &argument[1];
if (option[0] == '-') {
option++;
}
if (strcmp(option, "list-architectures") == 0) {
if (index != 1) {
fprintf(stderr, "Option (%s) needs to be run by itself or with a path to a mach-o file\n", argument);
exit(1);
}
// Two modes exist for --list-architectures, either list out the
// architecture-info table, or list the architectures of a single
// provided path to a mach-o file
if (index == argc - 1) {
auto architecture_info = macho::get_architecture_info_table();
fputs(architecture_info->name, stdout);
architecture_info++;
while (architecture_info->name != nullptr) {
fprintf(stdout, ", %s", architecture_info->name);
architecture_info++;
}
} else {
index++;
// Don't allow other arguments
// to --list-architectures
if (index + 2 <= argc) {
fprintf(stderr, "Unrecognized argument: %s\n", argv[index + 1]);
exit(1);
}
auto file = macho::file();
auto path = misc::path_with_current_directory(argv[index]);
struct stat sbuf;
if (stat(path.c_str(), &sbuf) != 0) {
fprintf(stderr, "Failed to retrieve information on object at provided path, failing with error: %s\n", strerror(errno));
exit(1);
}
if (!S_ISREG(sbuf.st_mode)) {
fputs("Object at provided path is not a regular file\n", stderr);
exit(1);
}
switch (file.open(path.c_str())) {
case macho::file::open_result::ok:
break;
case macho::file::open_result::not_a_macho:
fputs("File at provided path is not a mach-o\n", stderr);
exit(1);
case macho::file::open_result::invalid_macho:
fputs("File at provided path is an invalid mach-o\n", stderr);
exit(1);
case macho::file::open_result::failed_to_open_stream:
fprintf(stderr, "Failed to open stream for file at provided path, failing with error: %s\n", strerror(errno));
exit(1);
case macho::file::open_result::failed_to_retrieve_information:
fprintf(stderr, "Failed to retrieve information on object at provided path, failing with error: %s\n", strerror(errno));
exit(1);
case macho::file::open_result::stream_seek_error:
case macho::file::open_result::stream_read_error:
fputs("Encountered an error while parsing file at provided path\n", stderr);
exit(1);
case macho::file::open_result::zero_containers:
fputs("Mach-o file at provided path has zero architectures\n", stderr);
exit(1);
case macho::file::open_result::too_many_containers:
fputs("Mach-o file at provided path has too many architectures for its file-size\n", stderr);
exit(1);
case macho::file::open_result::containers_goes_past_end_of_file:
fputs("Mach-o file at provided path's architectures goes past end of file\n", stderr);
exit(1);
case macho::file::open_result::overlapping_containers:
fputs("Mach-o file at provided path has overlapping architectures\n", stderr);
exit(1);
case macho::file::open_result::invalid_container:
fputs("Mach-o file at provided path has an invalid architecture\n", stderr);
exit(1);
}
// Store architecture names in a vector before printing
// so we can handle any errors encountered first
auto cndex = 0;
auto names = std::vector<const char *>();
for (const auto &container : file.containers) {
const auto container_subtype = macho::subtype_from_cputype(macho::cputype(container.header.cputype), container.header.cpusubtype);
if (container_subtype == macho::subtype::none) {
fprintf(stderr, "Unrecognized cpu-subtype for architecture at index %d\n", cndex);
exit(1);
}
const auto architecture_info = macho::architecture_info_from_cputype(macho::cputype(container.header.cputype), container_subtype);
if (!architecture_info) {
fprintf(stderr, "Unrecognized cputype information for architecture at index %d\n", cndex);
exit(1);
}
cndex++;
}
fputs(names.front(), stdout);
for (auto iter = names.cbegin() + 1; iter != names.cend(); iter++) {
fprintf(stdout, ", %s", *iter);
}
}
fputc('\n', stdout);
} else if (strcmp(option, "list-macho-dynamic-libraries") == 0) {
if (index != 1) {
fprintf(stderr, "Option (%s) needs to be run by itself or with a path to a mach-o file\n", argument);
exit(1);
}
// Two different modes exist for --list-macho-dynamic-libraries;
// either recurse current-directory with default options, or
// recurse provided director(ies) with provided options
index++;
if (index != argc) {
auto paths = std::vector<std::pair<struct main_utils::tbd_with_options::options, std::string>>();
struct main_utils::tbd_with_options::options options;
options.recurse_directories_at_path = true;
for (; index != argc; index++) {
const auto &argument = argv[index];
const auto &argument_front = argument[0];
if (argument_front == '-') {
auto option = &argument[1];
if (option[0] == '\0') {
fputs("Please provide a valid option\n", stderr);
}
if (option[0] == '-') {
option++;
}
if (strcmp(option, "dont-print-warnings") == 0) {
options.ignore_warnings = true;
} else if (strcmp(option, "r") == 0) {
if (index + 1 != argc) {
if (strcmp(argv[index + 1], "once") == 0) {
index++;
} else if (strcmp(argv[index + 1], "all") == 0) {
options.recurse_subdirectories_at_path = true;
index++;
}
}
} else {
fprintf(stderr, "Unrecognized argument: %s\n", argument);
exit(1);
}
continue;
}
auto path = misc::path_with_current_directory(argv[index]);
struct stat sbuf;
if (stat(path.c_str(), &sbuf) != 0) {
if (index == argc - 1) {
fprintf(stderr, "Failed to retrieve information on file at provided path, failing with error: %s\n", strerror(errno));
} else {
fprintf(stderr, "Failed to retrieve information on file (at path %s), failing with error: %s\n", path.c_str(), strerror(errno));
}
exit(1);
}
if (!S_ISDIR(sbuf.st_mode)) {
if (index == argc - 1) {
fputs("Object at provided path is not a directory\n", stderr);
} else {
fprintf(stderr, "Object (at path %s) is not a directory\n", path.c_str());
}
exit(1);
}
paths.emplace_back(options, std::move(path));
options.clear();
}
if (paths.empty()) {
fputs("No directories have been provided to recurse in\n", stderr);
exit(1);
}
const auto &back = paths.back();
for (const auto &pair : paths) {
const auto &options = pair.first;
const auto &path = pair.second;
auto recurse_options = misc::recurse::options();
if (!options.ignore_warnings) {
recurse_options.print_warnings = true;
}
if (options.recurse_subdirectories_at_path) {
recurse_options.recurse_subdirectories = true;
}
auto filetypes = misc::recurse::filetypes();
filetypes.dynamic_library = true;
const auto recursion_result = misc::recurse::macho_files(path.c_str(), filetypes, recurse_options, [](const macho::file &file, const std::string &path) {
fprintf(stderr, "%s\n", path.c_str());
return true;
});
switch (recursion_result) {
case misc::recurse::operation_result::ok:
break;
case misc::recurse::operation_result::failed_to_open_directory:
if (paths.size() != 1) {
fprintf(stderr, "Failed to open directory (at path %s), failing with error: %s\n", path.c_str(), strerror(errno));
} else {
fprintf(stderr, "Failed to open directory at provided path, failing with error: %s\n", strerror(errno));
}
break;
case misc::recurse::operation_result::found_no_matching_files:
if (options.recurse_subdirectories_at_path) {
if (paths.size() != 1) {
fprintf(stderr, "Found no mach-o dynamic library files while recursing through directory and its sub-directories at path: %s\n", path.c_str());
} else {
fputs("Found no mach-o dynamic library files while recursing through directory and its sub-directories at provided path\n", stderr);
}
} else {
if (paths.size() != 1) {
fprintf(stderr, "Found no mach-o dynamic library files while recursing through directory at path: %s\n", path.c_str());
} else {
fputs("Found no mach-o dynamic library files while recursing through directory at provided path\n", stderr);
}
}
break;
default:
break;
}
// Print a newline between each pair
if (pair != back) {
fputc('\n', stdout);
}
}
} else {
auto path = misc::retrieve_current_directory();
auto recurse_options = misc::recurse::options();
recurse_options.print_warnings = true;
recurse_options.recurse_subdirectories = true;
auto filetypes = misc::recurse::filetypes();
filetypes.dynamic_library = true;
const auto recursion_result = misc::recurse::macho_files(path, filetypes, recurse_options, [](const macho::file &file, const std::string &path) {
fprintf(stderr, "%s\n", path.c_str());
return true;
});
switch (recursion_result) {
case misc::recurse::operation_result::ok:
break;
case misc::recurse::operation_result::failed_to_open_directory:
fprintf(stderr, "Failed to open directory at current-directory, failing with error: %s\n", strerror(errno));
break;
case misc::recurse::operation_result::found_no_matching_files:
fputs("Found no mach-o dynamic library files while recursing through directory and its sub-directories at provided path\n", stderr);
break;
default:
break;
}
}
} else if (strcmp(option, "list-objc-constraint") == 0) {
if (index != 1 || index != argc - 1) {
fprintf(stderr, "Option (%s) needs to be run by itself\n", argument);
exit(1);
}
fputs("none\nretain_release\nretain_release_or_gc\nretain_release_for_simulator\ngc\n", stderr);
} else if (strcmp(option, "list-platform") == 0) {
if (index != 1 || index != argc - 1) {
fprintf(stderr, "Option (%s) needs to be run by itself\n", argument);
exit(1);
}
main_utils::print_tbd_platforms();
} else if (strcmp(option, "list-recurse") == 0) {
if (index != 1 || index != argc - 1) {
fprintf(stderr, "Option (%s) needs to be run by itself\n", argument);
exit(1);
}
fputs("once, Recurse through all of a directory's files (default)\n", stdout);
fputs("all, Recurse through all of a directory's files and sub-directories\n", stdout);
} else if (strcmp(option, "list-tbd-flags") == 0) {
if (index != 1 || index != argc - 1) {
fprintf(stderr, "Option (%s) needs to be run by itself\n", argument);
exit(1);
}
fputs("flat_namespace\n", stdout);
fputs("not_app_extension_safe\n", stdout);
} else if (strcmp(option, "list-tbd-versions") == 0) {
if (index != 1 || index != argc - 1) {
fprintf(stderr, "Option (%s) needs to be run by itself\n", argument);
exit(1);
}
main_utils::print_tbd_versions();
} else {
return false;
}
return true;
}
}
<|endoftext|> |
<commit_before>#include "yuyvtoyuv420.h"
YUYVtoYUV420::YUYVtoYUV420(QString id, StatisticsInterface *stats,
std::shared_ptr<HWResourceManager> hwResources) :
Filter(id, "YUYVtoYUV420", stats, hwResources, YUYVVIDEO, YUV420VIDEO)
{}
void YUYVtoYUV420::process()
{
std::unique_ptr<Data> input = getInput();
while(input)
{
uint32_t finalDataSize = input->width*input->height*2;
std::unique_ptr<uchar[]> yuyv_frame(new uchar[finalDataSize]);
yuyv2yuv420_cpu(input->data.get(), yuyv_frame.get(), input->width, input->height);
input->type = YUYVVIDEO;
input->data = std::move(yuyv_frame);
input->data_size = finalDataSize;
sendOutput(std::move(input));
input = getInput();
}
}
void YUYVtoYUV420::yuyv2yuv420_cpu(uint8_t* input, uint8_t* output,
uint16_t width, uint16_t height)
{
}
<commit_msg>feature(Processing): Convert luma pixels from YUYV to YUV420<commit_after>#include "yuyvtoyuv420.h"
YUYVtoYUV420::YUYVtoYUV420(QString id, StatisticsInterface *stats,
std::shared_ptr<HWResourceManager> hwResources) :
Filter(id, "YUYVtoYUV420", stats, hwResources, YUYVVIDEO, YUV420VIDEO)
{}
void YUYVtoYUV420::process()
{
std::unique_ptr<Data> input = getInput();
while(input)
{
uint32_t finalDataSize = input->width*input->height + input->width*input->height/2;
std::unique_ptr<uchar[]> yuyv_frame(new uchar[finalDataSize]);
yuyv2yuv420_cpu(input->data.get(), yuyv_frame.get(), input->width, input->height);
input->type = YUYVVIDEO;
input->data = std::move(yuyv_frame);
input->data_size = finalDataSize;
sendOutput(std::move(input));
input = getInput();
}
}
void YUYVtoYUV420::yuyv2yuv420_cpu(uint8_t* input, uint8_t* output,
uint16_t width, uint16_t height)
{
// Luma pixels
for(int i = 0; i < width*height; i += 2)
{
output[i] = input[i*2];
output[i + 1] = input[i*2 + 2];
}
}
<|endoftext|> |
<commit_before>#include <string>
#include <nanogui/theme.h>
#include <nanogui/widget.h>
#include "dialogwindow.h"
#include "editorgui.h"
#include "helper.h"
#include "editorwidget.h"
#include "namedobject.h"
#include "widgetfactory.h"
DialogWindow::DialogWindow(EditorGUI *screen, nanogui::Theme *theme) : nanogui::Window(screen), gui(screen) {
using namespace nanogui;
setTheme(theme);
setFixedSize(Vector2i(screen->width()/2, screen->height()/2));
setSize(Vector2i(180,240));
setPosition(Vector2i(screen->width()/4, screen->height()/4));
setTitle("Dialog");
setVisible(true);
}
void DialogWindow::clear() {
int n = childCount();
int idx = 0;
while (n--) {
NamedObject *no = dynamic_cast<NamedObject *>(childAt(idx));
EditorWidget *ew = dynamic_cast<EditorWidget*>(no);
if (ew && ew->getRemote()) {
ew->getRemote()->unlink(ew);
}
removeChild(idx);
}
}
void DialogWindow::setStructure( Structure *s) {
if (!s) return;
StructureClass *sc = findClass(s->getKind());
if (!sc) {
std::cerr << "no structure class '" << s->getKind() << "' found\n";
return;
}
if ( s->getKind() != "SCREEN" && (!sc || sc->getBase() != "SCREEN") ) return;
clear();
loadStructure(s);
current_structure = s;
gui->performLayout();
}
void DialogWindow::loadStructure(Structure *s) {
StructureClass *sc = findClass(s->getKind());
if (sc && (s->getKind() == "SCREEN" || sc->getBase() == "SCREEN") ) {
if (sc && !s->getStructureDefinition())
s->setStructureDefinition(sc);
int pnum = 0;
nanogui::Vector2i offset;
nanogui::Vector2i frame_size;
for (auto param : sc->getLocals()) {
++pnum;
Structure *element = param.machine;
if (!element) {
continue;
}
std::string kind = element->getKind();
if (kind == "FRAME") {
auto properties = element->getProperties();
Value vx = properties.find("pos_x");
Value vy = properties.find("pos_y");
Value w = properties.find("width");
Value h = properties.find("height");
long x, y;
if (vx.asInteger(x) && vy.asInteger(y)) {
offset = nanogui::Vector2i(x,y);
}
if (w.asInteger(x) && h.asInteger(y)) {
frame_size = nanogui::Vector2i(x, y);
setFixedSize(frame_size);
setSize(frame_size);
}
break;
}
}
pnum = 0;
for (auto param : sc->getLocals()) {
++pnum;
Structure *element = param.machine;
if (!element) {
std::cout << "Warning: no structure for parameter " << pnum << "of " << s->getName() << "\n";
continue;
}
std::string kind = element->getKind();
StructureClass *element_class = findClass(kind);
WidgetParams params(s, this, element, gui, offset);
if (kind == "LABEL") {
createLabel(params);
}
if (kind == "IMAGE") {
createImage(params);
}
if (kind == "PROGRESS") {
createProgress(params);
}
if (kind == "TEXT") {
createText(params);
}
else if (kind == "PLOT" || (element_class &&element_class->getBase() == "PLOT") ) {
createPlot(params);
}
else if (kind == "BUTTON" || kind == "INDICATOR") {
createButton(params);
}
}
}
}
<commit_msg>automatically centre dialogs within the current window<commit_after>#include <string>
#include <nanogui/theme.h>
#include <nanogui/widget.h>
#include "dialogwindow.h"
#include "editorgui.h"
#include "helper.h"
#include "editorwidget.h"
#include "namedobject.h"
#include "widgetfactory.h"
DialogWindow::DialogWindow(EditorGUI *screen, nanogui::Theme *theme) : nanogui::Window(screen), gui(screen) {
using namespace nanogui;
setTheme(theme);
setFixedSize(Vector2i(gui->width()/2, gui->height()/2));
setSize(Vector2i(180,240));
setPosition(Vector2i(gui->width()/4, gui->height()/4));
setTitle("Dialog");
setVisible(true);
}
void DialogWindow::clear() {
int n = childCount();
int idx = 0;
while (n--) {
NamedObject *no = dynamic_cast<NamedObject *>(childAt(idx));
EditorWidget *ew = dynamic_cast<EditorWidget*>(no);
if (ew && ew->getRemote()) {
ew->getRemote()->unlink(ew);
}
removeChild(idx);
}
}
void DialogWindow::setStructure( Structure *s) {
if (!s) return;
StructureClass *sc = findClass(s->getKind());
if (!sc) {
std::cerr << "no structure class '" << s->getKind() << "' found\n";
return;
}
if ( s->getKind() != "SCREEN" && (!sc || sc->getBase() != "SCREEN") ) return;
clear();
loadStructure(s);
current_structure = s;
gui->performLayout();
}
void DialogWindow::loadStructure(Structure *s) {
StructureClass *sc = findClass(s->getKind());
if (sc && (s->getKind() == "SCREEN" || sc->getBase() == "SCREEN") ) {
if (sc && !s->getStructureDefinition())
s->setStructureDefinition(sc);
int pnum = 0;
nanogui::Vector2i offset;
nanogui::Vector2i frame_size;
for (auto param : sc->getLocals()) {
++pnum;
Structure *element = param.machine;
if (!element) {
continue;
}
std::string kind = element->getKind();
if (kind == "FRAME") {
auto properties = element->getProperties();
Value vx = properties.find("pos_x");
Value vy = properties.find("pos_y");
Value w = properties.find("width");
Value h = properties.find("height");
long x, y;
if (vx.asInteger(x) && vy.asInteger(y)) {
offset = nanogui::Vector2i(x,y);
}
if (w.asInteger(x) && h.asInteger(y)) {
frame_size = nanogui::Vector2i(x, y);
setFixedSize(frame_size);
setSize(frame_size);
auto pos = nanogui::Vector2i((gui->width() - frame_size.x())/2, (gui->height() - frame_size.y())/2);
setPosition(pos);
}
break;
}
}
pnum = 0;
for (auto param : sc->getLocals()) {
++pnum;
Structure *element = param.machine;
if (!element) {
std::cout << "Warning: no structure for parameter " << pnum << "of " << s->getName() << "\n";
continue;
}
std::string kind = element->getKind();
StructureClass *element_class = findClass(kind);
WidgetParams params(s, this, element, gui, offset);
if (kind == "LABEL") {
createLabel(params);
}
if (kind == "IMAGE") {
createImage(params);
}
if (kind == "PROGRESS") {
createProgress(params);
}
if (kind == "TEXT") {
createText(params);
}
else if (kind == "PLOT" || (element_class &&element_class->getBase() == "PLOT") ) {
createPlot(params);
}
else if (kind == "BUTTON" || kind == "INDICATOR") {
createButton(params);
}
}
}
}
<|endoftext|> |
<commit_before>/**
* @file lars_main.cpp
* @author Nishant Mehta
*
* Executable for LARS.
*/
#include <mlpack/core.hpp>
#include "lars.hpp"
PROGRAM_INFO("LARS", "An implementation of LARS: Least Angle Regression "
"(Stagewise/laSso). This is a stage-wise homotopy-based algorithm for "
"L1-regularized linear regression (LASSO) and L1+L2-regularized linear "
"regression (Elastic Net).\n"
"\n"
"Let X be a matrix where each row is a point and each column is a "
"dimension, and let y be a vector of targets.\n"
"\n"
"The Elastic Net problem is to solve\n\n"
" min_beta 0.5 || X * beta - y ||_2^2 + lambda_1 ||beta||_1 +\n"
" 0.5 lambda_2 ||beta||_2^2\n\n"
"If lambda_1 > 0 and lambda_2 = 0, the problem is the LASSO.\n"
"If lambda_1 > 0 and lambda_2 > 0, the problem is the Elastic Net.\n"
"If lambda_1 = 0 and lambda_2 > 0, the problem is ridge regression.\n"
"If lambda_1 = 0 and lambda_2 = 0, the problem is unregularized linear "
"regression.\n"
"\n"
"For efficiency reasons, it is not recommended to use this algorithm with "
"lambda_1 = 0. In that case, use the 'linear_regression' program, which "
"implements both unregularized linear regression and ridge regression.\n");
PARAM_STRING_REQ("input_file", "File containing covariates (X).",
"i");
PARAM_STRING_REQ("responses_file", "File containing y "
"(responses/observations).", "r");
PARAM_STRING("output_file", "File to save beta (linear estimator) to.", "o",
"output.csv");
PARAM_DOUBLE("lambda1", "Regularization parameter for l1-norm penalty.", "l",
0);
PARAM_DOUBLE("lambda2", "Regularization parameter for l2-norm penalty.", "L",
0);
PARAM_FLAG("use_cholesky", "Use Cholesky decomposition during computation "
"rather than explicitly computing the full Gram matrix.", "c");
using namespace arma;
using namespace std;
using namespace mlpack;
using namespace mlpack::regression;
int main(int argc, char* argv[])
{
// Handle parameters,
CLI::ParseCommandLine(argc, argv);
double lambda1 = CLI::GetParam<double>("lambda1");
double lambda2 = CLI::GetParam<double>("lambda2");
bool useCholesky = CLI::HasParam("use_cholesky");
// Load covariates. We can avoid LARS transposing our data by choosing to not
// transpose this data.
const string matXFilename = CLI::GetParam<string>("input_file");
mat matX;
data::Load(matXFilename, matX, true, false);
// Load responses. The responses should be a one-dimensional vector, and it
// seems more likely that these will be stored with one response per line (one
// per row). So we should not transpose upon loading.
const string yFilename = CLI::GetParam<string>("responses_file");
mat matY; // Will be a vector.
data::Load(yFilename, matY, true, false);
// Make sure y is oriented the right way.
if (matY.n_rows == 1)
matY = trans(matY);
if (matY.n_cols > 1)
Log::Fatal << "Only one column or row allowed in responses file!" << endl;
if (matY.n_elem != matX.n_rows)
Log::Fatal << "Number of responses must be equal to number of rows of X!"
<< endl;
// Do LARS.
LARS lars(useCholesky, lambda1, lambda2);
vec beta;
lars.Regress(matX, matY.unsafe_col(0), beta, false /* do not transpose */);
const string betaFilename = CLI::GetParam<string>("output_file");
beta.save(betaFilename, raw_ascii);
}
<commit_msg>Add option to predict values on test points.<commit_after>/**
* @file lars_main.cpp
* @author Nishant Mehta
*
* Executable for LARS.
*/
#include <mlpack/core.hpp>
#include "lars.hpp"
PROGRAM_INFO("LARS", "An implementation of LARS: Least Angle Regression "
"(Stagewise/laSso). This is a stage-wise homotopy-based algorithm for "
"L1-regularized linear regression (LASSO) and L1+L2-regularized linear "
"regression (Elastic Net).\n"
"\n"
"Let X be a matrix where each row is a point and each column is a "
"dimension, and let y be a vector of targets.\n"
"\n"
"The Elastic Net problem is to solve\n\n"
" min_beta 0.5 || X * beta - y ||_2^2 + lambda_1 ||beta||_1 +\n"
" 0.5 lambda_2 ||beta||_2^2\n\n"
"If lambda_1 > 0 and lambda_2 = 0, the problem is the LASSO.\n"
"If lambda_1 > 0 and lambda_2 > 0, the problem is the Elastic Net.\n"
"If lambda_1 = 0 and lambda_2 > 0, the problem is ridge regression.\n"
"If lambda_1 = 0 and lambda_2 = 0, the problem is unregularized linear "
"regression.\n"
"\n"
"For efficiency reasons, it is not recommended to use this algorithm with "
"lambda_1 = 0. In that case, use the 'linear_regression' program, which "
"implements both unregularized linear regression and ridge regression.\n");
PARAM_STRING_REQ("input_file", "File containing covariates (X).",
"i");
PARAM_STRING_REQ("responses_file", "File containing y "
"(responses/observations).", "r");
PARAM_STRING("output_file", "File to save beta (linear estimator) to.", "o",
"output.csv");
PARAM_STRING("test_file", "File containing points to regress on (test points).",
"t", "");
PARAM_STRING("output_predictions", "If --test_file is specified, this file is "
"where the predicted responses will be saved.", "p", "predictions.csv");
PARAM_DOUBLE("lambda1", "Regularization parameter for l1-norm penalty.", "l",
0);
PARAM_DOUBLE("lambda2", "Regularization parameter for l2-norm penalty.", "L",
0);
PARAM_FLAG("use_cholesky", "Use Cholesky decomposition during computation "
"rather than explicitly computing the full Gram matrix.", "c");
using namespace arma;
using namespace std;
using namespace mlpack;
using namespace mlpack::regression;
int main(int argc, char* argv[])
{
// Handle parameters,
CLI::ParseCommandLine(argc, argv);
double lambda1 = CLI::GetParam<double>("lambda1");
double lambda2 = CLI::GetParam<double>("lambda2");
bool useCholesky = CLI::HasParam("use_cholesky");
// Load covariates. We can avoid LARS transposing our data by choosing to not
// transpose this data.
const string matXFilename = CLI::GetParam<string>("input_file");
mat matX;
data::Load(matXFilename, matX, true, false);
// Load responses. The responses should be a one-dimensional vector, and it
// seems more likely that these will be stored with one response per line (one
// per row). So we should not transpose upon loading.
const string yFilename = CLI::GetParam<string>("responses_file");
mat matY; // Will be a vector.
data::Load(yFilename, matY, true, false);
// Make sure y is oriented the right way.
if (matY.n_rows == 1)
matY = trans(matY);
if (matY.n_cols > 1)
Log::Fatal << "Only one column or row allowed in responses file!" << endl;
if (matY.n_elem != matX.n_rows)
Log::Fatal << "Number of responses must be equal to number of rows of X!"
<< endl;
// Do LARS.
LARS lars(useCholesky, lambda1, lambda2);
vec beta;
lars.Regress(matX, matY.unsafe_col(0), beta, false /* do not transpose */);
const string betaFilename = CLI::GetParam<string>("output_file");
beta.save(betaFilename, raw_ascii);
if (CLI::HasParam("test_file"))
{
Log::Info << "Regressing on test points." << endl;
const string testFile = CLI::GetParam<string>("test_file");
const string outputPredictionsFile =
CLI::GetParam<string>("output_predictions");
// Load test points.
mat testPoints;
data::Load(testFile, testPoints, true, false);
arma::vec predictions;
lars.Predict(testPoints.t(), predictions, false);
// Save test predictions. One per line, so, we need a rowvec.
arma::rowvec predToSave = predictions.t();
data::Save(outputPredictionsFile, predToSave);
}
}
<|endoftext|> |
<commit_before>// sdl_main.cpp
#ifdef _WIN32
# define WINDOWS_LEAN_AND_MEAN
# define NOMINMAX
# include <windows.h>
#endif
#include <sstream>
#include <GL/glew.h>
#include <SDL.h>
#include <SDL_syswm.h>
#undef main
#include <glm/gtc/type_ptr.hpp>
#ifdef USE_ANTTWEAKBAR
# include <AntTweakBar.h>
#endif
#include <stdio.h>
#include <string.h>
#include <sstream>
#include "ShaderFunctions.h"
#include "Timer.h"
Timer g_timer;
int winw = 800;
int winh = 600;
struct Shadertoy {
GLuint prog;
GLint uloc_iResolution;
GLint uloc_iGlobalTime;
};
Shadertoy g_toy;
void PollEvents()
{
SDL_Event event;
while (SDL_PollEvent(&event))
{
switch(event.type)
{
case SDL_KEYDOWN:
case SDL_KEYUP:
break;
case SDL_MOUSEBUTTONDOWN:
case SDL_MOUSEBUTTONUP:
break;
case SDL_MOUSEMOTION:
break;
case SDL_MOUSEWHEEL:
break;
case SDL_WINDOWEVENT:
break;
case SDL_QUIT:
exit(0);
break;
default:
break;
}
}
}
void display()
{
glUseProgram(g_toy.prog);
if (g_toy.uloc_iResolution > -1) glUniform3f(g_toy.uloc_iResolution, (float)winw, (float)winh, 1.f);
if (g_toy.uloc_iGlobalTime > -1) glUniform1f(g_toy.uloc_iGlobalTime, g_timer.seconds());
glRecti(-1,-1,1,1);
}
int main(void)
{
///@todo cmd line aargs
if (SDL_Init(SDL_INIT_EVERYTHING) < 0)
{
return false;
}
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_COMPATIBILITY);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);
int winw = 800;
int winh = 600;
SDL_Window* pWindow = SDL_CreateWindow(
"kinderegg",
100,100,
winw, winh,
SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL);
// thank you http://www.brandonfoltz.com/2013/12/example-using-opengl-3-0-with-sdl2-and-glew/
SDL_GLContext glContext = SDL_GL_CreateContext(pWindow);
if (glContext == NULL)
{
printf("There was an error creating the OpenGL context!\n");
return 0;
}
const unsigned char *version = glGetString(GL_VERSION);
if (version == NULL)
{
printf("There was an error creating the OpenGL context!\n");
return 1;
}
SDL_GL_MakeCurrent(pWindow, glContext);
// Don't forget to initialize Glew, turn glewExperimental on to
// avoid problems fetching function pointers...
glewExperimental = GL_TRUE;
const GLenum l_Result = glewInit();
if (l_Result != GLEW_OK)
{
exit(EXIT_FAILURE);
}
g_toy.prog = makeShaderByName("basic");
g_toy.uloc_iResolution = glGetUniformLocation(g_toy.prog, "iResolution");
g_toy.uloc_iGlobalTime = glGetUniformLocation(g_toy.prog, "iGlobalTime");
int quit = 0;
while (quit == 0)
{
PollEvents();
display();
SDL_GL_SwapWindow(pWindow);
}
SDL_GL_DeleteContext(glContext);
SDL_DestroyWindow(pWindow);
SDL_Quit();
}
<commit_msg>Remove some extraneous includes.<commit_after>// sdl_main.cpp
#ifdef _WIN32
# define WINDOWS_LEAN_AND_MEAN
# define NOMINMAX
# include <windows.h>
#endif
#include <GL/glew.h>
#include <SDL.h>
#include <SDL_syswm.h>
#undef main
#include "ShaderFunctions.h"
#include "Timer.h"
Timer g_timer;
int winw = 800;
int winh = 600;
struct Shadertoy {
GLuint prog;
GLint uloc_iResolution;
GLint uloc_iGlobalTime;
};
Shadertoy g_toy;
void PollEvents()
{
SDL_Event event;
while (SDL_PollEvent(&event))
{
switch(event.type)
{
case SDL_KEYDOWN:
case SDL_KEYUP:
break;
case SDL_MOUSEBUTTONDOWN:
case SDL_MOUSEBUTTONUP:
break;
case SDL_MOUSEMOTION:
break;
case SDL_MOUSEWHEEL:
break;
case SDL_WINDOWEVENT:
break;
case SDL_QUIT:
exit(0);
break;
default:
break;
}
}
}
void display()
{
glUseProgram(g_toy.prog);
if (g_toy.uloc_iResolution > -1) glUniform3f(g_toy.uloc_iResolution, (float)winw, (float)winh, 1.f);
if (g_toy.uloc_iGlobalTime > -1) glUniform1f(g_toy.uloc_iGlobalTime, g_timer.seconds());
glRecti(-1,-1,1,1);
}
int main(void)
{
///@todo cmd line aargs
if (SDL_Init(SDL_INIT_EVERYTHING) < 0)
{
return false;
}
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_COMPATIBILITY);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);
int winw = 800;
int winh = 600;
SDL_Window* pWindow = SDL_CreateWindow(
"kinderegg",
100,100,
winw, winh,
SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL);
// thank you http://www.brandonfoltz.com/2013/12/example-using-opengl-3-0-with-sdl2-and-glew/
SDL_GLContext glContext = SDL_GL_CreateContext(pWindow);
if (glContext == NULL)
{
printf("There was an error creating the OpenGL context!\n");
return 0;
}
const unsigned char *version = glGetString(GL_VERSION);
if (version == NULL)
{
printf("There was an error creating the OpenGL context!\n");
return 1;
}
SDL_GL_MakeCurrent(pWindow, glContext);
// Don't forget to initialize Glew, turn glewExperimental on to
// avoid problems fetching function pointers...
glewExperimental = GL_TRUE;
const GLenum l_Result = glewInit();
if (l_Result != GLEW_OK)
{
exit(EXIT_FAILURE);
}
g_toy.prog = makeShaderByName("basic");
g_toy.uloc_iResolution = glGetUniformLocation(g_toy.prog, "iResolution");
g_toy.uloc_iGlobalTime = glGetUniformLocation(g_toy.prog, "iGlobalTime");
int quit = 0;
while (quit == 0)
{
PollEvents();
display();
SDL_GL_SwapWindow(pWindow);
}
SDL_GL_DeleteContext(glContext);
SDL_DestroyWindow(pWindow);
SDL_Quit();
}
<|endoftext|> |
<commit_before>/*************************************************
* Startup Self Tests Source File *
* (C) 1999-2007 Jack Lloyd *
*************************************************/
#include <botan/selftest.h>
#include <botan/lookup.h>
namespace Botan {
namespace {
/*************************************************
* Perform a Known Answer Test *
*************************************************/
void do_kat(const std::string& in, const std::string& out,
const std::string& algo_name, Filter* filter)
{
if(out.length())
{
Pipe pipe(new Hex_Decoder, filter, new Hex_Encoder);
pipe.process_msg(in);
if(out != pipe.read_all_as_string())
throw Self_Test_Failure("FIPS-140 " + algo_name + " test");
}
}
/*************************************************
* Perform a KAT for a cipher *
*************************************************/
void cipher_kat(const std::string& in, const std::string& out,
const std::string& key, const std::string& iv,
const std::string& cipher)
{
do_kat(in, out, cipher, get_cipher(cipher, key, iv, ENCRYPTION));
do_kat(out, in, cipher, get_cipher(cipher, key, iv, DECRYPTION));
}
/*************************************************
* Perform a KAT for a cipher *
*************************************************/
void cipher_kat(const std::string& cipher, const std::string& key,
const std::string& iv, const std::string& in,
const std::string& ecb_out, const std::string& cbc_out,
const std::string& cfb_out, const std::string& ofb_out,
const std::string& ctr_out)
{
if(!have_block_cipher(cipher))
return;
cipher_kat(in, ecb_out, key, "", cipher + "/ECB");
cipher_kat(in, cbc_out, key, iv, cipher + "/CBC/NoPadding");
cipher_kat(in, cfb_out, key, iv, cipher + "/CFB");
cipher_kat(in, ofb_out, key, iv, cipher + "/OFB");
cipher_kat(in, ctr_out, key, iv, cipher + "/CTR-BE");
}
/*************************************************
* Perform a KAT for a hash *
*************************************************/
void hash_kat(const std::string& hash, const std::string& in,
const std::string& out)
{
if(!have_hash(hash))
return;
do_kat(in, out, hash, new Hash_Filter(hash));
}
/*************************************************
* Perform a KAT for a MAC *
*************************************************/
void mac_kat(const std::string& mac, const std::string& in,
const std::string& out, const std::string& key)
{
if(!have_mac(mac))
return;
do_kat(in, out, mac, new MAC_Filter(mac, key));
}
}
/*************************************************
* Perform FIPS 140 Self Tests *
*************************************************/
bool passes_self_tests()
{
try {
cipher_kat("DES", "0123456789ABCDEF", "1234567890ABCDEF",
"4E6F77206973207468652074696D6520666F7220616C6C20",
"3FA40E8A984D48156A271787AB8883F9893D51EC4B563B53",
"E5C7CDDE872BF27C43E934008C389C0F683788499A7C05F6",
"F3096249C7F46E51A69E839B1A92F78403467133898EA622",
"F3096249C7F46E5135F24A242EEB3D3F3D6D5BE3255AF8C3",
"F3096249C7F46E51163A8CA0FFC94C27FA2F80F480B86F75");
cipher_kat("TripleDES",
"385D7189A5C3D485E1370AA5D408082B5CCCCB5E19F2D90E",
"C141B5FCCD28DC8A",
"6E1BD7C6120947A464A6AAB293A0F89A563D8D40D3461B68",
"64EAAD4ACBB9CEAD6C7615E7C7E4792FE587D91F20C7D2F4",
"6235A461AFD312973E3B4F7AA7D23E34E03371F8E8C376C9",
"E26BA806A59B0330DE40CA38E77A3E494BE2B212F6DD624B",
"E26BA806A59B03307DE2BCC25A08BA40A8BA335F5D604C62",
"E26BA806A59B03303C62C2EFF32D3ACDD5D5F35EBCC53371");
cipher_kat("AES",
"2B7E151628AED2A6ABF7158809CF4F3C",
"000102030405060708090A0B0C0D0E0F",
"6BC1BEE22E409F96E93D7E117393172A"
"AE2D8A571E03AC9C9EB76FAC45AF8E51",
"3AD77BB40D7A3660A89ECAF32466EF97"
"F5D3D58503B9699DE785895A96FDBAAF",
"7649ABAC8119B246CEE98E9B12E9197D"
"5086CB9B507219EE95DB113A917678B2",
"3B3FD92EB72DAD20333449F8E83CFB4A"
"C8A64537A0B3A93FCDE3CDAD9F1CE58B",
"3B3FD92EB72DAD20333449F8E83CFB4A"
"7789508D16918F03F53C52DAC54ED825",
"3B3FD92EB72DAD20333449F8E83CFB4A"
"010C041999E03F36448624483E582D0E");
hash_kat("SHA-1", "", "DA39A3EE5E6B4B0D3255BFEF95601890AFD80709");
hash_kat("SHA-1", "616263", "A9993E364706816ABA3E25717850C26C9CD0D89D");
hash_kat("SHA-1",
"6162636462636465636465666465666765666768666768696768696A"
"68696A6B696A6B6C6A6B6C6D6B6C6D6E6C6D6E6F6D6E6F706E6F7071",
"84983E441C3BD26EBAAE4AA1F95129E5E54670F1");
hash_kat("SHA-256", "",
"E3B0C44298FC1C149AFBF4C8996FB924"
"27AE41E4649B934CA495991B7852B855");
hash_kat("SHA-256", "616263",
"BA7816BF8F01CFEA414140DE5DAE2223"
"B00361A396177A9CB410FF61F20015AD");
hash_kat("SHA-256",
"6162636462636465636465666465666765666768666768696768696A"
"68696A6B696A6B6C6A6B6C6D6B6C6D6E6C6D6E6F6D6E6F706E6F7071",
"248D6A61D20638B8E5C026930C3E6039"
"A33CE45964FF2167F6ECEDD419DB06C1");
mac_kat("HMAC(SHA-1)", "4869205468657265",
"B617318655057264E28BC0B6FB378C8EF146BE00",
"0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B");
mac_kat("HMAC(SHA-256)", "4869205468657265",
"198A607EB44BFBC69903A0F1CF2BBDC5"
"BA0AA3F3D9AE3C1C7A3B1696A0B68CF7",
"0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B"
"0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B");
}
catch(std::exception& e)
{
printf("%s\n", e.what());
return false;
}
return true;
}
}
<commit_msg>Remove printf in catch block<commit_after>/*************************************************
* Startup Self Tests Source File *
* (C) 1999-2007 Jack Lloyd *
*************************************************/
#include <botan/selftest.h>
#include <botan/lookup.h>
namespace Botan {
namespace {
/*************************************************
* Perform a Known Answer Test *
*************************************************/
void do_kat(const std::string& in, const std::string& out,
const std::string& algo_name, Filter* filter)
{
if(out.length())
{
Pipe pipe(new Hex_Decoder, filter, new Hex_Encoder);
pipe.process_msg(in);
if(out != pipe.read_all_as_string())
throw Self_Test_Failure("FIPS-140 " + algo_name + " test");
}
}
/*************************************************
* Perform a KAT for a cipher *
*************************************************/
void cipher_kat(const std::string& in, const std::string& out,
const std::string& key, const std::string& iv,
const std::string& cipher)
{
do_kat(in, out, cipher, get_cipher(cipher, key, iv, ENCRYPTION));
do_kat(out, in, cipher, get_cipher(cipher, key, iv, DECRYPTION));
}
/*************************************************
* Perform a KAT for a cipher *
*************************************************/
void cipher_kat(const std::string& cipher, const std::string& key,
const std::string& iv, const std::string& in,
const std::string& ecb_out, const std::string& cbc_out,
const std::string& cfb_out, const std::string& ofb_out,
const std::string& ctr_out)
{
if(!have_block_cipher(cipher))
return;
cipher_kat(in, ecb_out, key, "", cipher + "/ECB");
cipher_kat(in, cbc_out, key, iv, cipher + "/CBC/NoPadding");
cipher_kat(in, cfb_out, key, iv, cipher + "/CFB");
cipher_kat(in, ofb_out, key, iv, cipher + "/OFB");
cipher_kat(in, ctr_out, key, iv, cipher + "/CTR-BE");
}
/*************************************************
* Perform a KAT for a hash *
*************************************************/
void hash_kat(const std::string& hash, const std::string& in,
const std::string& out)
{
if(!have_hash(hash))
return;
do_kat(in, out, hash, new Hash_Filter(hash));
}
/*************************************************
* Perform a KAT for a MAC *
*************************************************/
void mac_kat(const std::string& mac, const std::string& in,
const std::string& out, const std::string& key)
{
if(!have_mac(mac))
return;
do_kat(in, out, mac, new MAC_Filter(mac, key));
}
}
/*************************************************
* Perform FIPS 140 Self Tests *
*************************************************/
bool passes_self_tests()
{
try {
cipher_kat("DES", "0123456789ABCDEF", "1234567890ABCDEF",
"4E6F77206973207468652074696D6520666F7220616C6C20",
"3FA40E8A984D48156A271787AB8883F9893D51EC4B563B53",
"E5C7CDDE872BF27C43E934008C389C0F683788499A7C05F6",
"F3096249C7F46E51A69E839B1A92F78403467133898EA622",
"F3096249C7F46E5135F24A242EEB3D3F3D6D5BE3255AF8C3",
"F3096249C7F46E51163A8CA0FFC94C27FA2F80F480B86F75");
cipher_kat("TripleDES",
"385D7189A5C3D485E1370AA5D408082B5CCCCB5E19F2D90E",
"C141B5FCCD28DC8A",
"6E1BD7C6120947A464A6AAB293A0F89A563D8D40D3461B68",
"64EAAD4ACBB9CEAD6C7615E7C7E4792FE587D91F20C7D2F4",
"6235A461AFD312973E3B4F7AA7D23E34E03371F8E8C376C9",
"E26BA806A59B0330DE40CA38E77A3E494BE2B212F6DD624B",
"E26BA806A59B03307DE2BCC25A08BA40A8BA335F5D604C62",
"E26BA806A59B03303C62C2EFF32D3ACDD5D5F35EBCC53371");
cipher_kat("AES",
"2B7E151628AED2A6ABF7158809CF4F3C",
"000102030405060708090A0B0C0D0E0F",
"6BC1BEE22E409F96E93D7E117393172A"
"AE2D8A571E03AC9C9EB76FAC45AF8E51",
"3AD77BB40D7A3660A89ECAF32466EF97"
"F5D3D58503B9699DE785895A96FDBAAF",
"7649ABAC8119B246CEE98E9B12E9197D"
"5086CB9B507219EE95DB113A917678B2",
"3B3FD92EB72DAD20333449F8E83CFB4A"
"C8A64537A0B3A93FCDE3CDAD9F1CE58B",
"3B3FD92EB72DAD20333449F8E83CFB4A"
"7789508D16918F03F53C52DAC54ED825",
"3B3FD92EB72DAD20333449F8E83CFB4A"
"010C041999E03F36448624483E582D0E");
hash_kat("SHA-1", "", "DA39A3EE5E6B4B0D3255BFEF95601890AFD80709");
hash_kat("SHA-1", "616263", "A9993E364706816ABA3E25717850C26C9CD0D89D");
hash_kat("SHA-1",
"6162636462636465636465666465666765666768666768696768696A"
"68696A6B696A6B6C6A6B6C6D6B6C6D6E6C6D6E6F6D6E6F706E6F7071",
"84983E441C3BD26EBAAE4AA1F95129E5E54670F1");
hash_kat("SHA-256", "",
"E3B0C44298FC1C149AFBF4C8996FB924"
"27AE41E4649B934CA495991B7852B855");
hash_kat("SHA-256", "616263",
"BA7816BF8F01CFEA414140DE5DAE2223"
"B00361A396177A9CB410FF61F20015AD");
hash_kat("SHA-256",
"6162636462636465636465666465666765666768666768696768696A"
"68696A6B696A6B6C6A6B6C6D6B6C6D6E6C6D6E6F6D6E6F706E6F7071",
"248D6A61D20638B8E5C026930C3E6039"
"A33CE45964FF2167F6ECEDD419DB06C1");
mac_kat("HMAC(SHA-1)", "4869205468657265",
"B617318655057264E28BC0B6FB378C8EF146BE00",
"0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B");
mac_kat("HMAC(SHA-256)", "4869205468657265",
"198A607EB44BFBC69903A0F1CF2BBDC5"
"BA0AA3F3D9AE3C1C7A3B1696A0B68CF7",
"0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B"
"0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B");
}
catch(std::exception& e)
{
return false;
}
return true;
}
}
<|endoftext|> |
<commit_before><commit_msg>Fixed a crashbug in shutdown command<commit_after><|endoftext|> |
<commit_before>/*
*
* Copyright (c) 2020 Project CHIP Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <core/CHIPSafeCasts.h>
#include <support/CodeUtils.h>
#include <support/ErrorStr.h>
#include <support/SafeInt.h>
#include <transport/RendezvousSession.h>
#if CONFIG_DEVICE_LAYER
#include <platform/CHIPDeviceLayer.h>
#endif
#if CONFIG_NETWORK_LAYER_BLE
#include <transport/BLE.h>
#endif // CONFIG_NETWORK_LAYER_BLE
static const size_t kMax_SecureSDU_Length = 1024;
static constexpr uint32_t kSpake2p_Iteration_Count = 50000;
static const char * kSpake2pKeyExchangeSalt = "SPAKE2P Key Exchange Salt";
namespace chip {
enum NetworkProvisioningMsgTypes : uint8_t
{
kWiFiAssociationRequest = 0,
kIPAddressAssigned = 1,
};
CHIP_ERROR RendezvousSession::Init()
{
CHIP_ERROR err = CHIP_NO_ERROR;
mParams = params;
VerifyOrExit(mDelegate != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
VerifyOrExit(mParams.HasLocalNodeId(), err = CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrExit(mParams.HasSetupPINCode(), err = CHIP_ERROR_INVALID_ARGUMENT);
err = CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE;
#if CONFIG_NETWORK_LAYER_BLE
{
Transport::BLE * transport = new Transport::BLE();
err = transport->Init(this, mParams);
mTransport = transport;
mTransport->Retain();
transport->Release();
}
#endif // CONFIG_NETWORK_LAYER_BLE
SuccessOrExit(err);
if (mParams.HasDiscriminator() == false)
{
err = WaitForPairing(mParams.GetLocalNodeId(), mParams.GetSetupPINCode());
#if CONFIG_DEVICE_LAYER
DeviceLayer::PlatformMgr().AddEventHandler(ConnectivityHandler, reinterpret_cast<intptr_t>(this));
#endif
}
exit:
return err;
}
RendezvousSession::~RendezvousSession()
{
if (mTransport)
{
mTransport->Release();
mTransport = nullptr;
}
mDelegate = nullptr;
}
CHIP_ERROR RendezvousSession::SendMessage(System::PacketBuffer * msgBuf)
{
CHIP_ERROR err = mPairingInProgress ? SendPairingMessage(msgBuf)
: SendSecureMessage(Protocols::kChipProtocol_NetworkProvisioning,
NetworkProvisioningMsgTypes::kWiFiAssociationRequest, msgBuf);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
mPairingInProgress ? OnPairingError(err) : OnRendezvousError(err);
}
return err;
}
CHIP_ERROR RendezvousSession::SendPairingMessage(System::PacketBuffer * msgBuf)
{
CHIP_ERROR err = CHIP_NO_ERROR;
PacketHeader header;
uint16_t headerSize = 0;
VerifyOrExit(msgBuf != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrExit(msgBuf->Next() == nullptr, err = CHIP_ERROR_INVALID_MESSAGE_LENGTH);
err = header.Decode(msgBuf->Start(), msgBuf->DataLength(), &headerSize);
SuccessOrExit(err);
msgBuf->ConsumeHead(headerSize);
err = mTransport->SendMessage(header, Header::Flags::None(), Transport::PeerAddress::BLE(), msgBuf);
SuccessOrExit(err);
exit:
return err;
}
CHIP_ERROR RendezvousSession::SendSecureMessage(Protocols::CHIPProtocolId protocol, uint8_t msgType, System::PacketBuffer * msgBuf)
{
CHIP_ERROR err = CHIP_NO_ERROR;
PacketHeader packetHeader;
PayloadHeader payloadHeader;
MessageAuthenticationCode mac;
const uint16_t headerSize = payloadHeader.EncodeSizeBytes();
uint16_t actualEncodedHeaderSize;
uint8_t * data = nullptr;
uint16_t totalLen = 0;
uint16_t taglen = 0;
VerifyOrExit(msgBuf != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrExit(msgBuf->Next() == nullptr, err = CHIP_ERROR_INVALID_MESSAGE_LENGTH);
VerifyOrExit(msgBuf->TotalLength() < kMax_SecureSDU_Length, err = CHIP_ERROR_INVALID_MESSAGE_LENGTH);
VerifyOrExit(CanCastTo<uint16_t>(headerSize + msgBuf->TotalLength()), err = CHIP_ERROR_INVALID_MESSAGE_LENGTH);
packetHeader
.SetSourceNodeId(mParams.GetLocalNodeId()) //
.SetMessageId(mSecureMessageIndex) //
.SetEncryptionKeyID(mPairingSession.GetLocalKeyId()) //
.SetPayloadLength(static_cast<uint16_t>(headerSize + msgBuf->TotalLength()));
payloadHeader.SetProtocolID(protocol).SetMessageType(msgType);
VerifyOrExit(msgBuf->EnsureReservedSize(headerSize), err = CHIP_ERROR_NO_MEMORY);
msgBuf->SetStart(msgBuf->Start() - headerSize);
data = msgBuf->Start();
totalLen = msgBuf->TotalLength();
err = payloadHeader.Encode(data, totalLen, &actualEncodedHeaderSize);
SuccessOrExit(err);
err = mSecureSession.Encrypt(data, totalLen, data, packetHeader, payloadHeader.GetEncodePacketFlags(), mac);
SuccessOrExit(err);
err = mac.Encode(packetHeader, &data[totalLen], kMaxTagLen, &taglen);
SuccessOrExit(err);
VerifyOrExit(CanCastTo<uint16_t>(totalLen + taglen), err = CHIP_ERROR_INVALID_MESSAGE_LENGTH);
msgBuf->SetDataLength(static_cast<uint16_t>(totalLen + taglen));
err = mTransport->SendMessage(packetHeader, payloadHeader.GetEncodePacketFlags(), Transport::PeerAddress::BLE(), msgBuf);
SuccessOrExit(err);
mSecureMessageIndex++;
msgBuf = nullptr;
exit:
return err;
}
void RendezvousSession::OnPairingError(CHIP_ERROR err)
{
mPairingInProgress = false;
mDelegate->OnRendezvousError(err);
mDelegate->OnRendezvousStatusUpdate(RendezvousSessionDelegate::SecurePairingFailed);
}
void RendezvousSession::OnPairingComplete()
{
mPairingInProgress = false;
CHIP_ERROR err = mPairingSession.DeriveSecureSession((const unsigned char *) kSpake2pI2RSessionInfo,
strlen(kSpake2pI2RSessionInfo), mSecureSession);
VerifyOrExit(err == CHIP_NO_ERROR, ChipLogError(Ble, "Failed to initialize a secure session: %s", ErrorStr(err)));
mDelegate->OnRendezvousStatusUpdate(RendezvousSessionDelegate::SecurePairingSuccess);
mDelegate->OnRendezvousConnectionOpened();
exit:
return;
}
void RendezvousSession::OnRendezvousConnectionOpened()
{
if (mParams.HasDiscriminator())
{
CHIP_ERROR err = Pair(mParams.GetLocalNodeId(), mParams.GetSetupPINCode());
VerifyOrExit(err == CHIP_NO_ERROR, OnPairingError(err));
}
exit:
return;
}
void RendezvousSession::OnRendezvousConnectionClosed()
{
mDelegate->OnRendezvousConnectionClosed();
if (!mParams.HasDiscriminator() && !mParams.HasConnectionObject())
{
mSecureSession.Reset();
CHIP_ERROR err = WaitForPairing(mParams.GetLocalNodeId(), mParams.GetSetupPINCode());
VerifyOrExit(err == CHIP_NO_ERROR, OnPairingError(err));
}
exit:
return;
}
void RendezvousSession::OnRendezvousError(CHIP_ERROR err)
{
mDelegate->OnRendezvousError(err);
}
void RendezvousSession::OnRendezvousMessageReceived(PacketBuffer * msgBuf)
{
CHIP_ERROR err = CHIP_NO_ERROR;
err = mPairingInProgress ? HandlePairingMessage(msgBuf) : HandleSecureMessage(msgBuf);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
mPairingInProgress ? OnPairingError(err) : OnRendezvousError(err);
}
}
CHIP_ERROR RendezvousSession::HandlePairingMessage(PacketBuffer * msgBuf)
{
CHIP_ERROR err = CHIP_NO_ERROR;
PacketHeader packetHeader;
uint16_t headerSize = 0;
err = packetHeader.Decode(msgBuf->Start(), msgBuf->DataLength(), &headerSize);
SuccessOrExit(err);
msgBuf->ConsumeHead(headerSize);
err = mPairingSession.HandlePeerMessage(packetHeader, msgBuf);
SuccessOrExit(err);
exit:
return err;
}
CHIP_ERROR RendezvousSession::HandleSecureMessage(PacketBuffer * msgBuf)
{
CHIP_ERROR err = CHIP_NO_ERROR;
PacketHeader packetHeader;
PayloadHeader payloadHeader;
MessageAuthenticationCode mac;
uint16_t headerSize = 0;
uint8_t * data = nullptr;
uint8_t * plainText = nullptr;
uint16_t len = 0;
uint16_t decodedSize = 0;
uint16_t taglen = 0;
System::PacketBuffer * origMsg = nullptr;
err = packetHeader.Decode(msgBuf->Start(), msgBuf->DataLength(), &headerSize);
SuccessOrExit(err);
msgBuf->ConsumeHead(headerSize);
headerSize = payloadHeader.EncodeSizeBytes();
data = msgBuf->Start();
len = msgBuf->TotalLength();
#if CHIP_SYSTEM_CONFIG_USE_LWIP
/* This is a workaround for the case where PacketBuffer payload is not
allocated as an inline buffer to PacketBuffer structure */
origMsg = msgBuf;
msgBuf = PacketBuffer::NewWithAvailableSize(len);
msgBuf->SetDataLength(len, msgBuf);
#endif
plainText = msgBuf->Start();
// TODO: We need length checks here! https://github.com/project-chip/connectedhomeip/issues/2928
err = mac.Decode(packetHeader, &data[packetHeader.GetPayloadLength()], kMaxTagLen, &taglen);
SuccessOrExit(err);
len = static_cast<uint16_t>(len - taglen);
msgBuf->SetDataLength(len);
err = mSecureSession.Decrypt(data, len, plainText, packetHeader, payloadHeader.GetEncodePacketFlags(), mac);
SuccessOrExit(err);
err = payloadHeader.Decode(packetHeader.GetFlags(), plainText, headerSize, &decodedSize);
SuccessOrExit(err);
VerifyOrExit(headerSize == decodedSize, err = CHIP_ERROR_INCORRECT_STATE);
msgBuf->ConsumeHead(headerSize);
if (payloadHeader.GetProtocolID() == Protocols::kChipProtocol_NetworkProvisioning &&
payloadHeader.GetMessageType() == NetworkProvisioningMsgTypes::kIPAddressAssigned)
{
if (!IPAddress::FromString(Uint8::to_const_char(msgBuf->Start()), msgBuf->DataLength(), mDeviceAddress))
{
mDelegate->OnRendezvousStatusUpdate(RendezvousSessionDelegate::NetworkProvisioningFailed);
ExitNow(err = CHIP_ERROR_INVALID_ADDRESS);
}
mDelegate->OnRendezvousStatusUpdate(RendezvousSessionDelegate::NetworkProvisioningSuccess);
}
// else .. TBD once application dependency on this message has been removed, enable the else condition
{
mDelegate->OnRendezvousMessageReceived(msgBuf);
}
msgBuf = nullptr;
exit:
if (origMsg != nullptr)
{
PacketBuffer::Free(origMsg);
}
return err;
}
CHIP_ERROR RendezvousSession::WaitForPairing(Optional<NodeId> nodeId, uint32_t setupPINCode)
{
mPairingInProgress = true;
return mPairingSession.WaitForPairing(setupPINCode, kSpake2p_Iteration_Count, (const unsigned char *) kSpake2pKeyExchangeSalt,
strlen(kSpake2pKeyExchangeSalt), nodeId, 0, this);
}
CHIP_ERROR RendezvousSession::Pair(Optional<NodeId> nodeId, uint32_t setupPINCode)
{
mPairingInProgress = true;
return mPairingSession.Pair(setupPINCode, kSpake2p_Iteration_Count, (const unsigned char *) kSpake2pKeyExchangeSalt,
strlen(kSpake2pKeyExchangeSalt), nodeId, mNextKeyId++, this);
}
void RendezvousSession::SendIPAddress(IPAddress & addr)
{
CHIP_ERROR err = CHIP_NO_ERROR;
System::PacketBuffer * buffer = System::PacketBuffer::New();
char * addrStr = addr.ToString(Uint8::to_char(buffer->Start()), buffer->AvailableDataLength());
VerifyOrExit(addrStr != nullptr, err = CHIP_ERROR_INVALID_ADDRESS);
VerifyOrExit(mPairingInProgress == false, err = CHIP_ERROR_INCORRECT_STATE);
buffer->SetDataLength(strlen(addrStr) + 1);
err = SendSecureMessage(Protocols::kChipProtocol_NetworkProvisioning, NetworkProvisioningMsgTypes::kIPAddressAssigned, buffer);
SuccessOrExit(err);
exit:
if (CHIP_NO_ERROR != err)
{
OnRendezvousError(err);
PacketBuffer::Free(buffer);
}
}
#if CONFIG_DEVICE_LAYER
void RendezvousSession::ConnectivityHandler(const DeviceLayer::ChipDeviceEvent * event, intptr_t arg)
{
RendezvousSession * session = reinterpret_cast<RendezvousSession *>(arg);
VerifyOrExit(session != nullptr, /**/);
VerifyOrExit(event->Type == DeviceLayer::DeviceEventType::kInternetConnectivityChange, /**/);
VerifyOrExit(event->InternetConnectivityChange.IPv4 == DeviceLayer::kConnectivity_Established, /**/);
IPAddress addr;
IPAddress::FromString(event->InternetConnectivityChange.address, addr);
session->SendIPAddress(addr);
exit:
return;
}
#endif
} // namespace chip
<commit_msg>Fix post rebase build issues<commit_after>/*
*
* Copyright (c) 2020 Project CHIP Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <core/CHIPSafeCasts.h>
#include <support/CodeUtils.h>
#include <support/ErrorStr.h>
#include <support/SafeInt.h>
#include <transport/RendezvousSession.h>
#if CONFIG_DEVICE_LAYER
#include <platform/CHIPDeviceLayer.h>
#endif
#if CONFIG_NETWORK_LAYER_BLE
#include <transport/BLE.h>
#endif // CONFIG_NETWORK_LAYER_BLE
static const size_t kMax_SecureSDU_Length = 1024;
static constexpr uint32_t kSpake2p_Iteration_Count = 50000;
static const char * kSpake2pKeyExchangeSalt = "SPAKE2P Key Exchange Salt";
namespace chip {
enum NetworkProvisioningMsgTypes : uint8_t
{
kWiFiAssociationRequest = 0,
kIPAddressAssigned = 1,
};
CHIP_ERROR RendezvousSession::Init(const RendezvousParameters & params)
{
CHIP_ERROR err = CHIP_NO_ERROR;
mParams = params;
VerifyOrExit(mDelegate != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
VerifyOrExit(mParams.HasLocalNodeId(), err = CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrExit(mParams.HasSetupPINCode(), err = CHIP_ERROR_INVALID_ARGUMENT);
err = CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE;
#if CONFIG_NETWORK_LAYER_BLE
{
Transport::BLE * transport = new Transport::BLE();
err = transport->Init(this, mParams);
mTransport = transport;
mTransport->Retain();
transport->Release();
}
#endif // CONFIG_NETWORK_LAYER_BLE
SuccessOrExit(err);
if (mParams.HasDiscriminator() == false)
{
err = WaitForPairing(mParams.GetLocalNodeId(), mParams.GetSetupPINCode());
#if CONFIG_DEVICE_LAYER
DeviceLayer::PlatformMgr().AddEventHandler(ConnectivityHandler, reinterpret_cast<intptr_t>(this));
#endif
}
exit:
return err;
}
RendezvousSession::~RendezvousSession()
{
if (mTransport)
{
mTransport->Release();
mTransport = nullptr;
}
mDelegate = nullptr;
}
CHIP_ERROR RendezvousSession::SendMessage(System::PacketBuffer * msgBuf)
{
CHIP_ERROR err = mPairingInProgress ? SendPairingMessage(msgBuf)
: SendSecureMessage(Protocols::kChipProtocol_NetworkProvisioning,
NetworkProvisioningMsgTypes::kWiFiAssociationRequest, msgBuf);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
mPairingInProgress ? OnPairingError(err) : OnRendezvousError(err);
}
return err;
}
CHIP_ERROR RendezvousSession::SendPairingMessage(System::PacketBuffer * msgBuf)
{
CHIP_ERROR err = CHIP_NO_ERROR;
PacketHeader header;
uint16_t headerSize = 0;
VerifyOrExit(msgBuf != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrExit(msgBuf->Next() == nullptr, err = CHIP_ERROR_INVALID_MESSAGE_LENGTH);
err = header.Decode(msgBuf->Start(), msgBuf->DataLength(), &headerSize);
SuccessOrExit(err);
msgBuf->ConsumeHead(headerSize);
err = mTransport->SendMessage(header, Header::Flags::None(), Transport::PeerAddress::BLE(), msgBuf);
SuccessOrExit(err);
exit:
return err;
}
CHIP_ERROR RendezvousSession::SendSecureMessage(Protocols::CHIPProtocolId protocol, uint8_t msgType, System::PacketBuffer * msgBuf)
{
CHIP_ERROR err = CHIP_NO_ERROR;
PacketHeader packetHeader;
PayloadHeader payloadHeader;
MessageAuthenticationCode mac;
const uint16_t headerSize = payloadHeader.EncodeSizeBytes();
uint16_t actualEncodedHeaderSize;
uint8_t * data = nullptr;
uint16_t totalLen = 0;
uint16_t taglen = 0;
VerifyOrExit(msgBuf != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrExit(msgBuf->Next() == nullptr, err = CHIP_ERROR_INVALID_MESSAGE_LENGTH);
VerifyOrExit(msgBuf->TotalLength() < kMax_SecureSDU_Length, err = CHIP_ERROR_INVALID_MESSAGE_LENGTH);
VerifyOrExit(CanCastTo<uint16_t>(headerSize + msgBuf->TotalLength()), err = CHIP_ERROR_INVALID_MESSAGE_LENGTH);
packetHeader
.SetSourceNodeId(mParams.GetLocalNodeId()) //
.SetMessageId(mSecureMessageIndex) //
.SetEncryptionKeyID(mPairingSession.GetLocalKeyId()) //
.SetPayloadLength(static_cast<uint16_t>(headerSize + msgBuf->TotalLength()));
payloadHeader.SetProtocolID(protocol).SetMessageType(msgType);
VerifyOrExit(msgBuf->EnsureReservedSize(headerSize), err = CHIP_ERROR_NO_MEMORY);
msgBuf->SetStart(msgBuf->Start() - headerSize);
data = msgBuf->Start();
totalLen = msgBuf->TotalLength();
err = payloadHeader.Encode(data, totalLen, &actualEncodedHeaderSize);
SuccessOrExit(err);
err = mSecureSession.Encrypt(data, totalLen, data, packetHeader, payloadHeader.GetEncodePacketFlags(), mac);
SuccessOrExit(err);
err = mac.Encode(packetHeader, &data[totalLen], kMaxTagLen, &taglen);
SuccessOrExit(err);
VerifyOrExit(CanCastTo<uint16_t>(totalLen + taglen), err = CHIP_ERROR_INVALID_MESSAGE_LENGTH);
msgBuf->SetDataLength(static_cast<uint16_t>(totalLen + taglen));
err = mTransport->SendMessage(packetHeader, payloadHeader.GetEncodePacketFlags(), Transport::PeerAddress::BLE(), msgBuf);
SuccessOrExit(err);
mSecureMessageIndex++;
msgBuf = nullptr;
exit:
return err;
}
void RendezvousSession::OnPairingError(CHIP_ERROR err)
{
mPairingInProgress = false;
mDelegate->OnRendezvousError(err);
mDelegate->OnRendezvousStatusUpdate(RendezvousSessionDelegate::SecurePairingFailed);
}
void RendezvousSession::OnPairingComplete()
{
mPairingInProgress = false;
CHIP_ERROR err = mPairingSession.DeriveSecureSession((const unsigned char *) kSpake2pI2RSessionInfo,
strlen(kSpake2pI2RSessionInfo), mSecureSession);
VerifyOrExit(err == CHIP_NO_ERROR, ChipLogError(Ble, "Failed to initialize a secure session: %s", ErrorStr(err)));
mDelegate->OnRendezvousStatusUpdate(RendezvousSessionDelegate::SecurePairingSuccess);
mDelegate->OnRendezvousConnectionOpened();
exit:
return;
}
void RendezvousSession::OnRendezvousConnectionOpened()
{
if (mParams.HasDiscriminator())
{
CHIP_ERROR err = Pair(mParams.GetLocalNodeId(), mParams.GetSetupPINCode());
VerifyOrExit(err == CHIP_NO_ERROR, OnPairingError(err));
}
exit:
return;
}
void RendezvousSession::OnRendezvousConnectionClosed()
{
mDelegate->OnRendezvousConnectionClosed();
if (!mParams.HasDiscriminator() && !mParams.HasConnectionObject())
{
mSecureSession.Reset();
CHIP_ERROR err = WaitForPairing(mParams.GetLocalNodeId(), mParams.GetSetupPINCode());
VerifyOrExit(err == CHIP_NO_ERROR, OnPairingError(err));
}
exit:
return;
}
void RendezvousSession::OnRendezvousError(CHIP_ERROR err)
{
mDelegate->OnRendezvousError(err);
}
void RendezvousSession::OnRendezvousMessageReceived(PacketBuffer * msgBuf)
{
CHIP_ERROR err = CHIP_NO_ERROR;
err = mPairingInProgress ? HandlePairingMessage(msgBuf) : HandleSecureMessage(msgBuf);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
mPairingInProgress ? OnPairingError(err) : OnRendezvousError(err);
}
}
CHIP_ERROR RendezvousSession::HandlePairingMessage(PacketBuffer * msgBuf)
{
CHIP_ERROR err = CHIP_NO_ERROR;
PacketHeader packetHeader;
uint16_t headerSize = 0;
err = packetHeader.Decode(msgBuf->Start(), msgBuf->DataLength(), &headerSize);
SuccessOrExit(err);
msgBuf->ConsumeHead(headerSize);
err = mPairingSession.HandlePeerMessage(packetHeader, msgBuf);
SuccessOrExit(err);
exit:
return err;
}
CHIP_ERROR RendezvousSession::HandleSecureMessage(PacketBuffer * msgBuf)
{
CHIP_ERROR err = CHIP_NO_ERROR;
PacketHeader packetHeader;
PayloadHeader payloadHeader;
MessageAuthenticationCode mac;
uint16_t headerSize = 0;
uint8_t * data = nullptr;
uint8_t * plainText = nullptr;
uint16_t len = 0;
uint16_t decodedSize = 0;
uint16_t taglen = 0;
System::PacketBuffer * origMsg = nullptr;
err = packetHeader.Decode(msgBuf->Start(), msgBuf->DataLength(), &headerSize);
SuccessOrExit(err);
msgBuf->ConsumeHead(headerSize);
headerSize = payloadHeader.EncodeSizeBytes();
data = msgBuf->Start();
len = msgBuf->TotalLength();
#if CHIP_SYSTEM_CONFIG_USE_LWIP
/* This is a workaround for the case where PacketBuffer payload is not
allocated as an inline buffer to PacketBuffer structure */
origMsg = msgBuf;
msgBuf = PacketBuffer::NewWithAvailableSize(len);
msgBuf->SetDataLength(len, msgBuf);
#endif
plainText = msgBuf->Start();
// TODO: We need length checks here! https://github.com/project-chip/connectedhomeip/issues/2928
err = mac.Decode(packetHeader, &data[packetHeader.GetPayloadLength()], kMaxTagLen, &taglen);
SuccessOrExit(err);
len = static_cast<uint16_t>(len - taglen);
msgBuf->SetDataLength(len);
err = mSecureSession.Decrypt(data, len, plainText, packetHeader, payloadHeader.GetEncodePacketFlags(), mac);
SuccessOrExit(err);
err = payloadHeader.Decode(packetHeader.GetFlags(), plainText, headerSize, &decodedSize);
SuccessOrExit(err);
VerifyOrExit(headerSize == decodedSize, err = CHIP_ERROR_INCORRECT_STATE);
msgBuf->ConsumeHead(headerSize);
if (payloadHeader.GetProtocolID() == Protocols::kChipProtocol_NetworkProvisioning &&
payloadHeader.GetMessageType() == NetworkProvisioningMsgTypes::kIPAddressAssigned)
{
if (!IPAddress::FromString(Uint8::to_const_char(msgBuf->Start()), msgBuf->DataLength(), mDeviceAddress))
{
mDelegate->OnRendezvousStatusUpdate(RendezvousSessionDelegate::NetworkProvisioningFailed);
ExitNow(err = CHIP_ERROR_INVALID_ADDRESS);
}
mDelegate->OnRendezvousStatusUpdate(RendezvousSessionDelegate::NetworkProvisioningSuccess);
}
// else .. TBD once application dependency on this message has been removed, enable the else condition
{
mDelegate->OnRendezvousMessageReceived(msgBuf);
}
msgBuf = nullptr;
exit:
if (origMsg != nullptr)
{
PacketBuffer::Free(origMsg);
}
return err;
}
CHIP_ERROR RendezvousSession::WaitForPairing(Optional<NodeId> nodeId, uint32_t setupPINCode)
{
mPairingInProgress = true;
return mPairingSession.WaitForPairing(setupPINCode, kSpake2p_Iteration_Count, (const unsigned char *) kSpake2pKeyExchangeSalt,
strlen(kSpake2pKeyExchangeSalt), nodeId, 0, this);
}
CHIP_ERROR RendezvousSession::Pair(Optional<NodeId> nodeId, uint32_t setupPINCode)
{
mPairingInProgress = true;
return mPairingSession.Pair(setupPINCode, kSpake2p_Iteration_Count, (const unsigned char *) kSpake2pKeyExchangeSalt,
strlen(kSpake2pKeyExchangeSalt), nodeId, mNextKeyId++, this);
}
void RendezvousSession::SendIPAddress(IPAddress & addr)
{
CHIP_ERROR err = CHIP_NO_ERROR;
System::PacketBuffer * buffer = System::PacketBuffer::New();
char * addrStr = addr.ToString(Uint8::to_char(buffer->Start()), buffer->AvailableDataLength());
VerifyOrExit(addrStr != nullptr, err = CHIP_ERROR_INVALID_ADDRESS);
VerifyOrExit(mPairingInProgress == false, err = CHIP_ERROR_INCORRECT_STATE);
buffer->SetDataLength(strlen(addrStr) + 1);
err = SendSecureMessage(Protocols::kChipProtocol_NetworkProvisioning, NetworkProvisioningMsgTypes::kIPAddressAssigned, buffer);
SuccessOrExit(err);
exit:
if (CHIP_NO_ERROR != err)
{
OnRendezvousError(err);
PacketBuffer::Free(buffer);
}
}
#if CONFIG_DEVICE_LAYER
void RendezvousSession::ConnectivityHandler(const DeviceLayer::ChipDeviceEvent * event, intptr_t arg)
{
RendezvousSession * session = reinterpret_cast<RendezvousSession *>(arg);
VerifyOrExit(session != nullptr, /**/);
VerifyOrExit(event->Type == DeviceLayer::DeviceEventType::kInternetConnectivityChange, /**/);
VerifyOrExit(event->InternetConnectivityChange.IPv4 == DeviceLayer::kConnectivity_Established, /**/);
IPAddress addr;
IPAddress::FromString(event->InternetConnectivityChange.address, addr);
session->SendIPAddress(addr);
exit:
return;
}
#endif
} // namespace chip
<|endoftext|> |
<commit_before>/*
Copyright (c) 2016 Bastien Durix
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.
*/
/**
* \brief Provides tests for skeleton library
* \author Bastien Durix
*/
#include <iostream>
#include <math.h>
#include <cstdlib>
#include <skeleton/GraphCurveSkeleton.h>
#include <skeleton/model/Classic.h>
#include <mathtools/geometry/euclidian/HyperSphere.h>
using namespace mathtools::affine;
using namespace mathtools::geometry::euclidian;
int main()
{
unsigned int return_value = 0;
// frame creation
Frame<2>::Ptr frame = Frame<2>::CreateFrame(Eigen::Vector2d(1.0,0.0),Eigen::Vector2d(2.0,1.0),Eigen::Vector2d(1.0,0.0));
// model creation
skeleton::model::Classic<2>::Ptr modclass(new skeleton::model::Classic<2>{frame});
// creating a random node
Eigen::Vector3d vec3((double)(rand()%201)/10.0-1.0,
(double)(rand()%201)/10.0-1.0,
(double)(rand()%201)/10.0);
// skeleton creation
skeleton::GraphCurveSkeleton<skeleton::model::Classic<2> > skel(modclass);
std::cout << "Adding Node test... ";
// adding a node
unsigned int ind = skel.addNode(vec3);
// getting the node (vector form)
Eigen::Vector3d vec3_2 = skel.getNode(ind);
if(vec3_2.isApprox(vec3,std::numeric_limits<double>::epsilon()))
{
std::cout << "Success!" << std::endl;
}
else
{
return_value = -1;
std::cout << "Fail!" << std::endl;
}
std::cout << "Getter test... ";
// getting the node (center form)
Point<2> pt = skel.getNode<Point<2> >(ind);
if(pt.getCoords().isApprox(frame->getBasis()->getMatrix()*vec3.block<2,1>(0,0)+frame->getOrigin()))
{
std::cout << "Success!" << std::endl;
}
else
{
return_value = -1;
std::cout << "Fail!" << std::endl;
}
// hypersphere creation
HyperSphere<2> sph(Point<2>(1.0,0.0),5.0,frame);
std::cout << "Adding Sphere test... ";
// adding a node
unsigned int ind2 = skel.addNode<HyperSphere<2> >(sph);
// get the vector associated to the node
Eigen::Vector3d vecsph = skel.getNode(ind2);
// convert the node to a sphere
HyperSphere<2> sphcpy = skel.getModel()->toObj<HyperSphere<2> >(vecsph);
if(sphcpy.getCenter().getCoords().isApprox(sph.getCenter().getCoords(),std::numeric_limits<double>::epsilon() &&
sphcpy.getRadius() == sph.getRadius() &&
sphcpy.getFrame()->getBasis()->getMatrix().isApprox(sph.getFrame()->getBasis()->getMatrix(),std::numeric_limits<double>::epsilon())) &&
ind != ind2)
{
std::cout << "Success!" << std::endl;
}
else
{
return_value = -1;
std::cout << "Fail!" << std::endl;
}
// get all indices
std::list<unsigned int> listnod;
std::cout << "Get all nodes... ";
skel.getAllNodes(listnod);
listnod.unique();
if(listnod.size() == 2 &&
std::find(listnod.begin(),listnod.end(),ind) != listnod.end() &&
std::find(listnod.begin(),listnod.end(),ind2) != listnod.end())
{
std::cout << "Success!" << std::endl;
}
else
{
return_value = -1;
std::cout << "Fail!" << std::endl;
}
return return_value;
}
<commit_msg>Added test to neighbor access in skeleton<commit_after>/*
Copyright (c) 2016 Bastien Durix
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.
*/
/**
* \brief Provides tests for skeleton library
* \author Bastien Durix
*/
#include <iostream>
#include <math.h>
#include <cstdlib>
#include <skeleton/GraphCurveSkeleton.h>
#include <skeleton/model/Classic.h>
#include <mathtools/geometry/euclidian/HyperSphere.h>
using namespace mathtools::affine;
using namespace mathtools::geometry::euclidian;
int main()
{
unsigned int return_value = 0;
// frame creation
Frame<2>::Ptr frame = Frame<2>::CreateFrame(Eigen::Vector2d(1.0,0.0),Eigen::Vector2d(2.0,1.0),Eigen::Vector2d(1.0,0.0));
// model creation
skeleton::model::Classic<2>::Ptr modclass(new skeleton::model::Classic<2>{frame});
// creating a random node
Eigen::Vector3d vec3((double)(rand()%201)/10.0-1.0,
(double)(rand()%201)/10.0-1.0,
(double)(rand()%201)/10.0);
// skeleton creation
skeleton::GraphCurveSkeleton<skeleton::model::Classic<2> > skel(modclass);
std::cout << "Adding Node test... ";
// adding a node
unsigned int ind = skel.addNode(vec3);
// getting the node (vector form)
Eigen::Vector3d vec3_2 = skel.getNode(ind);
if(vec3_2.isApprox(vec3,std::numeric_limits<double>::epsilon()))
{
std::cout << "Success!" << std::endl;
}
else
{
return_value = -1;
std::cout << "Fail!" << std::endl;
}
std::cout << "Getter test... ";
// getting the node (center form)
Point<2> pt = skel.getNode<Point<2> >(ind);
if(pt.getCoords().isApprox(frame->getBasis()->getMatrix()*vec3.block<2,1>(0,0)+frame->getOrigin()))
{
std::cout << "Success!" << std::endl;
}
else
{
return_value = -1;
std::cout << "Fail!" << std::endl;
}
// hypersphere creation
HyperSphere<2> sph(Point<2>(1.0,0.0),5.0,frame);
std::cout << "Adding Sphere test... ";
// adding a node
unsigned int ind2 = skel.addNode<HyperSphere<2> >(sph);
// get the vector associated to the node
Eigen::Vector3d vecsph = skel.getNode(ind2);
// convert the node to a sphere
HyperSphere<2> sphcpy = skel.getModel()->toObj<HyperSphere<2> >(vecsph);
if(sphcpy.getCenter().getCoords().isApprox(sph.getCenter().getCoords(),std::numeric_limits<double>::epsilon() &&
sphcpy.getRadius() == sph.getRadius() &&
sphcpy.getFrame()->getBasis()->getMatrix().isApprox(sph.getFrame()->getBasis()->getMatrix(),std::numeric_limits<double>::epsilon())) &&
ind != ind2)
{
std::cout << "Success!" << std::endl;
}
else
{
return_value = -1;
std::cout << "Fail!" << std::endl;
}
// get all indices
std::list<unsigned int> listnod;
std::cout << "Get all nodes... ";
skel.getAllNodes(listnod);
listnod.unique();
if(listnod.size() == 2 &&
std::find(listnod.begin(),listnod.end(),ind) != listnod.end() &&
std::find(listnod.begin(),listnod.end(),ind2) != listnod.end())
{
std::cout << "Success!" << std::endl;
}
else
{
return_value = -1;
std::cout << "Fail!" << std::endl;
}
std::cout << "Adding edge test... ";
// adding an edge
skel.addEdge(ind, ind2);
std::list<unsigned int> neigh;
skel.getNeighbors(ind,neigh);
if(neigh.size() == 1 && *(neigh.begin()) == ind2)
{
std::cout << "Success!" << std::endl;
}
else
{
return_value = -1;
std::cout << "Fail!" << std::endl;
}
std::cout << "Removing edge test... ";
// removing an edge
skel.remEdge(ind, ind2);
neigh.erase(neigh.begin(),neigh.end());
skel.getNeighbors(ind,neigh);
if(neigh.size() == 0)
{
std::cout << "Success!" << std::endl;
}
else
{
return_value = -1;
std::cout << "Fail!" << std::endl;
}
return return_value;
}
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/usr/diag/attn/runtime/attn_rt.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2014,2016 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
#include "runtime/attnsvc.H"
#include "common/attntrace.H"
#include "common/attnmem.H"
#include <runtime/interface.h>
#include <runtime/rt_targeting.H>
#include <targeting/common/target.H>
#include <targeting/common/targetservice.H>
#include <targeting/common/utilFilter.H>
#include <errl/errlentry.H>
#include <errl/errlmanager.H>
#include <errno.h>
using namespace std;
using namespace TARGETING;
using namespace ATTN;
using namespace PRDF;
namespace ATTN_RT
{
/** Enable chip attentions
*
* @return 0 on success else return code
*/
int enableAttns(void)
{
ATTN_SLOW(ENTER_MRK"ATTN_RT::enableAttns");
int rc = 0;
errlHndl_t err = NULL;
err = Singleton<Service>::instance().enableAttns();
if(err)
{
errlCommit(err, ATTN_COMP_ID);
rc = -1;
}
ATTN_SLOW(EXIT_MRK"ATTN_RT::enableAttns rc: %d", rc);
return rc;
}
/** Disable chip attentions
*
* @return 0 on success else return code
*/
int disableAttns(void)
{
ATTN_SLOW(ENTER_MRK"ATTN_RT::disableAttns");
int rc = 0;
errlHndl_t err = NULL;
err = Singleton<Service>::instance().disableAttns();
if(err)
{
errlCommit(err, ATTN_COMP_ID);
rc = -1;
}
ATTN_SLOW(EXIT_MRK"ATTN_RT::disableAttns rc: %d", rc);
return rc;
}
/** brief handle chip attentions
*
* @param[in] i_proc - processor chip id at attention
* XSCOM chip id based on devtree defn
* @param[in] i_ipollStatus - processor chip Ipoll status
* @param[in] i_ipollMask - processor chip Ipoll mask
* @return 0 on success else return code
*/
int handleAttns(uint64_t i_proc,
uint64_t i_ipollStatus,
uint64_t i_ipollMask)
{
ATTN_SLOW(ENTER_MRK"ATTN_RT::handleAttns RtProc: %llx"
", ipollMask: %llx, ipollStatus: %llx",
i_proc, i_ipollMask, i_ipollStatus);
int rc = 0;
errlHndl_t err = NULL;
AttentionList attentions;
MemOps & memOps = getMemOps();
do
{
// Convert chipIds to HB targets
TargetHandle_t proc = NULL;
err = RT_TARG::getHbTarget(i_proc, proc);
if(err)
{
ATTN_ERR("ATTN_RT::handleAttns getHbTarget "
"returned error for RtProc: %llx", i_proc);
rc = EINVAL;
break;
}
err = Singleton<Service>::instance().handleAttentions(proc);
if(err)
{
ATTN_ERR("ATTN_RT::handleAttns service::handleAttentions "
"returned error for RtProc: %llx", i_proc);
break;
}
// On P8,
// For host attentions, clear gpio interrupt type register.
// If we do not clear gpio register, ipoll status will again
// get set and we will end up in infinite loop.
// For P9,
// Host attentions should be coming thru the
// normal (IPOLL) Error status reg. Hence, we shouldn't
// have to play with the IPR (interrupt presentation register)
// which was involved with the gpio/gpin register where
// centaur routed its attentions.
} while(0);
if(err)
{
errlCommit( err, ATTN_COMP_ID );
if(0 == rc)
{
rc = -1;
}
}
attentions.clear();
ATTN_SLOW(EXIT_MRK"ATTN_RT::handleAttns rc: %d", rc);
return rc;
}
// register runtimeInterfaces
struct registerAttn
{
registerAttn()
{
runtimeInterfaces_t * rt_intf = getRuntimeInterfaces();
if (NULL == rt_intf)
{
return;
}
rt_intf->enable_attns = &enableAttns;
rt_intf->disable_attns = &disableAttns;
rt_intf->handle_attns = &handleAttns;
}
};
registerAttn g_registerAttn;
}
<commit_msg>Remove unused variable in attn_rt.C<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/usr/diag/attn/runtime/attn_rt.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2014,2016 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
#include "runtime/attnsvc.H"
#include "common/attntrace.H"
#include "common/attnmem.H"
#include <runtime/interface.h>
#include <runtime/rt_targeting.H>
#include <targeting/common/target.H>
#include <targeting/common/targetservice.H>
#include <targeting/common/utilFilter.H>
#include <errl/errlentry.H>
#include <errl/errlmanager.H>
#include <errno.h>
using namespace std;
using namespace TARGETING;
using namespace ATTN;
using namespace PRDF;
namespace ATTN_RT
{
/** Enable chip attentions
*
* @return 0 on success else return code
*/
int enableAttns(void)
{
ATTN_SLOW(ENTER_MRK"ATTN_RT::enableAttns");
int rc = 0;
errlHndl_t err = NULL;
err = Singleton<Service>::instance().enableAttns();
if(err)
{
errlCommit(err, ATTN_COMP_ID);
rc = -1;
}
ATTN_SLOW(EXIT_MRK"ATTN_RT::enableAttns rc: %d", rc);
return rc;
}
/** Disable chip attentions
*
* @return 0 on success else return code
*/
int disableAttns(void)
{
ATTN_SLOW(ENTER_MRK"ATTN_RT::disableAttns");
int rc = 0;
errlHndl_t err = NULL;
err = Singleton<Service>::instance().disableAttns();
if(err)
{
errlCommit(err, ATTN_COMP_ID);
rc = -1;
}
ATTN_SLOW(EXIT_MRK"ATTN_RT::disableAttns rc: %d", rc);
return rc;
}
/** brief handle chip attentions
*
* @param[in] i_proc - processor chip id at attention
* XSCOM chip id based on devtree defn
* @param[in] i_ipollStatus - processor chip Ipoll status
* @param[in] i_ipollMask - processor chip Ipoll mask
* @return 0 on success else return code
*/
int handleAttns(uint64_t i_proc,
uint64_t i_ipollStatus,
uint64_t i_ipollMask)
{
ATTN_SLOW(ENTER_MRK"ATTN_RT::handleAttns RtProc: %llx"
", ipollMask: %llx, ipollStatus: %llx",
i_proc, i_ipollMask, i_ipollStatus);
int rc = 0;
errlHndl_t err = NULL;
AttentionList attentions;
do
{
// Convert chipIds to HB targets
TargetHandle_t proc = NULL;
err = RT_TARG::getHbTarget(i_proc, proc);
if(err)
{
ATTN_ERR("ATTN_RT::handleAttns getHbTarget "
"returned error for RtProc: %llx", i_proc);
rc = EINVAL;
break;
}
err = Singleton<Service>::instance().handleAttentions(proc);
if(err)
{
ATTN_ERR("ATTN_RT::handleAttns service::handleAttentions "
"returned error for RtProc: %llx", i_proc);
break;
}
// On P8,
// For host attentions, clear gpio interrupt type register.
// If we do not clear gpio register, ipoll status will again
// get set and we will end up in infinite loop.
// For P9,
// Host attentions should be coming thru the
// normal (IPOLL) Error status reg. Hence, we shouldn't
// have to play with the IPR (interrupt presentation register)
// which was involved with the gpio/gpin register where
// centaur routed its attentions.
} while(0);
if(err)
{
errlCommit( err, ATTN_COMP_ID );
if(0 == rc)
{
rc = -1;
}
}
attentions.clear();
ATTN_SLOW(EXIT_MRK"ATTN_RT::handleAttns rc: %d", rc);
return rc;
}
// register runtimeInterfaces
struct registerAttn
{
registerAttn()
{
runtimeInterfaces_t * rt_intf = getRuntimeInterfaces();
if (NULL == rt_intf)
{
return;
}
rt_intf->enable_attns = &enableAttns;
rt_intf->disable_attns = &disableAttns;
rt_intf->handle_attns = &handleAttns;
}
};
registerAttn g_registerAttn;
}
<|endoftext|> |
<commit_before>/*
* httpfileupload.cpp - HTTP File upload
* Copyright (C) 2017-2019 Aleksey Andreev, Sergey Ilinykh
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#include <QList>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QRegExp>
#include "httpfileupload.h"
#include "xmpp_tasks.h"
#include "xmpp_xmlcommon.h"
#include "xmpp_serverinfomanager.h"
using namespace XMPP;
static QLatin1String xmlns_v0_2_5("urn:xmpp:http:upload");
static QLatin1String xmlns_v0_3_1("urn:xmpp:http:upload:0");
//----------------------------------------------------------------------------
// HttpFileUpload
//----------------------------------------------------------------------------
class HttpFileUpload::Private
{
public:
HttpFileUpload::State state = State::None;
XMPP::Client *client = nullptr;
QIODevice *sourceDevice = nullptr;
QPointer<QNetworkAccessManager> qnam = nullptr;
quint64 fileSize = 0;
QString fileName;
QString mediaType;
QList<HttpHost> httpHosts;
struct {
HttpFileUpload::ErrorCode statusCode = HttpFileUpload::ErrorCode::NoError;
QString statusString;
QString getUrl;
QString putUrl;
XEP0363::HttpHeaders putHeaders;
quint64 sizeLimit = 0;
} result;
};
HttpFileUpload::HttpFileUpload(XMPP::Client *client, QIODevice *source, size_t fsize, const QString &dstFilename,
const QString &mType) :
QObject(client),
d(new Private)
{
d->client = client;
d->sourceDevice = source;
d->fileName = dstFilename;
d->fileSize = fsize;
d->mediaType = mType;
}
HttpFileUpload::~HttpFileUpload()
{
qDebug("destroying");
}
void HttpFileUpload::setNetworkAccessManager(QNetworkAccessManager *qnam)
{
d->qnam = qnam;
}
void HttpFileUpload::start()
{
if (d->state != State::None) // Attempt to start twice?
return;
setState(State::GettingSlot);
d->result.statusCode = HttpFileUpload::ErrorCode::NoError;
static QList<QSet<QString>> featureOptions;
if (featureOptions.isEmpty()) {
featureOptions << (QSet<QString>() << xmlns_v0_2_5) << (QSet<QString>() << xmlns_v0_3_1);
}
d->client->serverInfoManager()->queryServiceInfo(
QLatin1String("store"), QLatin1String("file"),
featureOptions, QRegExp("^(upload|http|stor|file|dis|drive).*"), ServerInfoManager::SQ_CheckAllOnNoMatch,
[this](const QList<DiscoItem> &items)
{
d->httpHosts.clear();
for (const auto &item: items) {
const QStringList &l = item.features().list();
XEP0363::version ver = XEP0363::vUnknown;
QString xmlns;
quint64 sizeLimit = 0;
if (l.contains(xmlns_v0_3_1)) {
ver = XEP0363::v0_3_1;
xmlns = xmlns_v0_3_1;
} else if (l.contains(xmlns_v0_2_5)) {
ver = XEP0363::v0_2_5;
xmlns = xmlns_v0_2_5;
}
if (ver != XEP0363::vUnknown) {
QList<std::pair<HttpHost,int>> hosts;
const XData::Field field = item.registeredExtension(xmlns).getField(QLatin1String("max-file-size"));
if (field.isValid() && field.type() == XData::Field::Field_TextSingle)
sizeLimit = field.value().at(0).toULongLong();
HttpHost host;
host.ver = ver;
host.jid = item.jid();
host.sizeLimit = sizeLimit;
QVariant metaProps(d->client->serverInfoManager()->serviceMeta(host.jid, "httpprops"));
if (metaProps.isValid()) {
host.props = HostProps(metaProps.value<int>());
} else {
host.props = SecureGet | SecurePut;
if (ver == XEP0363::v0_3_1)
host.props |= NewestVer;
}
int value = 0;
if (host.props & SecureGet) value += 5;
if (host.props & SecurePut) value += 5;
if (host.props & NewestVer) value += 3;
if (host.props & Failure) value -= 15;
if (!sizeLimit || d->fileSize < sizeLimit)
hosts.append({host,value});
// no sorting in preference order. most preferred go first
std::sort(hosts.begin(), hosts.end(), [](const auto &a, const auto &b){
return a.second > b.second;
});
for (auto &hp: hosts) {
d->httpHosts.append(hp.first);
}
}
}
//d->currentHost = d->httpHosts.begin();
if (d->httpHosts.isEmpty()) { // if empty as the last resort check all services
d->result.statusCode = HttpFileUpload::ErrorCode::NoUploadService;
d->result.statusString = "No suitable http upload services were found";
done(State::Error);
} else {
tryNextServer();
}
});
}
void HttpFileUpload::tryNextServer()
{
if (d->httpHosts.isEmpty()) { // if empty as the last resort check all services
d->result.statusCode = HttpFileUpload::ErrorCode::NoUploadService;
d->result.statusString = "All http services are either non compliant or returned errors";
done(State::Error);
return;
}
HttpHost host = std::move(d->httpHosts.takeFirst());
d->result.sizeLimit = host.sizeLimit;
auto jt = new JT_HTTPFileUpload(d->client->rootTask());
connect(jt, &JT_HTTPFileUpload::finished, this, [this, jt, host]() mutable {
if (!jt->success()) {
host.props |= Failure;
int code = jt->statusCode();
if (code < 300) {
code++; // ErrDisc and ErrTimeout. but 0 code is already occupated
}
d->result.statusCode = static_cast<ErrorCode>(jt->statusCode());
d->result.statusString = jt->statusString();
d->client->serverInfoManager()->setServiceMeta(host.jid, QLatin1String("httpprops"), int(host.props));
if (d->httpHosts.isEmpty())
done(State::Error);
else
tryNextServer();
return;
}
d->result.getUrl = jt->url(JT_HTTPFileUpload::GetUrl);
d->result.putUrl = jt->url(JT_HTTPFileUpload::PutUrl);
d->result.putHeaders = jt->headers();
if (d->result.getUrl.startsWith("https://"))
host.props |= SecureGet;
else
host.props &= ~SecureGet;
if (d->result.putUrl.startsWith("https://"))
host.props |= SecurePut;
else
host.props &= ~SecurePut;
host.props &= ~Failure;
d->client->serverInfoManager()->setServiceMeta(host.jid, QLatin1String("httpprops"), int(host.props));
if (!d->qnam) { // w/o network access manager, it's not more than getting slots
done(State::Success);
return;
}
setState(State::HttpRequest);
// time for a http request
QNetworkRequest req(d->result.putUrl);
for (auto &h: d->result.putHeaders) {
req.setRawHeader(h.name.toLatin1(), h.value.toLatin1());
}
auto reply = d->qnam->put(req, d->sourceDevice);
connect(reply, &QNetworkReply::finished, this, [this, reply](){
if (reply->error() == QNetworkReply::NoError) {
done(State::Success);
} else {
d->result.statusCode = ErrorCode::HttpFailed;
d->result.statusString = reply->errorString();
if (d->httpHosts.isEmpty())
done(State::Error);
else
tryNextServer();
}
reply->deleteLater();
});
}, Qt::QueuedConnection);
jt->request(host.jid, d->fileName, d->fileSize, d->mediaType, host.ver);
jt->go(true);
}
bool HttpFileUpload::success() const
{
return d->state == State::Success;
}
HttpFileUpload::ErrorCode HttpFileUpload::statusCode() const
{
return d->result.statusCode;
}
const QString & HttpFileUpload::statusString() const
{
return d->result.statusString;
}
HttpFileUpload::HttpSlot HttpFileUpload::getHttpSlot()
{
HttpSlot slot;
if (d->state == State::Success) {
slot.get.url = d->result.getUrl;
slot.put.url = d->result.putUrl;
slot.put.headers = d->result.putHeaders;
slot.limits.fileSize = d->result.sizeLimit;
}
return slot;
}
void HttpFileUpload::setState(State state)
{
d->state = state;
if (state == Success) {
d->result.statusCode = ErrorCode::NoError;
d->result.statusString.clear();
}
emit stateChanged();
}
void HttpFileUpload::done(State state)
{
setState(state);
emit finished();
}
//----------------------------------------------------------------------------
// JT_HTTPFileUpload
//----------------------------------------------------------------------------
class JT_HTTPFileUpload::Private
{
public:
Jid to;
QDomElement iq;
QStringList urls;
XEP0363::version ver;
XEP0363::HttpHeaders headers;
};
JT_HTTPFileUpload::JT_HTTPFileUpload(Task *parent)
: Task(parent)
{
d = new Private;
d->ver = XEP0363::vUnknown;
d->urls << QString() << QString();
}
JT_HTTPFileUpload::~JT_HTTPFileUpload()
{
delete d;
}
void JT_HTTPFileUpload::request(const Jid &to, const QString &fname,
quint64 fsize, const QString &ftype, XEP0363::version ver)
{
d->to = to;
d->ver = ver;
d->iq = createIQ(doc(), "get", to.full(), id());
QDomElement req = doc()->createElement("request");
switch (ver)
{
case XEP0363::v0_2_5:
req.setAttribute("xmlns", xmlns_v0_2_5);
req.appendChild(textTag(doc(), "filename", fname));
req.appendChild(textTag(doc(), "size", QString::number(fsize)));
if (!ftype.isEmpty()) {
req.appendChild(textTag(doc(), "content-type", ftype));
}
break;
case XEP0363::v0_3_1:
req.setAttribute("xmlns", xmlns_v0_3_1);
req.setAttribute("filename", fname);
req.setAttribute("size", fsize);
if (!ftype.isEmpty())
req.setAttribute("content-type", ftype);
break;
default:
d->ver = XEP0363::vUnknown;
break;
}
d->iq.appendChild(req);
}
QString JT_HTTPFileUpload::url(UrlType t) const
{
return d->urls.value(t);
}
XEP0363::HttpHeaders JT_HTTPFileUpload::headers() const
{
return d->headers;
}
void JT_HTTPFileUpload::onGo()
{
if (d->ver != XEP0363::vUnknown)
send(d->iq);
}
bool JT_HTTPFileUpload::take(const QDomElement &e)
{
if (!iqVerify(e, d->to, id()))
return false;
if (e.attribute("type") != "result") {
setError(e);
return true;
}
bool correct_xmlns = false;
QString getUrl, putUrl;
XEP0363::HttpHeaders headers;
const QDomElement &slot = e.firstChildElement("slot");
if (!slot.isNull()) {
const QDomElement &get = slot.firstChildElement("get");
const QDomElement &put = slot.firstChildElement("put");
switch (d->ver)
{
case XEP0363::v0_2_5:
correct_xmlns = slot.attribute("xmlns") == xmlns_v0_2_5;
getUrl = tagContent(get);
putUrl = tagContent(put);
break;
case XEP0363::v0_3_1:
correct_xmlns = slot.attribute("xmlns") == xmlns_v0_3_1;
getUrl = get.attribute("url");
if (!put.isNull()) {
putUrl = put.attribute("url");
QDomElement he = put.firstChildElement("header");
while (!he.isNull()) {
// only next are allowed: Authorization, Cookie, Expires
QString header = he.attribute("name").trimmed().remove(QLatin1Char('\n'));
QString value = he.text().trimmed().remove(QLatin1Char('\n'));
if (!value.isEmpty() &&
(header.compare(QLatin1String("Authorization"), Qt::CaseInsensitive) == 0 ||
header.compare(QLatin1String("Cookie"), Qt::CaseInsensitive) == 0 ||
header.compare(QLatin1String("Expires"), Qt::CaseInsensitive) == 0))
{
headers.append(XEP0363::HttpHeader{header, value});
}
he = he.nextSiblingElement("header");
}
}
break;
default:
break;
}
}
if (!correct_xmlns) {
setError(ErrInvalidResponse);
return true;
}
if (!getUrl.isEmpty() && !putUrl.isEmpty()) {
d->urls[GetUrl] = getUrl;
d->urls[PutUrl] = putUrl;
d->headers = headers;
setSuccess();
}
else
setError(ErrInvalidResponse, "Either `put` or `get` URL is missing in the server's reply.");
return true;
}
class HttpFileUploadManager::Private {
public:
Client *client = nullptr;
QPointer<QNetworkAccessManager> qnam;
QLinkedList<HttpFileUpload::HttpHost> hosts;
};
HttpFileUploadManager::HttpFileUploadManager(Client *parent) :
QObject(parent),
d(new Private)
{
d->client = parent;
}
void HttpFileUploadManager::setNetworkAccessManager(QNetworkAccessManager *qnam)
{
d->qnam = qnam;
}
HttpFileUpload* HttpFileUploadManager::upload(const QString &srcFilename, const QString &dstFilename, const QString &mType)
{
auto f = new QFile(srcFilename);
f->open(QIODevice::ReadOnly);
auto hfu = upload(f, f->size(), dstFilename, mType);
f->setParent(hfu);
return hfu;
}
HttpFileUpload* HttpFileUploadManager::upload(QIODevice *source, size_t fsize, const QString &dstFilename, const QString &mType)
{
auto hfu = new HttpFileUpload(d->client, source, fsize, dstFilename, mType);
hfu->setNetworkAccessManager(d->qnam);
QMetaObject::invokeMethod(hfu, "start", Qt::QueuedConnection);
return hfu;
}
<commit_msg>Fix clang warning:<commit_after>/*
* httpfileupload.cpp - HTTP File upload
* Copyright (C) 2017-2019 Aleksey Andreev, Sergey Ilinykh
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#include <QList>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QRegExp>
#include "httpfileupload.h"
#include "xmpp_tasks.h"
#include "xmpp_xmlcommon.h"
#include "xmpp_serverinfomanager.h"
using namespace XMPP;
static QLatin1String xmlns_v0_2_5("urn:xmpp:http:upload");
static QLatin1String xmlns_v0_3_1("urn:xmpp:http:upload:0");
//----------------------------------------------------------------------------
// HttpFileUpload
//----------------------------------------------------------------------------
class HttpFileUpload::Private
{
public:
HttpFileUpload::State state = State::None;
XMPP::Client *client = nullptr;
QIODevice *sourceDevice = nullptr;
QPointer<QNetworkAccessManager> qnam = nullptr;
quint64 fileSize = 0;
QString fileName;
QString mediaType;
QList<HttpHost> httpHosts;
struct {
HttpFileUpload::ErrorCode statusCode = HttpFileUpload::ErrorCode::NoError;
QString statusString;
QString getUrl;
QString putUrl;
XEP0363::HttpHeaders putHeaders;
quint64 sizeLimit = 0;
} result;
};
HttpFileUpload::HttpFileUpload(XMPP::Client *client, QIODevice *source, size_t fsize, const QString &dstFilename,
const QString &mType) :
QObject(client),
d(new Private)
{
d->client = client;
d->sourceDevice = source;
d->fileName = dstFilename;
d->fileSize = fsize;
d->mediaType = mType;
}
HttpFileUpload::~HttpFileUpload()
{
qDebug("destroying");
}
void HttpFileUpload::setNetworkAccessManager(QNetworkAccessManager *qnam)
{
d->qnam = qnam;
}
void HttpFileUpload::start()
{
if (d->state != State::None) // Attempt to start twice?
return;
setState(State::GettingSlot);
d->result.statusCode = HttpFileUpload::ErrorCode::NoError;
static QList<QSet<QString>> featureOptions;
if (featureOptions.isEmpty()) {
featureOptions << (QSet<QString>() << xmlns_v0_2_5) << (QSet<QString>() << xmlns_v0_3_1);
}
d->client->serverInfoManager()->queryServiceInfo(
QLatin1String("store"), QLatin1String("file"),
featureOptions, QRegExp("^(upload|http|stor|file|dis|drive).*"), ServerInfoManager::SQ_CheckAllOnNoMatch,
[this](const QList<DiscoItem> &items)
{
d->httpHosts.clear();
for (const auto &item: items) {
const QStringList &l = item.features().list();
XEP0363::version ver = XEP0363::vUnknown;
QString xmlns;
quint64 sizeLimit = 0;
if (l.contains(xmlns_v0_3_1)) {
ver = XEP0363::v0_3_1;
xmlns = xmlns_v0_3_1;
} else if (l.contains(xmlns_v0_2_5)) {
ver = XEP0363::v0_2_5;
xmlns = xmlns_v0_2_5;
}
if (ver != XEP0363::vUnknown) {
QList<std::pair<HttpHost,int>> hosts;
const XData::Field field = item.registeredExtension(xmlns).getField(QLatin1String("max-file-size"));
if (field.isValid() && field.type() == XData::Field::Field_TextSingle)
sizeLimit = field.value().at(0).toULongLong();
HttpHost host;
host.ver = ver;
host.jid = item.jid();
host.sizeLimit = sizeLimit;
QVariant metaProps(d->client->serverInfoManager()->serviceMeta(host.jid, "httpprops"));
if (metaProps.isValid()) {
host.props = HostProps(metaProps.value<int>());
} else {
host.props = SecureGet | SecurePut;
if (ver == XEP0363::v0_3_1)
host.props |= NewestVer;
}
int value = 0;
if (host.props & SecureGet) value += 5;
if (host.props & SecurePut) value += 5;
if (host.props & NewestVer) value += 3;
if (host.props & Failure) value -= 15;
if (!sizeLimit || d->fileSize < sizeLimit)
hosts.append({host,value});
// no sorting in preference order. most preferred go first
std::sort(hosts.begin(), hosts.end(), [](const auto &a, const auto &b){
return a.second > b.second;
});
for (auto &hp: hosts) {
d->httpHosts.append(hp.first);
}
}
}
//d->currentHost = d->httpHosts.begin();
if (d->httpHosts.isEmpty()) { // if empty as the last resort check all services
d->result.statusCode = HttpFileUpload::ErrorCode::NoUploadService;
d->result.statusString = "No suitable http upload services were found";
done(State::Error);
} else {
tryNextServer();
}
});
}
void HttpFileUpload::tryNextServer()
{
if (d->httpHosts.isEmpty()) { // if empty as the last resort check all services
d->result.statusCode = HttpFileUpload::ErrorCode::NoUploadService;
d->result.statusString = "All http services are either non compliant or returned errors";
done(State::Error);
return;
}
HttpHost host = d->httpHosts.takeFirst();
d->result.sizeLimit = host.sizeLimit;
auto jt = new JT_HTTPFileUpload(d->client->rootTask());
connect(jt, &JT_HTTPFileUpload::finished, this, [this, jt, host]() mutable {
if (!jt->success()) {
host.props |= Failure;
int code = jt->statusCode();
if (code < 300) {
code++; // ErrDisc and ErrTimeout. but 0 code is already occupated
}
d->result.statusCode = static_cast<ErrorCode>(jt->statusCode());
d->result.statusString = jt->statusString();
d->client->serverInfoManager()->setServiceMeta(host.jid, QLatin1String("httpprops"), int(host.props));
if (d->httpHosts.isEmpty())
done(State::Error);
else
tryNextServer();
return;
}
d->result.getUrl = jt->url(JT_HTTPFileUpload::GetUrl);
d->result.putUrl = jt->url(JT_HTTPFileUpload::PutUrl);
d->result.putHeaders = jt->headers();
if (d->result.getUrl.startsWith("https://"))
host.props |= SecureGet;
else
host.props &= ~SecureGet;
if (d->result.putUrl.startsWith("https://"))
host.props |= SecurePut;
else
host.props &= ~SecurePut;
host.props &= ~Failure;
d->client->serverInfoManager()->setServiceMeta(host.jid, QLatin1String("httpprops"), int(host.props));
if (!d->qnam) { // w/o network access manager, it's not more than getting slots
done(State::Success);
return;
}
setState(State::HttpRequest);
// time for a http request
QNetworkRequest req(d->result.putUrl);
for (auto &h: d->result.putHeaders) {
req.setRawHeader(h.name.toLatin1(), h.value.toLatin1());
}
auto reply = d->qnam->put(req, d->sourceDevice);
connect(reply, &QNetworkReply::finished, this, [this, reply](){
if (reply->error() == QNetworkReply::NoError) {
done(State::Success);
} else {
d->result.statusCode = ErrorCode::HttpFailed;
d->result.statusString = reply->errorString();
if (d->httpHosts.isEmpty())
done(State::Error);
else
tryNextServer();
}
reply->deleteLater();
});
}, Qt::QueuedConnection);
jt->request(host.jid, d->fileName, d->fileSize, d->mediaType, host.ver);
jt->go(true);
}
bool HttpFileUpload::success() const
{
return d->state == State::Success;
}
HttpFileUpload::ErrorCode HttpFileUpload::statusCode() const
{
return d->result.statusCode;
}
const QString & HttpFileUpload::statusString() const
{
return d->result.statusString;
}
HttpFileUpload::HttpSlot HttpFileUpload::getHttpSlot()
{
HttpSlot slot;
if (d->state == State::Success) {
slot.get.url = d->result.getUrl;
slot.put.url = d->result.putUrl;
slot.put.headers = d->result.putHeaders;
slot.limits.fileSize = d->result.sizeLimit;
}
return slot;
}
void HttpFileUpload::setState(State state)
{
d->state = state;
if (state == Success) {
d->result.statusCode = ErrorCode::NoError;
d->result.statusString.clear();
}
emit stateChanged();
}
void HttpFileUpload::done(State state)
{
setState(state);
emit finished();
}
//----------------------------------------------------------------------------
// JT_HTTPFileUpload
//----------------------------------------------------------------------------
class JT_HTTPFileUpload::Private
{
public:
Jid to;
QDomElement iq;
QStringList urls;
XEP0363::version ver;
XEP0363::HttpHeaders headers;
};
JT_HTTPFileUpload::JT_HTTPFileUpload(Task *parent)
: Task(parent)
{
d = new Private;
d->ver = XEP0363::vUnknown;
d->urls << QString() << QString();
}
JT_HTTPFileUpload::~JT_HTTPFileUpload()
{
delete d;
}
void JT_HTTPFileUpload::request(const Jid &to, const QString &fname,
quint64 fsize, const QString &ftype, XEP0363::version ver)
{
d->to = to;
d->ver = ver;
d->iq = createIQ(doc(), "get", to.full(), id());
QDomElement req = doc()->createElement("request");
switch (ver)
{
case XEP0363::v0_2_5:
req.setAttribute("xmlns", xmlns_v0_2_5);
req.appendChild(textTag(doc(), "filename", fname));
req.appendChild(textTag(doc(), "size", QString::number(fsize)));
if (!ftype.isEmpty()) {
req.appendChild(textTag(doc(), "content-type", ftype));
}
break;
case XEP0363::v0_3_1:
req.setAttribute("xmlns", xmlns_v0_3_1);
req.setAttribute("filename", fname);
req.setAttribute("size", fsize);
if (!ftype.isEmpty())
req.setAttribute("content-type", ftype);
break;
default:
d->ver = XEP0363::vUnknown;
break;
}
d->iq.appendChild(req);
}
QString JT_HTTPFileUpload::url(UrlType t) const
{
return d->urls.value(t);
}
XEP0363::HttpHeaders JT_HTTPFileUpload::headers() const
{
return d->headers;
}
void JT_HTTPFileUpload::onGo()
{
if (d->ver != XEP0363::vUnknown)
send(d->iq);
}
bool JT_HTTPFileUpload::take(const QDomElement &e)
{
if (!iqVerify(e, d->to, id()))
return false;
if (e.attribute("type") != "result") {
setError(e);
return true;
}
bool correct_xmlns = false;
QString getUrl, putUrl;
XEP0363::HttpHeaders headers;
const QDomElement &slot = e.firstChildElement("slot");
if (!slot.isNull()) {
const QDomElement &get = slot.firstChildElement("get");
const QDomElement &put = slot.firstChildElement("put");
switch (d->ver)
{
case XEP0363::v0_2_5:
correct_xmlns = slot.attribute("xmlns") == xmlns_v0_2_5;
getUrl = tagContent(get);
putUrl = tagContent(put);
break;
case XEP0363::v0_3_1:
correct_xmlns = slot.attribute("xmlns") == xmlns_v0_3_1;
getUrl = get.attribute("url");
if (!put.isNull()) {
putUrl = put.attribute("url");
QDomElement he = put.firstChildElement("header");
while (!he.isNull()) {
// only next are allowed: Authorization, Cookie, Expires
QString header = he.attribute("name").trimmed().remove(QLatin1Char('\n'));
QString value = he.text().trimmed().remove(QLatin1Char('\n'));
if (!value.isEmpty() &&
(header.compare(QLatin1String("Authorization"), Qt::CaseInsensitive) == 0 ||
header.compare(QLatin1String("Cookie"), Qt::CaseInsensitive) == 0 ||
header.compare(QLatin1String("Expires"), Qt::CaseInsensitive) == 0))
{
headers.append(XEP0363::HttpHeader{header, value});
}
he = he.nextSiblingElement("header");
}
}
break;
default:
break;
}
}
if (!correct_xmlns) {
setError(ErrInvalidResponse);
return true;
}
if (!getUrl.isEmpty() && !putUrl.isEmpty()) {
d->urls[GetUrl] = getUrl;
d->urls[PutUrl] = putUrl;
d->headers = headers;
setSuccess();
}
else
setError(ErrInvalidResponse, "Either `put` or `get` URL is missing in the server's reply.");
return true;
}
class HttpFileUploadManager::Private {
public:
Client *client = nullptr;
QPointer<QNetworkAccessManager> qnam;
QLinkedList<HttpFileUpload::HttpHost> hosts;
};
HttpFileUploadManager::HttpFileUploadManager(Client *parent) :
QObject(parent),
d(new Private)
{
d->client = parent;
}
void HttpFileUploadManager::setNetworkAccessManager(QNetworkAccessManager *qnam)
{
d->qnam = qnam;
}
HttpFileUpload* HttpFileUploadManager::upload(const QString &srcFilename, const QString &dstFilename, const QString &mType)
{
auto f = new QFile(srcFilename);
f->open(QIODevice::ReadOnly);
auto hfu = upload(f, f->size(), dstFilename, mType);
f->setParent(hfu);
return hfu;
}
HttpFileUpload* HttpFileUploadManager::upload(QIODevice *source, size_t fsize, const QString &dstFilename, const QString &mType)
{
auto hfu = new HttpFileUpload(d->client, source, fsize, dstFilename, mType);
hfu->setNetworkAccessManager(d->qnam);
QMetaObject::invokeMethod(hfu, "start", Qt::QueuedConnection);
return hfu;
}
<|endoftext|> |
<commit_before>#ifndef STAN_MATH_PRIM_MAT_FUN_PROMOTER_HPP
#define STAN_MATH_PRIM_MAT_FUN_PROMOTER_HPP
#include <stan/math/prim/arr/fun/promoter.hpp>
#include <stan/math/prim/mat/fun/Eigen.hpp>
namespace stan {
namespace math {
/**
* Struct which holds static function for element-wise type promotion.
* This specialization promotes Eigen matrix elements of different types.
*
* @tparam F type of input element
* @tparam T type of output element
*/
template <typename F, typename T>
struct promoter<Eigen::Matrix<F, Eigen::Dynamic, Eigen::Dynamic>,
Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> > {
inline static void promote(const Eigen::Matrix<F,
Eigen::Dynamic, Eigen::Dynamic>& u,
Eigen::Matrix<T,
Eigen::Dynamic, Eigen::Dynamic>& t) {
t.resize(u.rows(), u.cols());
for (int i = 0; i < u.size(); ++i)
promoter<F, T>::promote(u(i), t(i));
}
inline static Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>
promote_to(const Eigen::Matrix<F, Eigen::Dynamic, Eigen::Dynamic>& u) {
Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> t;
promoter<Eigen::Matrix<F, Eigen::Dynamic, Eigen::Dynamic>,
Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>
>::promote(u, t);
return t;
}
};
/**
* Struct which holds static function for element-wise type promotion.
* This specialization promotes Eigen matrix elements of same type.
*
* @tparam T type of matrix element
*/
template <typename T>
struct promoter<Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>,
Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> > {
inline static void promote(const Eigen::Matrix<T,
Eigen::Dynamic, Eigen::Dynamic>& u,
Eigen::Matrix<T,
Eigen::Dynamic, Eigen::Dynamic>& t) {
t = u;
}
inline static Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>
promote_to(const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& u) {
return u;
}
};
}
}
#endif
<commit_msg>promoter needs matrix specialization, called from promote_to<commit_after>#ifndef STAN_MATH_PRIM_MAT_FUN_PROMOTER_HPP
#define STAN_MATH_PRIM_MAT_FUN_PROMOTER_HPP
#include <stan/math/prim/arr/fun/promoter.hpp>
#include <stan/math/prim/mat/fun/Eigen.hpp>
namespace stan {
namespace math {
/**
* Struct which holds static function for element-wise type promotion.
* This specialization promotes Eigen matrix elements of different types.
*
* @tparam F type of input element
* @tparam T type of output element
* @tparam R number of rows
* @tparam C number of columns
*/
template <typename F, typename T, int R, int C>
struct promoter<Eigen::Matrix<F, R, C>,
Eigen::Matrix<T, R, C> > {
inline static void promote(const Eigen::Matrix<F,
R, C>& u,
Eigen::Matrix<T,
R, C>& t) {
t.resize(u.rows(), u.cols());
for (int i = 0; i < u.size(); ++i)
promoter<F, T>::promote(u(i), t(i));
}
inline static Eigen::Matrix<T, R, C>
promote_to(const Eigen::Matrix<F, R, C>& u) {
Eigen::Matrix<T, R, C> t;
promoter<Eigen::Matrix<F, R, C>,
Eigen::Matrix<T, R, C>
>::promote(u, t);
return t;
}
};
/**
* Struct which holds static function for element-wise type promotion.
* This specialization promotes Eigen matrix elements of same type.
*
* @tparam T type of matrix element
* @tparam R number of rows
* @tparam C number of columns
*/
template <typename T, int R, int C>
struct promoter<Eigen::Matrix<T, R, C>,
Eigen::Matrix<T, R, C> > {
inline static void promote(const Eigen::Matrix<T,
R, C>& u,
Eigen::Matrix<T,
R, C>& t) {
t = u;
}
inline static Eigen::Matrix<T, R, C>
promote_to(const Eigen::Matrix<T, R, C>& u) {
return u;
}
};
}
}
#endif
<|endoftext|> |
<commit_before>#ifndef STAN_MATH_PRIM_PROB_NORMAL_LPDF_HPP
#define STAN_MATH_PRIM_PROB_NORMAL_LPDF_HPP
#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/err.hpp>
#include <stan/math/prim/fun/as_column_vector_or_scalar.hpp>
#include <stan/math/prim/fun/as_array_or_scalar.hpp>
#include <stan/math/prim/fun/as_value_column_array_or_scalar.hpp>
#include <stan/math/prim/fun/constants.hpp>
#include <stan/math/prim/fun/log.hpp>
#include <stan/math/prim/fun/max_size.hpp>
#include <stan/math/prim/fun/size.hpp>
#include <stan/math/prim/fun/size_zero.hpp>
#include <stan/math/prim/fun/to_ref.hpp>
#include <stan/math/prim/fun/value_of.hpp>
#include <stan/math/prim/functor/operands_and_partials.hpp>
#include <cmath>
namespace stan {
namespace math {
/** \ingroup prob_dists
* The log of the normal density for the specified scalar(s) given
* the specified mean(s) and deviation(s). y, mu, or sigma can
* each be either a scalar or a vector. Any vector inputs
* must be the same length.
*
* <p>The result log probability is defined to be the sum of the
* log probabilities for each observation/mean/deviation triple.
*
* @tparam T_y type of scalar
* @tparam T_loc type of location parameter
* @tparam T_scale type of scale parameter
* @param y (Sequence of) scalar(s).
* @param mu (Sequence of) location parameter(s)
* for the normal distribution.
* @param sigma (Sequence of) scale parameters for the normal distribution.
* @return The log of the product of the densities.
* @throw std::domain_error if the scale is not positive.
*/
template <bool propto, typename T_y, typename T_loc, typename T_scale,
require_all_not_nonscalar_prim_or_rev_kernel_expression_t<
T_y, T_loc, T_scale>* = nullptr>
inline return_type_t<T_y, T_loc, T_scale> normal_lpdf(const T_y& y,
const T_loc& mu,
const T_scale& sigma) {
using T_partials_return = partials_return_t<T_y, T_loc, T_scale>;
using T_y_ref = ref_type_if_t<!is_constant<T_y>::value, T_y>;
using T_mu_ref = ref_type_if_t<!is_constant<T_loc>::value, T_loc>;
using T_sigma_ref = ref_type_if_t<!is_constant<T_scale>::value, T_scale>;
static const char* function = "normal_lpdf";
check_consistent_sizes(function, "Random variable", y, "Location parameter",
mu, "Scale parameter", sigma);
T_y_ref y_ref = y;
T_mu_ref mu_ref = mu;
T_sigma_ref sigma_ref = sigma;
decltype(auto) y_val = to_ref(as_value_column_array_or_scalar(y_ref));
decltype(auto) mu_val = to_ref(as_value_column_array_or_scalar(mu_ref));
decltype(auto) sigma_val = to_ref(as_value_column_array_or_scalar(sigma_ref));
check_not_nan(function, "Random variable", y_val);
check_finite(function, "Location parameter", mu_val);
check_positive(function, "Scale parameter", sigma_val);
if (size_zero(y, mu, sigma)) {
return 0.0;
}
if (!include_summand<propto, T_y, T_loc, T_scale>::value) {
return 0.0;
}
operands_and_partials<T_y_ref, T_mu_ref, T_sigma_ref> ops_partials(
y_ref, mu_ref, sigma_ref);
const auto& inv_sigma
= to_ref_if<!is_constant_all<T_y, T_scale, T_loc>::value>(inv(sigma_val));
const auto& y_scaled = to_ref((y_val - mu_val) * inv_sigma);
const auto& y_scaled_sq
= to_ref_if<!is_constant_all<T_scale>::value>(y_scaled * y_scaled);
size_t N = max_size(y, mu, sigma);
T_partials_return logp = -0.5 * sum(y_scaled_sq);
if (include_summand<propto>::value) {
logp += NEG_LOG_SQRT_TWO_PI * N;
}
if (include_summand<propto, T_scale>::value) {
logp -= sum(log(sigma_val)) * N / size(sigma);
}
if (!is_constant_all<T_y, T_scale, T_loc>::value) {
auto scaled_diff = to_ref_if<!is_constant_all<T_y>::value
+ !is_constant_all<T_scale>::value
+ !is_constant_all<T_loc>::value
>= 2>(inv_sigma * y_scaled);
if (!is_constant_all<T_y>::value) {
ops_partials.edge1_.partials_ = -scaled_diff;
}
if (!is_constant_all<T_scale>::value) {
ops_partials.edge3_.partials_ = inv_sigma * y_scaled_sq - inv_sigma;
}
if (!is_constant_all<T_loc>::value) {
ops_partials.edge2_.partials_ = std::move(scaled_diff);
}
}
return ops_partials.build(logp);
}
template <typename T_y, typename T_loc, typename T_scale>
inline return_type_t<T_y, T_loc, T_scale> normal_lpdf(const T_y& y,
const T_loc& mu,
const T_scale& sigma) {
return normal_lpdf<false>(y, mu, sigma);
}
} // namespace math
} // namespace stan
#endif
<commit_msg>Added some couts. All tests passed.<commit_after>#ifndef STAN_MATH_PRIM_PROB_NORMAL_LPDF_HPP
#define STAN_MATH_PRIM_PROB_NORMAL_LPDF_HPP
#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/err.hpp>
#include <stan/math/prim/fun/as_column_vector_or_scalar.hpp>
#include <stan/math/prim/fun/as_array_or_scalar.hpp>
#include <stan/math/prim/fun/as_value_column_array_or_scalar.hpp>
#include <stan/math/prim/fun/constants.hpp>
#include <stan/math/prim/fun/log.hpp>
#include <stan/math/prim/fun/max_size.hpp>
#include <stan/math/prim/fun/size.hpp>
#include <stan/math/prim/fun/size_zero.hpp>
#include <stan/math/prim/fun/to_ref.hpp>
#include <stan/math/prim/fun/value_of.hpp>
#include <stan/math/prim/functor/operands_and_partials.hpp>
#include <cmath>
namespace stan {
namespace math {
/** \ingroup prob_dists
* The log of the normal density for the specified scalar(s) given
* the specified mean(s) and deviation(s). y, mu, or sigma can
* each be either a scalar or a vector. Any vector inputs
* must be the same length.
*
* <p>The result log probability is defined to be the sum of the
* log probabilities for each observation/mean/deviation triple.
*
* @tparam T_y type of scalar
* @tparam T_loc type of location parameter
* @tparam T_scale type of scale parameter
* @param y (Sequence of) scalar(s).
* @param mu (Sequence of) location parameter(s)
* for the normal distribution.
* @param sigma (Sequence of) scale parameters for the normal distribution.
* @return The log of the product of the densities.
* @throw std::domain_error if the scale is not positive.
*/
template <bool propto, typename T_y, typename T_loc, typename T_scale,
require_all_not_nonscalar_prim_or_rev_kernel_expression_t<
T_y, T_loc, T_scale>* = nullptr>
inline return_type_t<T_y, T_loc, T_scale> normal_lpdf(const T_y& y,
const T_loc& mu,
const T_scale& sigma) {
using T_partials_return = partials_return_t<T_y, T_loc, T_scale>;
using T_y_ref = ref_type_if_t<!is_constant<T_y>::value, T_y>;
using T_mu_ref = ref_type_if_t<!is_constant<T_loc>::value, T_loc>;
using T_sigma_ref = ref_type_if_t<!is_constant<T_scale>::value, T_scale>;
static const char* function = "normal_lpdf";
check_consistent_sizes(function, "Random variable", y, "Location parameter",
mu, "Scale parameter", sigma);
T_y_ref y_ref = y;
T_mu_ref mu_ref = mu;
T_sigma_ref sigma_ref = sigma;
decltype(auto) y_val = to_ref(as_value_column_array_or_scalar(y_ref));
decltype(auto) mu_val = to_ref(as_value_column_array_or_scalar(mu_ref));
decltype(auto) sigma_val = to_ref(as_value_column_array_or_scalar(sigma_ref));
check_not_nan(function, "Random variable", y_val);
check_finite(function, "Location parameter", mu_val);
check_positive(function, "Scale parameter", sigma_val);
if (size_zero(y, mu, sigma)) {
return 0.0;
}
if (!include_summand<propto, T_y, T_loc, T_scale>::value) {
return 0.0;
}
operands_and_partials<T_y_ref, T_mu_ref, T_sigma_ref> ops_partials(
y_ref, mu_ref, sigma_ref);
const auto& inv_sigma
= to_ref_if<!is_constant_all<T_y, T_scale, T_loc>::value>(inv(sigma_val));
const auto& y_scaled = to_ref((y_val - mu_val) * inv_sigma);
const auto& y_scaled_sq
= to_ref_if<!is_constant_all<T_scale>::value>(y_scaled * y_scaled);
size_t N = max_size(y, mu, sigma);
T_partials_return logp = -0.5 * sum(y_scaled_sq);
if (include_summand<propto>::value) {
logp += NEG_LOG_SQRT_TWO_PI * N;
}
if (include_summand<propto, T_scale>::value) {
logp -= sum(log(sigma_val)) * N / size(sigma);
}
if (!is_constant_all<T_y, T_scale, T_loc>::value) {
auto scaled_diff = to_ref_if<!is_constant_all<T_y>::value
+ !is_constant_all<T_scale>::value
+ !is_constant_all<T_loc>::value
>= 2>(inv_sigma * y_scaled);
if (!is_constant_all<T_y>::value) {
std::cout << "y partial: " << -scaled_diff << std::endl;
ops_partials.edge1_.partials_ = -scaled_diff;
}
if (!is_constant_all<T_scale>::value) {
std::cout << "mu partial: " << inv_sigma * y_scaled_sq - inv_sigma << std::endl;
ops_partials.edge3_.partials_ = inv_sigma * y_scaled_sq - inv_sigma;
}
if (!is_constant_all<T_loc>::value) {
std::cout << "mu partial: " << scaled_diff << std::endl;
ops_partials.edge2_.partials_ = std::move(scaled_diff);
}
}
return ops_partials.build(logp);
}
template <typename T_y, typename T_loc, typename T_scale>
inline return_type_t<T_y, T_loc, T_scale> normal_lpdf(const T_y& y,
const T_loc& mu,
const T_scale& sigma) {
return normal_lpdf<false>(y, mu, sigma);
}
} // namespace math
} // namespace stan
#endif
<|endoftext|> |
<commit_before>/*-----------------------------------------------------------------------------
This source file is part of Hopsan NG
Copyright (c) 2011
Mikael Axin, Robert Braun, Alessandro Dell'Amico, Björn Eriksson,
Peter Nordin, Karl Pettersson, Petter Krus, Ingo Staack
This file is provided "as is", with no guarantee or warranty for the
functionality or reliability of the contents. All contents in this file is
the original work of the copyright holders at the Division of Fluid and
Mechatronic Systems (Flumes) at Linköping University. Modifying, using or
redistributing any part of this file is prohibited without explicit
permission from the copyright holders.
-----------------------------------------------------------------------------*/
//!
//! @file HydraulicCylinderQ.hpp
//! @author Robert Braun <robert.braun@liu.se>
//! @date 2010-01-21
//!
//! @brief Contains a Hydraulic Cylinder of Q type with mass load
//!
//$Id$
////////////////////////////////////////////////////////////////////////////////////
// //
// <--------------Stroke---------------> //
// //
// XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXX //
// X Area1 X X Area2 X X X //
// X X XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX X //
// X x1,v1,f1 <---O X X Mass O---> x2,v2,f2 //
// X X XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX X //
// X X X X X X //
// XXOXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXOXX XXXXXXXX //
// | | //
// | | //
// V p1,q1 V p2,q2 //
// //
////////////////////////////////////////////////////////////////////////////////////
#ifndef HYDRAULICCYLINDERQ_HPP_INCLUDED
#define HYDRAULICCYLINDERQ_HPP_INCLUDED
#include <iostream>
#include "../../ComponentEssentials.h"
#include "../../ComponentUtilities.h"
namespace hopsan {
//!
//! @brief
//! @ingroup HydraulicComponents
//!
class HydraulicCylinderQ : public ComponentQ
{
private:
double mArea1;
double mArea2;
double mStroke;
double mMass;
double mBp;
double mBl;
double mKl;
double mTao;
SecondOrderFilter mPositionFilter;
SecondOrderFilter mVelocityFilter;
double posnum[3], posden[3], velnum[3], velden[3];
double p1, q1, c1, Zc1, p2, q2, c2, Zc2, v1, cx1, Zx1, f2, x2, v2, cx2, Zx2;
double *mpND_p1, *mpND_q1, *mpND_c1, *mpND_Zc1, *mpND_p2, *mpND_q2, *mpND_c2, *mpND_Zc2, *mpND_f2, *mpND_x2, *mpND_v2, *cmpND_x2, *mpND_Zx2;
Port *mpP1, *mpP2, *mpP3;
public:
static Component *Creator()
{
return new HydraulicCylinderQ("CylinderQ");
}
HydraulicCylinderQ(const std::string name) : ComponentQ(name)
{
mArea1 = 0.0001;
mArea2 = 0.0001;
mStroke = 0.01;
mMass = 0.05;
mBp = 0.0;
mBl = 0;
mKl = 1000;
mTao = 3.0/2.0*mTimestep; //Velocity filter time constant, should be in initialize?
mpP1 = addPowerPort("P1", "NodeHydraulic");
mpP2 = addPowerPort("P2", "NodeHydraulic");
mpP3 = addPowerPort("P3", "NodeMechanic");
registerParameter("A_1", "Piston Area 1", "[m^2]", mArea1);
registerParameter("A_2", "Piston Area 2", "[m^2]", mArea2);
registerParameter("s_l", "Stroke", "[m]", mStroke);
registerParameter("B_p", "Viscous Friction Coefficient of Piston", "[Ns/m]", mBp);
registerParameter("m_l", "Inertia Load", "[kg]", mMass);
registerParameter("B_l", "Viscous Friction of Load", "[Ns/m]", mBl);
registerParameter("k_l", "Stiffness of Load", "[N/m]", mKl);
}
void initialize()
{
//Assign node data pointers
mpND_p1 = getSafeNodeDataPtr(mpP1, NodeHydraulic::PRESSURE);
mpND_q1 = getSafeNodeDataPtr(mpP1, NodeHydraulic::FLOW);
mpND_c1 = getSafeNodeDataPtr(mpP1, NodeHydraulic::WAVEVARIABLE);
mpND_Zc1 = getSafeNodeDataPtr(mpP1, NodeHydraulic::CHARIMP);
mpND_p2 = getSafeNodeDataPtr(mpP1, NodeHydraulic::PRESSURE);
mpND_q2 = getSafeNodeDataPtr(mpP1, NodeHydraulic::FLOW);
mpND_c2 = getSafeNodeDataPtr(mpP1, NodeHydraulic::WAVEVARIABLE);
mpND_Zc2 = getSafeNodeDataPtr(mpP1, NodeHydraulic::CHARIMP);
mpND_f2 = getSafeNodeDataPtr(mpP1, NodeMechanic::FORCE);
mpND_x2 = getSafeNodeDataPtr(mpP1, NodeMechanic::POSITION);
mpND_v2 = getSafeNodeDataPtr(mpP1, NodeMechanic::VELOCITY);
cmpND_x2 = getSafeNodeDataPtr(mpP1, NodeMechanic::WAVEVARIABLE);
mpND_Zx2 = getSafeNodeDataPtr(mpP1, NodeMechanic::CHARIMP);
//Read data from nodes
x2 = (*mpND_x2);
v2 = (*mpND_v2);
Zc1 = (*mpND_Zc1);
Zc2 = (*mpND_Zc2);
cx2 = (*cmpND_x2);
Zx2 = (*mpND_Zx2);
Zx1 = mArea1*mArea1*Zc1 + mArea2*mArea2*Zc2-mBp;
//Initialization of filters
posnum[0] = 0.0;
posnum[1] = 0.0;
posnum[2] = 1.0;
posden[0] = mMass;
posden[1] = mBl+Zx1+Zx2;
posden[2] = mKl;
velnum[0] = 0.0;
velnum[1] = 1.0;
velnum[2] = 0.0;
velden[0] = 0.0;
velden[1] = mTao;
velden[2] = 1.0;
mPositionFilter.initialize(mTimestep, posnum, posden, cx2, x2, 0.0, mStroke);
mVelocityFilter.initialize(mTimestep, velnum, velden, x2, v2);
}
void simulateOneTimestep()
{
//Get variable values from nodes
c1 = (*mpND_c1);
Zc1 = (*mpND_Zc1);
c2 = (*mpND_c2);
Zc2 = (*mpND_Zc2);
cx2 = (*cmpND_x2);
Zx2 = (*mpND_Zx2);
//CylinderCtest Equations
//Internal mechanical port
cx1 = mArea1*c1 - mArea2*c2;
Zx1 = mArea1*mArea1*Zc1 + mArea2*mArea2*Zc2-mBp;
//Piston
posden [1] = mBl+Zx1+Zx2;
mPositionFilter.setNumDen(posnum, posden);
mPositionFilter.update(cx1-cx2);
x2 = mPositionFilter.value();
mVelocityFilter.update(x2);
v2 = mVelocityFilter.value();
v1 = -v2;
f2 = cx2 + Zc2*v2;
//Volumes
q1 = mArea1*v1;
q2 = mArea2*v2;
p1 = c1 + Zc1*q1;
p2 = c2 + Zc2*q2;
//Cavitation check
if(p1 < 0.0) { p1 = 0.0; }
if(p2 < 0.0) { p2 = 0.0; }
//Write new values to nodes
(*mpND_p1) = p1;
(*mpND_q1) = q1;
(*mpND_p2) = p2;
(*mpND_q2) = q2;
(*mpND_f2) = f2;
(*mpND_x2) = x2;
(*mpND_v2) = v2;
}
};
}
#endif // HYDRAULICCYLINDERQ_HPP_INCLUDED
<commit_msg>changed filter call in cylinder Q, it does not work. But, it could not had worked before either.<commit_after>/*-----------------------------------------------------------------------------
This source file is part of Hopsan NG
Copyright (c) 2011
Mikael Axin, Robert Braun, Alessandro Dell'Amico, Björn Eriksson,
Peter Nordin, Karl Pettersson, Petter Krus, Ingo Staack
This file is provided "as is", with no guarantee or warranty for the
functionality or reliability of the contents. All contents in this file is
the original work of the copyright holders at the Division of Fluid and
Mechatronic Systems (Flumes) at Linköping University. Modifying, using or
redistributing any part of this file is prohibited without explicit
permission from the copyright holders.
-----------------------------------------------------------------------------*/
//!
//! @file HydraulicCylinderQ.hpp
//! @author Robert Braun <robert.braun@liu.se>
//! @date 2010-01-21
//!
//! @brief Contains a Hydraulic Cylinder of Q type with mass load
//!
//$Id$
////////////////////////////////////////////////////////////////////////////////////
// //
// <--------------Stroke---------------> //
// //
// XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXX //
// X Area1 X X Area2 X X X //
// X X XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX X //
// X x1,v1,f1 <---O X X Mass O---> x2,v2,f2 //
// X X XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX X //
// X X X X X X //
// XXOXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXOXX XXXXXXXX //
// | | //
// | | //
// V p1,q1 V p2,q2 //
// //
////////////////////////////////////////////////////////////////////////////////////
#ifndef HYDRAULICCYLINDERQ_HPP_INCLUDED
#define HYDRAULICCYLINDERQ_HPP_INCLUDED
#include <iostream>
#include "../../ComponentEssentials.h"
#include "../../ComponentUtilities.h"
namespace hopsan {
//!
//! @brief
//! @ingroup HydraulicComponents
//!
class HydraulicCylinderQ : public ComponentQ
{
private:
double mArea1;
double mArea2;
double mStroke;
double mMass;
double mBp;
double mBl;
double mKl;
double mTao;
SecondOrderFilter mPositionFilter;
SecondOrderFilter mVelocityFilter;
double posnum[3], posden[3], velnum[3], velden[3];
double p1, q1, c1, Zc1, p2, q2, c2, Zc2, v1, cx1, Zx1, f2, x2, v2, cx2, Zx2;
double *mpND_p1, *mpND_q1, *mpND_c1, *mpND_Zc1, *mpND_p2, *mpND_q2, *mpND_c2, *mpND_Zc2, *mpND_f2, *mpND_x2, *mpND_v2, *cmpND_x2, *mpND_Zx2;
Port *mpP1, *mpP2, *mpP3;
public:
static Component *Creator()
{
return new HydraulicCylinderQ("CylinderQ");
}
HydraulicCylinderQ(const std::string name) : ComponentQ(name)
{
mArea1 = 0.0001;
mArea2 = 0.0001;
mStroke = 0.01;
mMass = 0.05;
mBp = 0.0;
mBl = 0;
mKl = 1000;
mTao = 3.0/2.0*mTimestep; //Velocity filter time constant, should be in initialize?
mpP1 = addPowerPort("P1", "NodeHydraulic");
mpP2 = addPowerPort("P2", "NodeHydraulic");
mpP3 = addPowerPort("P3", "NodeMechanic");
registerParameter("A_1", "Piston Area 1", "[m^2]", mArea1);
registerParameter("A_2", "Piston Area 2", "[m^2]", mArea2);
registerParameter("s_l", "Stroke", "[m]", mStroke);
registerParameter("B_p", "Viscous Friction Coefficient of Piston", "[Ns/m]", mBp);
registerParameter("m_l", "Inertia Load", "[kg]", mMass);
registerParameter("B_l", "Viscous Friction of Load", "[Ns/m]", mBl);
registerParameter("k_l", "Stiffness of Load", "[N/m]", mKl);
}
void initialize()
{
//Assign node data pointers
mpND_p1 = getSafeNodeDataPtr(mpP1, NodeHydraulic::PRESSURE);
mpND_q1 = getSafeNodeDataPtr(mpP1, NodeHydraulic::FLOW);
mpND_c1 = getSafeNodeDataPtr(mpP1, NodeHydraulic::WAVEVARIABLE);
mpND_Zc1 = getSafeNodeDataPtr(mpP1, NodeHydraulic::CHARIMP);
mpND_p2 = getSafeNodeDataPtr(mpP1, NodeHydraulic::PRESSURE);
mpND_q2 = getSafeNodeDataPtr(mpP1, NodeHydraulic::FLOW);
mpND_c2 = getSafeNodeDataPtr(mpP1, NodeHydraulic::WAVEVARIABLE);
mpND_Zc2 = getSafeNodeDataPtr(mpP1, NodeHydraulic::CHARIMP);
mpND_f2 = getSafeNodeDataPtr(mpP1, NodeMechanic::FORCE);
mpND_x2 = getSafeNodeDataPtr(mpP1, NodeMechanic::POSITION);
mpND_v2 = getSafeNodeDataPtr(mpP1, NodeMechanic::VELOCITY);
cmpND_x2 = getSafeNodeDataPtr(mpP1, NodeMechanic::WAVEVARIABLE);
mpND_Zx2 = getSafeNodeDataPtr(mpP1, NodeMechanic::CHARIMP);
//Read data from nodes
x2 = (*mpND_x2);
v2 = (*mpND_v2);
Zc1 = (*mpND_Zc1);
Zc2 = (*mpND_Zc2);
cx2 = (*cmpND_x2);
Zx2 = (*mpND_Zx2);
Zx1 = mArea1*mArea1*Zc1 + mArea2*mArea2*Zc2-mBp;
//Initialization of filters
posnum[0] = 0.0;
posnum[1] = 0.0;
posnum[2] = 1.0;
posden[0] = mKl;
posden[1] = mBl+Zx1+Zx2;
posden[2] = mMass;
velnum[0] = 0.0;
velnum[1] = 1.0;
velnum[2] = 0.0;
velden[0] = 1.0;
velden[1] = mTao;
velden[2] = 0.0;
mPositionFilter.initialize(mTimestep, posnum, posden, cx2, x2, 0.0, mStroke);
mVelocityFilter.initialize(mTimestep, velnum, velden, x2, v2);
}
void simulateOneTimestep()
{
//Get variable values from nodes
c1 = (*mpND_c1);
Zc1 = (*mpND_Zc1);
c2 = (*mpND_c2);
Zc2 = (*mpND_Zc2);
cx2 = (*cmpND_x2);
Zx2 = (*mpND_Zx2);
//CylinderCtest Equations
//Internal mechanical port
cx1 = mArea1*c1 - mArea2*c2;
Zx1 = mArea1*mArea1*Zc1 + mArea2*mArea2*Zc2-mBp;
//Piston
posden [1] = mBl+Zx1+Zx2;
mPositionFilter.setNumDen(posnum, posden);
mPositionFilter.update(cx1-cx2);
x2 = mPositionFilter.value();
mVelocityFilter.update(x2);
v2 = mVelocityFilter.value();
v1 = -v2;
f2 = cx2 + Zc2*v2;
//Volumes
q1 = mArea1*v1;
q2 = mArea2*v2;
p1 = c1 + Zc1*q1;
p2 = c2 + Zc2*q2;
//Cavitation check
if(p1 < 0.0) { p1 = 0.0; }
if(p2 < 0.0) { p2 = 0.0; }
//Write new values to nodes
(*mpND_p1) = p1;
(*mpND_q1) = q1;
(*mpND_p2) = p2;
(*mpND_q2) = q2;
(*mpND_f2) = f2;
(*mpND_x2) = x2;
(*mpND_v2) = v2;
}
};
}
#endif // HYDRAULICCYLINDERQ_HPP_INCLUDED
<|endoftext|> |
<commit_before>//
// datarecovery.cpp
// codeval1
//
// Created by Malcolm Crum on 5/13/14.
//
//
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
int main(int argc, char** argv) {
ifstream fileInput;
fileInput.open(argv[1]);
//while (fileInput.peek() != EOF) {
string word;
vector<string> words;
fileInput >> word;
while (word.find(';') == string::npos) {
words.push_back(word);
fileInput >> word;
}
// the last "word" would normally get grabbed as 'word;9'.
// special handling is required to split it into 'word' and '9'
int semicolonIndex = word.find(';');
words.push_back(word.substr(0, semicolonIndex));
cout << "read " << words.size() << " words" << endl;
for (int i = 0; i < words.size(); i++) {
cout << words[i] << " ";
}
cout << endl;
int value;
vector<string> orderedWords;
orderedWords.resize(words.size());
// again, special handling required to get the number out of 'word;9'
value = atoi(word.substr(semicolonIndex, word.size()).c_str());
orderedWords[0] = words[value];
for(int i = 1; fileInput.peek() != '\n'; i++) {
fileInput >> value;
cout << "words[" << value << "] = " << words[value] << endl;
cout << "words[" << i << "] = " << words[i] << endl;
orderedWords[value] = words[i];
}
for (int i = 0; i < orderedWords.size(); i++) {
cout << orderedWords[i] << " ";
}
cout << endl;
//}
}<commit_msg>Forgot to actually finish this one. A hard 'easy'<commit_after>//
// datarecovery.cpp
// codeval1
//
// Created by Malcolm Crum on 5/13/14.
//
//
#include <iostream>
#include <fstream>
#include <vector>
#include <sstream>
#include <algorithm>
using namespace std;
vector<string> splitString(string str) {
vector<string> vec;
stringstream ss(str);
string s;
while (ss >> s) {
vec.push_back(s);
}
return vec;
}
vector<int> splitIntString(string str) {
vector<int> vec;
stringstream ss(str);
int i;
while (ss >> i) {
vec.push_back(i);
}
return vec;
}
int main(int argc, char** argv) {
ifstream fileInput;
fileInput.open(argv[1]);
string line;
while (getline(fileInput, line)) {
string wordString = line.substr(0, line.find(';'));
vector<string> words = splitString(wordString);
string orderString = line.substr(line.find(';') + 1);
vector<int> order = splitIntString(orderString);
vector<string> orderedWords(order.size() + 1);
for (int i = 0; i < order.size(); ++i) {
int index = order[i] - 1;
//cout << words[i] << " ";
orderedWords[index] = words[i];
}
int missingIndex = 1;
for (int i = 1; i < words.size() + 1; ++i) {
if (find(order.begin(), order.end(), i) == order.end()) {
missingIndex = i;
break;
}
}
orderedWords[missingIndex - 1] = words.back();
for (vector<string>::iterator it = orderedWords.begin(); it != orderedWords.end(); ++it) {
cout << *it << " ";
}
cout << endl;
}
}<|endoftext|> |
<commit_before>/*
* Copyright 2002-2013 Jose Fonseca
*
* 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.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <assert.h>
#include <stdlib.h>
#include <string>
#include <windows.h>
#include <tlhelp32.h>
#include <process.h>
#include "getopt.h"
#include "debugger.h"
#include "symbols.h"
#include "dialog.h"
#include "errmsg.h"
#include "log.h"
#include "outdbg.h"
static int process_id_given = 0; /* Whether process-id was given. */
static int install_given = 0; /* Whether install was given. */
static int uninstall_given = 0; /* Whether uninstall was given. */
static void
help(void)
{
MessageBoxA(NULL,
"Usage: drmingw [OPTIONS]\r\n"
"\r\n"
"Options:\r\n"
" -h, --help\tPrint help and exit\r\n"
" -V, --version\tPrint version and exit\r\n"
" -i, --install\tInstall as the default JIT debugger\r\n"
" -u, --uninstall\tUninstall\r\n"
" -pLONG, --process-id=LONG\r\n"
"\t\tAttach to the process with the given identifier\r\n"
" -eLONG, --event=LONG\r\n"
"\t\tSignal an event after process is attached\r\n"
" -b, --breakpoint\tTreat debug breakpoints as exceptions\r\n"
" -v, --verbose\tVerbose output\r\n"
" -d, --debug\tDebug output\r\n",
PACKAGE, MB_OK | MB_ICONINFORMATION);
}
static LSTATUS
regSetStr(HKEY hKey, LPCSTR lpValueName, LPCSTR szStr)
{
return RegSetValueExA(hKey, lpValueName, 0, REG_SZ, reinterpret_cast<LPCBYTE>(szStr),
strlen(szStr) + 1);
}
static DWORD
install(REGSAM samDesired)
{
char szFile[MAX_PATH];
if (!GetModuleFileNameA(NULL, szFile, MAX_PATH)) {
return GetLastError();
}
std::string debuggerCommand;
debuggerCommand += '"';
debuggerCommand += szFile;
debuggerCommand += "\" -p %ld -e %ld";
if (debugOptions.verbose_flag)
debuggerCommand += " -v";
if (debugOptions.breakpoint_flag)
debuggerCommand += " -b";
if (debugOptions.debug_flag)
debuggerCommand += " -d";
HKEY hKey;
long lRet;
DWORD dwDisposition;
lRet =
RegCreateKeyExA(HKEY_LOCAL_MACHINE,
"Software\\Microsoft\\Windows NT\\CurrentVersion\\AeDebug", // The AeDebug
// registry key.
0, NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE | samDesired, NULL, &hKey,
&dwDisposition);
if (lRet != ERROR_SUCCESS) {
return lRet;
}
// Write the Debugger value.
lRet = regSetStr(hKey, "Debugger", debuggerCommand.c_str());
if (lRet == ERROR_SUCCESS) {
// Write the Auto value.
lRet = regSetStr(hKey, "Auto", "1");
}
// Close the key no matter what happened.
RegCloseKey(hKey);
return lRet;
}
static DWORD
uninstall(REGSAM samDesired)
{
HKEY hKey;
long lRet;
lRet =
RegOpenKeyExA(HKEY_LOCAL_MACHINE,
"Software\\Microsoft\\Windows NT\\CurrentVersion\\AeDebug", // The AeDebug
// registry key.
0, KEY_ALL_ACCESS | samDesired, &hKey);
if (lRet != ERROR_SUCCESS) {
return lRet;
}
// Write the Debugger value.
lRet = regSetStr(hKey, "Debugger", "");
// Leave Auto value as "1". It is the default
// (https://docs.microsoft.com/en-us/windows/desktop/Debug/configuring-automatic-debugging)
// and setting it to "0" doesn't seem to work as documented on Windows 10
// (https://github.com/jrfonseca/drmingw/issues/38)
// Close the key no matter what happened.
RegCloseKey(hKey);
return lRet;
}
static DWORD
getProcessIdByName(const char *szProcessName)
{
DWORD dwProcessId = 0;
HANDLE hProcessSnap;
hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hProcessSnap != INVALID_HANDLE_VALUE) {
PROCESSENTRY32 pe32;
pe32.dwSize = sizeof pe32;
if (Process32First(hProcessSnap, &pe32)) {
do {
if (stricmp(szProcessName, pe32.szExeFile) == 0) {
dwProcessId = pe32.th32ProcessID;
break;
}
} while (Process32Next(hProcessSnap, &pe32));
}
CloseHandle(hProcessSnap);
}
return dwProcessId;
}
static void
debugThread(void *arg)
{
DWORD dwProcessId = (DWORD)(UINT_PTR)arg;
// attach debuggee
if (!DebugActiveProcess(dwProcessId)) {
ErrorMessageBox("DebugActiveProcess: %s", LastErrorMessage());
return;
}
setDumpCallback(appendText);
SetSymOptions(debugOptions.debug_flag);
DebugMainLoop();
}
int
main(int argc, char **argv)
{
DWORD dwProcessId = 0;
int c; /* Character of the parsed option. */
debugOptions.first_chance = 1;
while (1) {
int option_index = 0;
static const struct option long_options[] = {{"help", 0, NULL, 'h'},
{"version", 0, NULL, 'V'},
{"install", 0, NULL, 'i'},
{"uninstall", 0, NULL, 'u'},
{"process-id", 1, NULL, 'p'},
{"event", 1, NULL, 'e'},
{"tid", 1, NULL, 't'},
{"breakpoint", 0, NULL, 'b'},
{"verbose", 0, NULL, 'v'},
{"debug", 0, NULL, 'd'},
{NULL, 0, NULL, 0}};
c = getopt_long_only(argc, argv, "?hViup:e:t:vbd", long_options, &option_index);
if (c == -1)
break; /* Exit from `while (1)' loop. */
switch (c) {
case '?':
if (optopt != '?') {
/* Invalid option. */
char szErrMsg[512];
sprintf(szErrMsg, "Invalid option '%c'", optopt);
MessageBoxA(NULL, szErrMsg, PACKAGE, MB_OK | MB_ICONSTOP);
return 1;
}
/* fall-through */
case 'h': /* Print help and exit. */
help();
return 0;
case 'V': /* Print version and exit. */
MessageBoxA(NULL, PACKAGE " " VERSION, PACKAGE, MB_OK | MB_ICONINFORMATION);
return 0;
case 'i': /* Install as the default JIT debugger. */
if (uninstall_given) {
MessageBoxA(NULL, "conficting options `--uninstall' (`-u') and `--install' (`-i')",
PACKAGE, MB_OK | MB_ICONSTOP);
return 0;
}
install_given = 1;
break;
case 'u': /* Uninstall. */
if (install_given) {
MessageBoxA(NULL, "conficting options `--install' (`-i') and `--uninstall' (`-u')",
PACKAGE, MB_OK | MB_ICONSTOP);
return 0;
}
uninstall_given = 1;
break;
case 'p': /* Attach to the process with the given identifier. */
if (process_id_given) {
MessageBoxA(NULL, "`--process-id' (`-p') option redeclared", PACKAGE,
MB_OK | MB_ICONSTOP);
return 1;
}
process_id_given = 1;
if (optarg[0] >= '0' && optarg[0] <= '9') {
dwProcessId = strtoul(optarg, NULL, 0);
} else {
debugOptions.breakpoint_flag = true;
dwProcessId = getProcessIdByName(optarg);
}
if (!dwProcessId) {
MessageBoxA(NULL, "Invalid process", PACKAGE, MB_OK | MB_ICONSTOP);
return 1;
}
break;
case 'e': /* Signal an event after process is attached. */
if (debugOptions.hEvent) {
MessageBoxA(NULL, "`--event' (`-e') option redeclared", PACKAGE,
MB_OK | MB_ICONSTOP);
return 1;
}
debugOptions.hEvent = (HANDLE)(INT_PTR)atol(optarg);
break;
case 't': {
/* Thread id. Used when debugging WinRT apps. */
debugOptions.dwThreadId = strtoul(optarg, NULL, 0);
break;
}
case 'b': /* Treat debug breakpoints as exceptions */
debugOptions.breakpoint_flag = true;
break;
case 'v': /* Verbose output. */
debugOptions.verbose_flag = true;
break;
case 'd': /* Debug output. */
debugOptions.debug_flag = true;
break;
default: /* bug: option not considered. */
{
char szErrMsg[512];
sprintf(szErrMsg, "Unexpected option '-%c'", c);
MessageBoxA(NULL, szErrMsg, PACKAGE, MB_OK | MB_ICONSTOP);
return 1;
}
}
}
if (install_given) {
DWORD dwRet = install(0);
#if defined(_WIN64)
if (dwRet == ERROR_SUCCESS) {
dwRet = install(KEY_WOW64_32KEY);
}
#endif
if (dwRet != ERROR_SUCCESS) {
MessageBoxA(NULL,
dwRet == ERROR_ACCESS_DENIED
? "You must have administrator privileges to install Dr. Mingw as the "
"default application debugger"
: "Unexpected error when trying to install Dr. Mingw as the default "
"application debugger",
"DrMingw", MB_OK | MB_ICONERROR);
return 1;
}
MessageBoxA(NULL, "Dr. Mingw has been installed as the default application debugger",
"DrMingw", MB_OK | MB_ICONINFORMATION);
return 0;
}
if (uninstall_given) {
DWORD dwRet = uninstall(0);
#if defined(_WIN64)
if (dwRet == ERROR_SUCCESS) {
dwRet = uninstall(KEY_WOW64_32KEY);
}
#endif
if (dwRet != ERROR_SUCCESS) {
MessageBoxA(NULL,
dwRet == ERROR_ACCESS_DENIED
? "You must have administrator privileges to uninstall Dr. Mingw as "
"the default application debugger"
: "Unexpected error when trying to uninstall Dr. Mingw as the default "
"application debugger",
"DrMingw", MB_OK | MB_ICONERROR);
return 1;
}
MessageBoxA(NULL, "Dr. Mingw has been uninstalled", "DrMingw", MB_OK | MB_ICONINFORMATION);
return 0;
}
if (process_id_given) {
SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
if (!ObtainSeDebugPrivilege())
MessageBoxA(NULL,
"An error occurred while obtaining debug privileges.\nDrMingw will not "
"debug system processes.",
"DrMingw", MB_OK | MB_ICONERROR);
createDialog();
_beginthread(debugThread, 0, (void *)(UINT_PTR)dwProcessId);
return mainLoop();
} else {
help();
}
return 0;
}
<commit_msg>Show version and copyright in Dr. Mingw usage dialog<commit_after>/*
* Copyright 2002-2013 Jose Fonseca
*
* 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.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <assert.h>
#include <stdlib.h>
#include <string>
#include <windows.h>
#include <tlhelp32.h>
#include <process.h>
#include "getopt.h"
#include "debugger.h"
#include "symbols.h"
#include "dialog.h"
#include "errmsg.h"
#include "log.h"
#include "outdbg.h"
#include "version.h"
static int process_id_given = 0; /* Whether process-id was given. */
static int install_given = 0; /* Whether install was given. */
static int uninstall_given = 0; /* Whether uninstall was given. */
static void
help(void)
{
MessageBoxA(NULL,
VER_PRODUCTNAME_STR " version " VER_PRODUCTVERSION_STR "\r\n"
VER_LEGALCOPYRIGHT_STR "\r\n"
"\r\n"
"Usage: drmingw [OPTIONS]\r\n"
"\r\n"
"Options:\r\n"
" -h, --help\tPrint help and exit\r\n"
" -V, --version\tPrint version and exit\r\n"
" -i, --install\tInstall as the default JIT debugger\r\n"
" -u, --uninstall\tUninstall\r\n"
" -pLONG, --process-id=LONG\r\n"
"\t\tAttach to the process with the given identifier\r\n"
" -eLONG, --event=LONG\r\n"
"\t\tSignal an event after process is attached\r\n"
" -b, --breakpoint\tTreat debug breakpoints as exceptions\r\n"
" -v, --verbose\tVerbose output\r\n"
" -d, --debug\tDebug output\r\n",
PACKAGE, MB_OK | MB_ICONINFORMATION);
}
static LSTATUS
regSetStr(HKEY hKey, LPCSTR lpValueName, LPCSTR szStr)
{
return RegSetValueExA(hKey, lpValueName, 0, REG_SZ, reinterpret_cast<LPCBYTE>(szStr),
strlen(szStr) + 1);
}
static DWORD
install(REGSAM samDesired)
{
char szFile[MAX_PATH];
if (!GetModuleFileNameA(NULL, szFile, MAX_PATH)) {
return GetLastError();
}
std::string debuggerCommand;
debuggerCommand += '"';
debuggerCommand += szFile;
debuggerCommand += "\" -p %ld -e %ld";
if (debugOptions.verbose_flag)
debuggerCommand += " -v";
if (debugOptions.breakpoint_flag)
debuggerCommand += " -b";
if (debugOptions.debug_flag)
debuggerCommand += " -d";
HKEY hKey;
long lRet;
DWORD dwDisposition;
lRet =
RegCreateKeyExA(HKEY_LOCAL_MACHINE,
"Software\\Microsoft\\Windows NT\\CurrentVersion\\AeDebug", // The AeDebug
// registry key.
0, NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE | samDesired, NULL, &hKey,
&dwDisposition);
if (lRet != ERROR_SUCCESS) {
return lRet;
}
// Write the Debugger value.
lRet = regSetStr(hKey, "Debugger", debuggerCommand.c_str());
if (lRet == ERROR_SUCCESS) {
// Write the Auto value.
lRet = regSetStr(hKey, "Auto", "1");
}
// Close the key no matter what happened.
RegCloseKey(hKey);
return lRet;
}
static DWORD
uninstall(REGSAM samDesired)
{
HKEY hKey;
long lRet;
lRet =
RegOpenKeyExA(HKEY_LOCAL_MACHINE,
"Software\\Microsoft\\Windows NT\\CurrentVersion\\AeDebug", // The AeDebug
// registry key.
0, KEY_ALL_ACCESS | samDesired, &hKey);
if (lRet != ERROR_SUCCESS) {
return lRet;
}
// Write the Debugger value.
lRet = regSetStr(hKey, "Debugger", "");
// Leave Auto value as "1". It is the default
// (https://docs.microsoft.com/en-us/windows/desktop/Debug/configuring-automatic-debugging)
// and setting it to "0" doesn't seem to work as documented on Windows 10
// (https://github.com/jrfonseca/drmingw/issues/38)
// Close the key no matter what happened.
RegCloseKey(hKey);
return lRet;
}
static DWORD
getProcessIdByName(const char *szProcessName)
{
DWORD dwProcessId = 0;
HANDLE hProcessSnap;
hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hProcessSnap != INVALID_HANDLE_VALUE) {
PROCESSENTRY32 pe32;
pe32.dwSize = sizeof pe32;
if (Process32First(hProcessSnap, &pe32)) {
do {
if (stricmp(szProcessName, pe32.szExeFile) == 0) {
dwProcessId = pe32.th32ProcessID;
break;
}
} while (Process32Next(hProcessSnap, &pe32));
}
CloseHandle(hProcessSnap);
}
return dwProcessId;
}
static void
debugThread(void *arg)
{
DWORD dwProcessId = (DWORD)(UINT_PTR)arg;
// attach debuggee
if (!DebugActiveProcess(dwProcessId)) {
ErrorMessageBox("DebugActiveProcess: %s", LastErrorMessage());
return;
}
setDumpCallback(appendText);
SetSymOptions(debugOptions.debug_flag);
DebugMainLoop();
}
int
main(int argc, char **argv)
{
DWORD dwProcessId = 0;
int c; /* Character of the parsed option. */
debugOptions.first_chance = 1;
while (1) {
int option_index = 0;
static const struct option long_options[] = {{"help", 0, NULL, 'h'},
{"version", 0, NULL, 'V'},
{"install", 0, NULL, 'i'},
{"uninstall", 0, NULL, 'u'},
{"process-id", 1, NULL, 'p'},
{"event", 1, NULL, 'e'},
{"tid", 1, NULL, 't'},
{"breakpoint", 0, NULL, 'b'},
{"verbose", 0, NULL, 'v'},
{"debug", 0, NULL, 'd'},
{NULL, 0, NULL, 0}};
c = getopt_long_only(argc, argv, "?hViup:e:t:vbd", long_options, &option_index);
if (c == -1)
break; /* Exit from `while (1)' loop. */
switch (c) {
case '?':
if (optopt != '?') {
/* Invalid option. */
char szErrMsg[512];
sprintf(szErrMsg, "Invalid option '%c'", optopt);
MessageBoxA(NULL, szErrMsg, PACKAGE, MB_OK | MB_ICONSTOP);
return 1;
}
/* fall-through */
case 'h': /* Print help and exit. */
help();
return 0;
case 'V': /* Print version and exit. */
MessageBoxA(NULL, PACKAGE " " VERSION, PACKAGE, MB_OK | MB_ICONINFORMATION);
return 0;
case 'i': /* Install as the default JIT debugger. */
if (uninstall_given) {
MessageBoxA(NULL, "conficting options `--uninstall' (`-u') and `--install' (`-i')",
PACKAGE, MB_OK | MB_ICONSTOP);
return 0;
}
install_given = 1;
break;
case 'u': /* Uninstall. */
if (install_given) {
MessageBoxA(NULL, "conficting options `--install' (`-i') and `--uninstall' (`-u')",
PACKAGE, MB_OK | MB_ICONSTOP);
return 0;
}
uninstall_given = 1;
break;
case 'p': /* Attach to the process with the given identifier. */
if (process_id_given) {
MessageBoxA(NULL, "`--process-id' (`-p') option redeclared", PACKAGE,
MB_OK | MB_ICONSTOP);
return 1;
}
process_id_given = 1;
if (optarg[0] >= '0' && optarg[0] <= '9') {
dwProcessId = strtoul(optarg, NULL, 0);
} else {
debugOptions.breakpoint_flag = true;
dwProcessId = getProcessIdByName(optarg);
}
if (!dwProcessId) {
MessageBoxA(NULL, "Invalid process", PACKAGE, MB_OK | MB_ICONSTOP);
return 1;
}
break;
case 'e': /* Signal an event after process is attached. */
if (debugOptions.hEvent) {
MessageBoxA(NULL, "`--event' (`-e') option redeclared", PACKAGE,
MB_OK | MB_ICONSTOP);
return 1;
}
debugOptions.hEvent = (HANDLE)(INT_PTR)atol(optarg);
break;
case 't': {
/* Thread id. Used when debugging WinRT apps. */
debugOptions.dwThreadId = strtoul(optarg, NULL, 0);
break;
}
case 'b': /* Treat debug breakpoints as exceptions */
debugOptions.breakpoint_flag = true;
break;
case 'v': /* Verbose output. */
debugOptions.verbose_flag = true;
break;
case 'd': /* Debug output. */
debugOptions.debug_flag = true;
break;
default: /* bug: option not considered. */
{
char szErrMsg[512];
sprintf(szErrMsg, "Unexpected option '-%c'", c);
MessageBoxA(NULL, szErrMsg, PACKAGE, MB_OK | MB_ICONSTOP);
return 1;
}
}
}
if (install_given) {
DWORD dwRet = install(0);
#if defined(_WIN64)
if (dwRet == ERROR_SUCCESS) {
dwRet = install(KEY_WOW64_32KEY);
}
#endif
if (dwRet != ERROR_SUCCESS) {
MessageBoxA(NULL,
dwRet == ERROR_ACCESS_DENIED
? "You must have administrator privileges to install Dr. Mingw as the "
"default application debugger"
: "Unexpected error when trying to install Dr. Mingw as the default "
"application debugger",
"DrMingw", MB_OK | MB_ICONERROR);
return 1;
}
MessageBoxA(NULL, "Dr. Mingw has been installed as the default application debugger",
"DrMingw", MB_OK | MB_ICONINFORMATION);
return 0;
}
if (uninstall_given) {
DWORD dwRet = uninstall(0);
#if defined(_WIN64)
if (dwRet == ERROR_SUCCESS) {
dwRet = uninstall(KEY_WOW64_32KEY);
}
#endif
if (dwRet != ERROR_SUCCESS) {
MessageBoxA(NULL,
dwRet == ERROR_ACCESS_DENIED
? "You must have administrator privileges to uninstall Dr. Mingw as "
"the default application debugger"
: "Unexpected error when trying to uninstall Dr. Mingw as the default "
"application debugger",
"DrMingw", MB_OK | MB_ICONERROR);
return 1;
}
MessageBoxA(NULL, "Dr. Mingw has been uninstalled", "DrMingw", MB_OK | MB_ICONINFORMATION);
return 0;
}
if (process_id_given) {
SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
if (!ObtainSeDebugPrivilege())
MessageBoxA(NULL,
"An error occurred while obtaining debug privileges.\nDrMingw will not "
"debug system processes.",
"DrMingw", MB_OK | MB_ICONERROR);
createDialog();
_beginthread(debugThread, 0, (void *)(UINT_PTR)dwProcessId);
return mainLoop();
} else {
help();
}
return 0;
}
<|endoftext|> |
<commit_before>/*********************************************************************
* node-dvbtee for Node.js
*
* Copyright (c) 2017 Michael Ira Krufky <https://github.com/mkrufky>
*
* MIT License <https://github.com/mkrufky/node-dvbtee/blob/master/LICENSE>
*
* See https://github.com/mkrufky/node-dvbtee for more information
********************************************************************/
#include <nan.h>
#include "dvbtee-parser.h" // NOLINT(build/include)
TableData::TableData(const uint8_t &tableId,
const std::string &decoderName,
const std::string &json)
: tableId(tableId)
, decoderName(decoderName)
, json(json)
{}
TableData::TableData()
: tableId(0)
{}
TableData::TableData(const TableData &t)
: tableId(t.tableId)
, decoderName(t.decoderName)
, json(t.json)
{}
TableData &TableData::operator=(const TableData &cSource) {
if (this == &cSource)
return *this;
tableId = cSource.tableId;
decoderName = cSource.decoderName;
json = cSource.json;
return *this;
}
////////////////////////////////////////
Nan::Persistent<v8::Function> dvbteeParser::constructor;
dvbteeParser::dvbteeParser() {
}
dvbteeParser::~dvbteeParser() {
}
void dvbteeParser::Init(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE exports) {
Nan::HandleScope scope;
v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New);
tpl->SetClassName(Nan::New("Parser").ToLocalChecked());
tpl->InstanceTemplate()->SetInternalFieldCount(1);
Nan::SetPrototypeMethod(tpl, "reset", reset);
Nan::SetPrototypeMethod(tpl, "feed", feed);
Nan::SetPrototypeMethod(tpl, "enableEttCollection", enableEttCollection);
constructor.Reset(tpl->GetFunction());
exports->Set(Nan::New("Parser").ToLocalChecked(), tpl->GetFunction());
}
void dvbteeParser::New(const Nan::FunctionCallbackInfo<v8::Value>& info) {
if (info.IsConstructCall()) {
// Invoked as constructor: `new dvbteeParser(...)`
dvbteeParser* obj = new dvbteeParser();
obj->Wrap(info.This());
info.GetReturnValue().Set(info.This());
} else {
// Invoked as plain function `dvbteeParser(...)`, turn into construct call.
const int argc = 0;
v8::Local<v8::Value> argv[argc] = { };
v8::Local<v8::Function> cons = Nan::New<v8::Function>(constructor);
info.GetReturnValue().Set(cons->NewInstance(argc, argv));
}
}
////////////////////////////////////////
void dvbteeParser::enableEttCollection(
const Nan::FunctionCallbackInfo<v8::Value>& info) {
dvbteeParser* obj = ObjectWrap::Unwrap<dvbteeParser>(info.Holder());
obj->m_parser.enable_ett_collection();
info.GetReturnValue().Set(info.Holder());
}
////////////////////////////////////////
class ResetWorker : public Nan::AsyncWorker {
public:
ResetWorker(Nan::Callback *callback,
const Nan::FunctionCallbackInfo<v8::Value>& info)
: Nan::AsyncWorker(callback) {
m_obj = Nan::ObjectWrap::Unwrap<dvbteeParser>(info.Holder());
}
~ResetWorker() {
}
void Execute () {
m_obj->m_parser.cleanup();
m_obj->m_parser.reset();
}
void HandleOKCallback () {
Nan::HandleScope scope;
v8::Local<v8::Value> argv[] = {
Nan::Null()
, Nan::New<v8::Number>(0)
};
callback->Call(2, argv);
}
private:
dvbteeParser* m_obj;
};
void dvbteeParser::reset(const Nan::FunctionCallbackInfo<v8::Value>& info) {
// If a callback function is supplied, this method will run async
// otherwise, it will run synchronous
int lastArg = info.Length() - 1;
if ((lastArg >= 0) && (info[lastArg]->IsFunction())) {
Nan::Callback *callback = new Nan::Callback(
info[lastArg].As<v8::Function>()
);
Nan::AsyncQueueWorker(new ResetWorker(callback, info));
} else {
dvbteeParser* obj = ObjectWrap::Unwrap<dvbteeParser>(info.Holder());
obj->m_parser.cleanup();
obj->m_parser.reset();
info.GetReturnValue().Set(info.Holder());
}
}
////////////////////////////////////////
class FeedWorker: public Nan::AsyncProgressQueueWorker<TableData> {
public:
FeedWorker(Nan::Callback *callback,
Nan::Callback *progress,
const Nan::FunctionCallbackInfo<v8::Value>& info)
: Nan::AsyncProgressQueueWorker<TableData>(callback)
, m_cb_progress(progress)
, m_buf(NULL)
, m_buf_len(0)
, m_ret(-1) {
m_obj = Nan::ObjectWrap::Unwrap<dvbteeParser>(info.Holder());
if ((info[0]->IsObject()) && (info[1]->IsNumber())) {
const char *key = "buf";
SaveToPersistent(key, info[0]);
Nan::MaybeLocal<v8::Object> mbBuf =
Nan::To<v8::Object>(GetFromPersistent(key));
if (!mbBuf.IsEmpty()) {
m_buf = node::Buffer::Data(mbBuf.ToLocalChecked());
m_buf_len = info[1]->Uint32Value();
}
}
}
~FeedWorker() {
}
void Execute(const AsyncProgressQueueWorker::ExecutionProgress& progress) {
if ((m_buf) && (m_buf_len)) {
Watcher watch(m_obj->m_parser, progress);
m_ret = m_obj->m_parser.feed(
m_buf_len, reinterpret_cast<uint8_t*>(m_buf)
);
}
if (m_ret < 0) {
SetErrorMessage("invalid buffer / length");
}
}
void HandleProgressCallback(const TableData *async_data, size_t count) {
Nan::HandleScope scope;
if (!m_cb_progress->IsEmpty()) {
for (unsigned int i = 0; i < count; i++) {
const TableData *data = &async_data[i];
Nan::MaybeLocal<v8::String> jsonStr = Nan::New(data->json);
if (!jsonStr.IsEmpty()) {
Nan::MaybeLocal<v8::Value> jsonVal =
NanJSON.Parse(jsonStr.ToLocalChecked());
if (!jsonVal.IsEmpty()) {
Nan::MaybeLocal<v8::String> decoderName =
Nan::New(data->decoderName);
v8::Local<v8::Value> decoderNameArg;
if (decoderName.IsEmpty())
decoderNameArg = Nan::Null();
else
decoderNameArg = decoderName.ToLocalChecked();
v8::Local<v8::Value> argv[] = {
Nan::New(data->tableId),
decoderNameArg,
jsonVal.ToLocalChecked()
};
m_cb_progress->Call(3, argv);
}
}
}
}
}
void HandleOKCallback() {
Nan::HandleScope scope;
v8::Local<v8::Value> argv[] = {
Nan::Null()
, Nan::New<v8::Number>(m_ret)
};
callback->Call(2, argv);
}
private:
Nan::Callback *m_cb_progress;
Nan::JSON NanJSON;
const AsyncProgressQueueWorker::ExecutionProgress *m_progress;
dvbteeParser* m_obj;
char* m_buf;
unsigned int m_buf_len;
int m_ret;
class Watcher: public dvbtee::decode::TableWatcher {
public:
explicit Watcher(parse& p, const AsyncProgressQueueWorker::ExecutionProgress& progress)
: m_parser(p)
, m_progress(progress) {
m_parser.subscribeTables(this);
}
~Watcher() {
m_parser.subscribeTables(NULL);
}
void updateTable(uint8_t tId, dvbtee::decode::Table *table) {
m_progress.Send(
new TableData(table->getTableid(),
table->getDecoderName(),
table->toJson()), 1
);
}
private:
parse& m_parser;
const AsyncProgressQueueWorker::ExecutionProgress& m_progress;
};
};
void dvbteeParser::feed(const Nan::FunctionCallbackInfo<v8::Value>& info) {
int lastArg = info.Length() - 1;
if ((lastArg >= 1) && (info[lastArg]->IsFunction()) &&
(info[lastArg - 1]->IsFunction())) {
Nan::Callback *progress = new Nan::Callback(
info[lastArg - 1].As<v8::Function>()
);
Nan::Callback *callback = new Nan::Callback(
info[lastArg].As<v8::Function>()
);
Nan::AsyncQueueWorker(new FeedWorker(callback, progress, info));
} else {
info.GetReturnValue().Set(Nan::New(-1));
}
}
<commit_msg>FeedWorker: Watcher takes `this` FeedWorker<commit_after>/*********************************************************************
* node-dvbtee for Node.js
*
* Copyright (c) 2017 Michael Ira Krufky <https://github.com/mkrufky>
*
* MIT License <https://github.com/mkrufky/node-dvbtee/blob/master/LICENSE>
*
* See https://github.com/mkrufky/node-dvbtee for more information
********************************************************************/
#include <nan.h>
#include "dvbtee-parser.h" // NOLINT(build/include)
TableData::TableData(const uint8_t &tableId,
const std::string &decoderName,
const std::string &json)
: tableId(tableId)
, decoderName(decoderName)
, json(json)
{}
TableData::TableData()
: tableId(0)
{}
TableData::TableData(const TableData &t)
: tableId(t.tableId)
, decoderName(t.decoderName)
, json(t.json)
{}
TableData &TableData::operator=(const TableData &cSource) {
if (this == &cSource)
return *this;
tableId = cSource.tableId;
decoderName = cSource.decoderName;
json = cSource.json;
return *this;
}
////////////////////////////////////////
Nan::Persistent<v8::Function> dvbteeParser::constructor;
dvbteeParser::dvbteeParser() {
}
dvbteeParser::~dvbteeParser() {
}
void dvbteeParser::Init(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE exports) {
Nan::HandleScope scope;
v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New);
tpl->SetClassName(Nan::New("Parser").ToLocalChecked());
tpl->InstanceTemplate()->SetInternalFieldCount(1);
Nan::SetPrototypeMethod(tpl, "reset", reset);
Nan::SetPrototypeMethod(tpl, "feed", feed);
Nan::SetPrototypeMethod(tpl, "enableEttCollection", enableEttCollection);
constructor.Reset(tpl->GetFunction());
exports->Set(Nan::New("Parser").ToLocalChecked(), tpl->GetFunction());
}
void dvbteeParser::New(const Nan::FunctionCallbackInfo<v8::Value>& info) {
if (info.IsConstructCall()) {
// Invoked as constructor: `new dvbteeParser(...)`
dvbteeParser* obj = new dvbteeParser();
obj->Wrap(info.This());
info.GetReturnValue().Set(info.This());
} else {
// Invoked as plain function `dvbteeParser(...)`, turn into construct call.
const int argc = 0;
v8::Local<v8::Value> argv[argc] = { };
v8::Local<v8::Function> cons = Nan::New<v8::Function>(constructor);
info.GetReturnValue().Set(cons->NewInstance(argc, argv));
}
}
////////////////////////////////////////
void dvbteeParser::enableEttCollection(
const Nan::FunctionCallbackInfo<v8::Value>& info) {
dvbteeParser* obj = ObjectWrap::Unwrap<dvbteeParser>(info.Holder());
obj->m_parser.enable_ett_collection();
info.GetReturnValue().Set(info.Holder());
}
////////////////////////////////////////
class ResetWorker : public Nan::AsyncWorker {
public:
ResetWorker(Nan::Callback *callback,
const Nan::FunctionCallbackInfo<v8::Value>& info)
: Nan::AsyncWorker(callback) {
m_obj = Nan::ObjectWrap::Unwrap<dvbteeParser>(info.Holder());
}
~ResetWorker() {
}
void Execute () {
m_obj->m_parser.cleanup();
m_obj->m_parser.reset();
}
void HandleOKCallback () {
Nan::HandleScope scope;
v8::Local<v8::Value> argv[] = {
Nan::Null()
, Nan::New<v8::Number>(0)
};
callback->Call(2, argv);
}
private:
dvbteeParser* m_obj;
};
void dvbteeParser::reset(const Nan::FunctionCallbackInfo<v8::Value>& info) {
// If a callback function is supplied, this method will run async
// otherwise, it will run synchronous
int lastArg = info.Length() - 1;
if ((lastArg >= 0) && (info[lastArg]->IsFunction())) {
Nan::Callback *callback = new Nan::Callback(
info[lastArg].As<v8::Function>()
);
Nan::AsyncQueueWorker(new ResetWorker(callback, info));
} else {
dvbteeParser* obj = ObjectWrap::Unwrap<dvbteeParser>(info.Holder());
obj->m_parser.cleanup();
obj->m_parser.reset();
info.GetReturnValue().Set(info.Holder());
}
}
////////////////////////////////////////
class FeedWorker: public Nan::AsyncProgressQueueWorker<TableData> {
public:
FeedWorker(Nan::Callback *callback,
Nan::Callback *progress,
const Nan::FunctionCallbackInfo<v8::Value>& info)
: Nan::AsyncProgressQueueWorker<TableData>(callback)
, m_cb_progress(progress)
, m_buf(NULL)
, m_buf_len(0)
, m_ret(-1) {
m_obj = Nan::ObjectWrap::Unwrap<dvbteeParser>(info.Holder());
if ((info[0]->IsObject()) && (info[1]->IsNumber())) {
const char *key = "buf";
SaveToPersistent(key, info[0]);
Nan::MaybeLocal<v8::Object> mbBuf =
Nan::To<v8::Object>(GetFromPersistent(key));
if (!mbBuf.IsEmpty()) {
m_buf = node::Buffer::Data(mbBuf.ToLocalChecked());
m_buf_len = info[1]->Uint32Value();
}
}
}
~FeedWorker() {
}
void Execute(const AsyncProgressQueueWorker::ExecutionProgress& progress) {
if ((m_buf) && (m_buf_len)) {
Watcher watch(this, progress);
m_ret = m_obj->m_parser.feed(
m_buf_len, reinterpret_cast<uint8_t*>(m_buf)
);
}
if (m_ret < 0) {
SetErrorMessage("invalid buffer / length");
}
}
void HandleProgressCallback(const TableData *async_data, size_t count) {
Nan::HandleScope scope;
if (!m_cb_progress->IsEmpty()) {
for (unsigned int i = 0; i < count; i++) {
const TableData *data = &async_data[i];
Nan::MaybeLocal<v8::String> jsonStr = Nan::New(data->json);
if (!jsonStr.IsEmpty()) {
Nan::MaybeLocal<v8::Value> jsonVal =
NanJSON.Parse(jsonStr.ToLocalChecked());
if (!jsonVal.IsEmpty()) {
Nan::MaybeLocal<v8::String> decoderName =
Nan::New(data->decoderName);
v8::Local<v8::Value> decoderNameArg;
if (decoderName.IsEmpty())
decoderNameArg = Nan::Null();
else
decoderNameArg = decoderName.ToLocalChecked();
v8::Local<v8::Value> argv[] = {
Nan::New(data->tableId),
decoderNameArg,
jsonVal.ToLocalChecked()
};
m_cb_progress->Call(3, argv);
}
}
}
}
}
void HandleOKCallback() {
Nan::HandleScope scope;
v8::Local<v8::Value> argv[] = {
Nan::Null()
, Nan::New<v8::Number>(m_ret)
};
callback->Call(2, argv);
}
private:
Nan::Callback *m_cb_progress;
Nan::JSON NanJSON;
const AsyncProgressQueueWorker::ExecutionProgress *m_progress;
dvbteeParser* m_obj;
char* m_buf;
unsigned int m_buf_len;
int m_ret;
class Watcher: public dvbtee::decode::TableWatcher {
public:
explicit Watcher(FeedWorker* w,
const AsyncProgressQueueWorker::ExecutionProgress& progress)
: m_worker(w)
, m_progress(progress) {
m_worker->m_obj->m_parser.subscribeTables(this);
}
~Watcher() {
m_worker->m_obj->m_parser.subscribeTables(NULL);
}
void updateTable(uint8_t tId, dvbtee::decode::Table *table) {
m_progress.Send(
new TableData(table->getTableid(),
table->getDecoderName(),
table->toJson()), 1
);
}
private:
FeedWorker* m_worker;
const AsyncProgressQueueWorker::ExecutionProgress& m_progress;
};
};
void dvbteeParser::feed(const Nan::FunctionCallbackInfo<v8::Value>& info) {
int lastArg = info.Length() - 1;
if ((lastArg >= 1) && (info[lastArg]->IsFunction()) &&
(info[lastArg - 1]->IsFunction())) {
Nan::Callback *progress = new Nan::Callback(
info[lastArg - 1].As<v8::Function>()
);
Nan::Callback *callback = new Nan::Callback(
info[lastArg].As<v8::Function>()
);
Nan::AsyncQueueWorker(new FeedWorker(callback, progress, info));
} else {
info.GetReturnValue().Set(Nan::New(-1));
}
}
<|endoftext|> |
<commit_before>#include "terminal.h"
/// Sets a newline operator to Terminal output.
Terminal& Terminal::newline(Terminal& term)
{
term.set_ops(Ops::newline);
return *this;
}
/// Sets a newline operator then a flush operator to Terminal output.
Terminal& Terminal::endl(Terminal& term)
{
term.set_ops(Ops::newline);
term.set_ops(Ops::flush);
return *this;
}
/// Sets a flush operator to Terminal output.
Terminal& Terminal::flush(Terminal& term)
{
term.set_ops(Ops::flush);
return *this;
}
/// Sets a general message state operator to Terminal output.
Terminal& Terminal::general(Terminal& term)
{
term.set_ops(Ops::general);
return *this;
}
/// Sets a warning message state operator to Terminal output.
Terminal& Terminal::warning(Terminal& term)
{
term.set_ops(Ops::warning);
return *this;
}
/// Sets a error message state operator to Terminal output.
Terminal& Terminal::error(Terminal& term)
{
term.set_ops(Ops::error);
return *this;
}
// Self-referencing print functions that redirect to output operators.
Terminal& Terminal::print(short n)
{
return *this << n;
}
Terminal& Terminal::print(unsigned short n)
{
return *this << n;
}
Terminal& Terminal::print(int n)
{
return *this << n;
}
Terminal& Terminal::print(unsigned int n)
{
return *this << n;
}
Terminal& Terminal::print(long n)
{
return *this << n;
}
Terminal& Terminal::print(unsigned long n)
{
return *this << n;
}
Terminal& Terminal::print(float n)
{
return *this << n;
}
Terminal& Terminal::print(double n)
{
return *this << n;
}
Terminal& Terminal::print(const char* n)
{
return *this << n;
}
Terminal& Terminal::print(const std::string& n)
{
return *this << n;
}
Terminal& Terminal::operator<<(Terminal& (*pf)(Terminal&))
{
return pf(*this);
}
<commit_msg>Fixed terminal class.<commit_after>#include "terminal.h"
/// Sets a newline operator to Terminal output.
Terminal& Terminal::newline(Terminal& term)
{
term.set_ops(Ops::newline);
}
/// Sets a newline operator then a flush operator to Terminal output.
Terminal& Terminal::endl(Terminal& term)
{
term.set_ops(Ops::newline);
term.set_ops(Ops::flush);
}
/// Sets a flush operator to Terminal output.
Terminal& Terminal::flush(Terminal& term)
{
term.set_ops(Ops::flush);
}
/// Sets a general message state operator to Terminal output.
Terminal& Terminal::general(Terminal& term)
{
term.set_ops(Ops::general);
}
/// Sets a warning message state operator to Terminal output.
Terminal& Terminal::warning(Terminal& term)
{
term.set_ops(Ops::warning);
}
/// Sets a error message state operator to Terminal output.
Terminal& Terminal::error(Terminal& term)
{
term.set_ops(Ops::error);
}
// Self-referencing print functions that redirect to output operators.
Terminal& Terminal::print(short n)
{
return *this << n;
}
Terminal& Terminal::print(unsigned short n)
{
return *this << n;
}
Terminal& Terminal::print(int n)
{
return *this << n;
}
Terminal& Terminal::print(unsigned int n)
{
return *this << n;
}
Terminal& Terminal::print(long n)
{
return *this << n;
}
Terminal& Terminal::print(unsigned long n)
{
return *this << n;
}
Terminal& Terminal::print(float n)
{
return *this << n;
}
Terminal& Terminal::print(double n)
{
return *this << n;
}
Terminal& Terminal::print(const char* n)
{
return *this << n;
}
Terminal& Terminal::print(const std::string& n)
{
return *this << n;
}
Terminal& Terminal::operator<<(Terminal& (*pf)(Terminal&))
{
return pf(*this);
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "after_initialization_fixture.h"
#include "test/testsupport/fileutils.h"
namespace {
const int kSampleRateHz = 16000;
const int kTestDurationMs = 1000;
const int16_t kInputValue = 15000;
const int16_t kSilenceValue = 0;
} // namespace
class FileBeforeStreamingTest : public AfterInitializationFixture {
protected:
FileBeforeStreamingTest()
: input_filename_(webrtc::test::OutputPath() + "file_test_input.pcm"),
output_filename_(webrtc::test::OutputPath() + "file_test_output.pcm") {
}
void SetUp() {
channel_ = voe_base_->CreateChannel();
}
void TearDown() {
voe_base_->DeleteChannel(channel_);
}
// TODO(andrew): consolidate below methods in a shared place?
// Generate input file with constant values as |kInputValue|. The file
// will be one second longer than the duration of the test.
void GenerateInputFile() {
FILE* input_file = fopen(input_filename_.c_str(), "wb");
ASSERT_TRUE(input_file != NULL);
for (int i = 0; i < kSampleRateHz / 1000 * (kTestDurationMs + 1000); i++) {
ASSERT_EQ(1u, fwrite(&kInputValue, sizeof(kInputValue), 1, input_file));
}
ASSERT_EQ(0, fclose(input_file));
}
void RecordOutput() {
// Start recording the mixed output for |kTestDurationMs| long.
EXPECT_EQ(0, voe_file_->StartRecordingPlayout(-1,
output_filename_.c_str()));
Sleep(kTestDurationMs);
EXPECT_EQ(0, voe_file_->StopRecordingPlayout(-1));
}
void VerifyOutput(int16_t target_value) {
FILE* output_file = fopen(output_filename_.c_str(), "rb");
ASSERT_TRUE(output_file != NULL);
int16_t output_value = 0;
int samples_read = 0;
while (fread(&output_value, sizeof(output_value), 1, output_file) == 1) {
samples_read++;
EXPECT_EQ(output_value, target_value);
}
// Ensure the recording length is close to the duration of the test.
ASSERT_GE((samples_read * 1000.0) / kSampleRateHz, 0.9 * kTestDurationMs);
// Ensure we read the entire file.
ASSERT_NE(0, feof(output_file));
ASSERT_EQ(0, fclose(output_file));
}
void VerifyEmptyOutput() {
FILE* output_file = fopen(output_filename_.c_str(), "rb");
ASSERT_TRUE(output_file != NULL);
ASSERT_EQ(0, fseek(output_file, 0, SEEK_END));
EXPECT_EQ(0, ftell(output_file));
ASSERT_EQ(0, fclose(output_file));
}
int channel_;
const std::string input_filename_;
const std::string output_filename_;
};
// This test case is to ensure that StartPlayingFileLocally() and
// StartPlayout() can be called in any order.
// A DC signal is used as input. And the output of mixer is supposed to be:
// 1. the same DC signal if file is played out,
// 2. total silence if file is not played out,
// 3. no output if playout is not started.
TEST_F(FileBeforeStreamingTest,
DISABLED_TestStartPlayingFileLocallyWithStartPlayout) {
GenerateInputFile();
TEST_LOG("Playout is not started. File will not be played out.\n");
EXPECT_EQ(0, voe_file_->StartPlayingFileLocally(
channel_, input_filename_.c_str(), true));
EXPECT_EQ(1, voe_file_->IsPlayingFileLocally(channel_));
RecordOutput();
VerifyEmptyOutput();
TEST_LOG("Playout is now started. File will be played out.\n");
EXPECT_EQ(0, voe_base_->StartPlayout(channel_));
RecordOutput();
VerifyOutput(kInputValue);
TEST_LOG("Stop playing file. Only silence will be played out.\n");
EXPECT_EQ(0, voe_file_->StopPlayingFileLocally(channel_));
EXPECT_EQ(0, voe_file_->IsPlayingFileLocally(channel_));
RecordOutput();
VerifyOutput(kSilenceValue);
TEST_LOG("Start playing file again. File will be played out.\n");
EXPECT_EQ(0, voe_file_->StartPlayingFileLocally(
channel_, input_filename_.c_str(), true));
EXPECT_EQ(1, voe_file_->IsPlayingFileLocally(channel_));
RecordOutput();
VerifyOutput(kInputValue);
EXPECT_EQ(0, voe_base_->StopPlayout(channel_));
EXPECT_EQ(0, voe_file_->StopPlayingFileLocally(channel_));
}
<commit_msg>Fix the flakiness in FileBeforeStreamingTest<commit_after>/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "after_initialization_fixture.h"
#include "test/testsupport/fileutils.h"
namespace {
const int kSampleRateHz = 16000;
const int kTestDurationMs = 1000;
const int kSkipOutputMs = 50;
const int16_t kInputValue = 15000;
const int16_t kSilenceValue = 0;
} // namespace
class FileBeforeStreamingTest : public AfterInitializationFixture {
protected:
FileBeforeStreamingTest()
: input_filename_(webrtc::test::OutputPath() + "file_test_input.pcm"),
output_filename_(webrtc::test::OutputPath() + "file_test_output.pcm") {
}
void SetUp() {
channel_ = voe_base_->CreateChannel();
}
void TearDown() {
voe_base_->DeleteChannel(channel_);
}
// TODO(andrew): consolidate below methods in a shared place?
// Generate input file with constant values as |kInputValue|. The file
// will be one second longer than the duration of the test.
void GenerateInputFile() {
FILE* input_file = fopen(input_filename_.c_str(), "wb");
ASSERT_TRUE(input_file != NULL);
for (int i = 0; i < kSampleRateHz / 1000 * (kTestDurationMs + 1000); i++) {
ASSERT_EQ(1u, fwrite(&kInputValue, sizeof(kInputValue), 1, input_file));
}
ASSERT_EQ(0, fclose(input_file));
}
void RecordOutput() {
// Start recording the mixed output for |kTestDurationMs| long.
EXPECT_EQ(0, voe_file_->StartRecordingPlayout(-1,
output_filename_.c_str()));
Sleep(kTestDurationMs);
EXPECT_EQ(0, voe_file_->StopRecordingPlayout(-1));
}
void VerifyOutput(int16_t target_value) {
FILE* output_file = fopen(output_filename_.c_str(), "rb");
ASSERT_TRUE(output_file != NULL);
int16_t output_value = 0;
int samples_read = 0;
// Skip the first segment to avoid initialization and ramping-in effects.
EXPECT_EQ(0, fseek(output_file, sizeof(output_value) *
kSampleRateHz / 1000 * kSkipOutputMs, SEEK_SET));
while (fread(&output_value, sizeof(output_value), 1, output_file) == 1) {
samples_read++;
EXPECT_EQ(output_value, target_value);
}
// Ensure the recording length is close to the duration of the test.
ASSERT_GE((samples_read * 1000.0) / kSampleRateHz, 0.9 * kTestDurationMs);
// Ensure we read the entire file.
ASSERT_NE(0, feof(output_file));
ASSERT_EQ(0, fclose(output_file));
}
void VerifyEmptyOutput() {
FILE* output_file = fopen(output_filename_.c_str(), "rb");
ASSERT_TRUE(output_file != NULL);
ASSERT_EQ(0, fseek(output_file, 0, SEEK_END));
EXPECT_EQ(0, ftell(output_file));
ASSERT_EQ(0, fclose(output_file));
}
int channel_;
const std::string input_filename_;
const std::string output_filename_;
};
// This test case is to ensure that StartPlayingFileLocally() and
// StartPlayout() can be called in any order.
// A DC signal is used as input. And the output of mixer is supposed to be:
// 1. the same DC signal if file is played out,
// 2. total silence if file is not played out,
// 3. no output if playout is not started.
TEST_F(FileBeforeStreamingTest, TestStartPlayingFileLocallyWithStartPlayout) {
GenerateInputFile();
TEST_LOG("Playout is not started. File will not be played out.\n");
EXPECT_EQ(0, voe_file_->StartPlayingFileLocally(
channel_, input_filename_.c_str(), true));
EXPECT_EQ(1, voe_file_->IsPlayingFileLocally(channel_));
RecordOutput();
VerifyEmptyOutput();
TEST_LOG("Playout is now started. File will be played out.\n");
EXPECT_EQ(0, voe_base_->StartPlayout(channel_));
RecordOutput();
VerifyOutput(kInputValue);
TEST_LOG("Stop playing file. Only silence will be played out.\n");
EXPECT_EQ(0, voe_file_->StopPlayingFileLocally(channel_));
EXPECT_EQ(0, voe_file_->IsPlayingFileLocally(channel_));
RecordOutput();
VerifyOutput(kSilenceValue);
TEST_LOG("Start playing file again. File will be played out.\n");
EXPECT_EQ(0, voe_file_->StartPlayingFileLocally(
channel_, input_filename_.c_str(), true));
EXPECT_EQ(1, voe_file_->IsPlayingFileLocally(channel_));
RecordOutput();
VerifyOutput(kInputValue);
EXPECT_EQ(0, voe_base_->StopPlayout(channel_));
EXPECT_EQ(0, voe_file_->StopPlayingFileLocally(channel_));
}
<|endoftext|> |
<commit_before>/**
* Derived from this blog post:
* http://simmesimme.github.io/tutorials/2015/09/20/signal-slot
*/
#ifndef SIGNAL_HPP
#define SIGNAL_HPP
#include <functional>
#include <map>
// A signal object may call multiple slots with the
// same signature. You can connect functions to the signal
// which will be called when the emit() method on the
// signal object is invoked. Any argument passed to emit()
// will be passed to the given functions.
template <typename... Args> class Signal {
public:
Signal() : current_id_(0) {}
// copy creates new signal
Signal(Signal const &other) : current_id_(0) {}
// connects a member function to this Signal
template <typename T> int ConnectMember(T *inst, void (T::*func)(Args...)) {
return Connect([=](Args... args) { (inst->*func)(args...); });
}
// connects a member function to this Signal
template <typename T>
int ConnectMember(std::shared_ptr<T> inst, void (T::*func)(Args...)) {
return Connect([=](Args... args) { ((*inst).*func)(args...); });
}
// connects a const member function to this Signal
template <typename T>
int ConnectMember(T *inst, void (T::*func)(Args...) const) {
return Connect([=](Args... args) { (inst->*func)(args...); });
}
// connects a std::function to the signal. The returned
// value can be used to disconnect the function again
int Connect(std::function<void(Args...)> const &slot) const {
slots_.insert(std::make_pair(++current_id_, slot));
return current_id_;
}
// disconnects a previously connected function
void Disconnect(int id) const { slots_.erase(id); }
// disconnects all previously connected functions
void DisconnectAll() const { slots_.clear(); }
// calls all connected functions
void Emit(Args... p) {
for (auto it : slots_) {
it.second(p...);
}
}
// assignment creates new Signal
Signal &operator=(Signal const &other) { DisconnectAll(); }
private:
mutable std::map<int, std::function<void(Args...)>> slots_;
mutable int current_id_;
};
#endif /* SIGNAL_HPP */<commit_msg>removed unneeded Signal::ConnectMember function<commit_after>/**
* Derived from this blog post:
* http://simmesimme.github.io/tutorials/2015/09/20/signal-slot
*/
#ifndef SIGNAL_HPP
#define SIGNAL_HPP
#include <functional>
#include <map>
// A signal object may call multiple slots with the
// same signature. You can connect functions to the signal
// which will be called when the emit() method on the
// signal object is invoked. Any argument passed to emit()
// will be passed to the given functions.
template <typename... Args> class Signal {
public:
Signal() : current_id_(0) {}
// copy creates new signal
Signal(Signal const &other) : current_id_(0) {}
// connects a member function to this Signal
template <typename T> int ConnectMember(T *inst, void (T::*func)(Args...)) {
return Connect([=](Args... args) { (inst->*func)(args...); });
}
// connects a const member function to this Signal
template <typename T>
int ConnectMember(T *inst, void (T::*func)(Args...) const) {
return Connect([=](Args... args) { (inst->*func)(args...); });
}
// connects a std::function to the signal. The returned
// value can be used to disconnect the function again
int Connect(std::function<void(Args...)> const &slot) const {
slots_.insert(std::make_pair(++current_id_, slot));
return current_id_;
}
// disconnects a previously connected function
void Disconnect(int id) const { slots_.erase(id); }
// disconnects all previously connected functions
void DisconnectAll() const { slots_.clear(); }
// calls all connected functions
void Emit(Args... p) {
for (auto it : slots_) {
it.second(p...);
}
}
// assignment creates new Signal
Signal &operator=(Signal const &other) { DisconnectAll(); }
private:
mutable std::map<int, std::function<void(Args...)>> slots_;
mutable int current_id_;
};
#endif /* SIGNAL_HPP */<|endoftext|> |
<commit_before>// Copyright 2010-2013 RethinkDB, all rights reserved.
#ifndef EXTPROC_POOL_HPP_
#define EXTPROC_POOL_HPP_
#include <sys/types.h> // pid_t
#include "errors.hpp"
#include "concurrency/one_per_thread.hpp"
#include "concurrency/semaphore.hpp"
#include "concurrency/signal.hpp"
#include "containers/archive/interruptible_stream.hpp"
#include "containers/archive/socket_stream.hpp"
#include "containers/intrusive_list.hpp"
#include "extproc/job.hpp"
#include "extproc/spawner.hpp"
namespace extproc {
class job_handle_t;
class pool_t;
// Use this to create one process pool per thread, and access the appropriate
// one (via `get()`).
class pool_group_t {
friend class pool_t;
public:
static const int DEFAULT_MIN_WORKERS = 2;
static const int DEFAULT_MAX_WORKERS = 2;
struct config_t {
config_t()
: min_workers(DEFAULT_MIN_WORKERS), max_workers(DEFAULT_MAX_WORKERS) {}
int min_workers; // >= 0
int max_workers; // >= min_workers, > 0
};
static const config_t DEFAULTS;
pool_group_t(spawner_info_t *info, const config_t &config);
pool_t *get() { return pool_maker_.get(); }
private:
spawner_t spawner_;
config_t config_;
one_per_thread_t<pool_t> pool_maker_;
};
// A worker process.
class pool_worker_t : public intrusive_list_node_t<pool_worker_t> {
friend class job_handle_t;
public:
pool_worker_t(pool_t *pool, pid_t pid, scoped_fd_t *fd);
~pool_worker_t();
// Called when we get an error on a worker process socket, which usually
// indicates the worker process' death.
void on_error();
// Inherited from unix_socket_stream_t. Called when epoll finds an error
// condition on our socket. Calls on_error().
virtual void do_on_event(int events);
unix_socket_stream_t unix_socket;
private:
friend class pool_t;
pool_t *const pool_;
const pid_t pid_;
bool attached_;
DISABLE_COPYING(pool_worker_t);
};
// A per-thread worker pool.
class pool_t : public home_thread_mixin_debug_only_t {
public:
explicit pool_t(pool_group_t *group);
~pool_t();
private:
friend class job_handle_t;
pool_group_t::config_t *config() { return &group_->config_; }
spawner_t *spawner() { return &group_->spawner_; }
private:
// Checks & repairs invariants, namely:
// - num_workers() >= config()->min_workers
void repair_invariants();
// Connects us to a worker. Private; used only by job_handle_t::spawn().
pool_worker_t *acquire_worker();
// Called by job_handle_t to indicate the job has finished or errored.
void release_worker(pool_worker_t *worker) THROWS_NOTHING;
// Called by job_handle_t to interrupt a running job.
void interrupt_worker(pool_worker_t *worker) THROWS_NOTHING;
// Detaches the worker from the pool, sends it SIGKILL, and ignores further
// errors from it (ie. on_event will not call on_error, and hence will not
// crash). Does not block.
//
// This is used by the interruptor-signal logic in
// job_handle_t::{read,write}_interruptible(), where interrupt_worker()
// cannot be used because it destroys the worker.
//
// It is the caller's responsibility to call cleanup_detached_worker() at
// some point in the near future.
void detach_worker(pool_worker_t *worker);
// Cleans up after a detached worker. Destroys the worker. May block.
void cleanup_detached_worker(pool_worker_t *worker);
void spawn_workers(int n);
void end_worker(intrusive_list_t<pool_worker_t> *list, pool_worker_t *worker);
int num_workers() {
return idle_workers_.size() + busy_workers_.size() + num_spawning_workers_;
}
private:
pool_group_t *group_;
// Worker processes.
intrusive_list_t<pool_worker_t> idle_workers_;
intrusive_list_t<pool_worker_t> busy_workers_;
// Count of the number of workers in the process of being spawned. Necessary
// in order to maintain (min_workers, max_workers) bounds without race
// conditions.
int num_spawning_workers_;
// Used to signify that you're using a worker. In particular, lets us block
// for a worker to become available when we already have
// config_->max_workers workers running.
semaphore_t worker_semaphore_;
};
// A handle to a running job.
class job_handle_t : public interruptible_read_stream_t, public interruptible_write_stream_t {
public:
// When constructed, job handles are "disconnected", not associated with a
// job. They are connected by pool_t::spawn_job().
job_handle_t();
// You MUST call release() to finish a job normally, and you SHOULD call
// interrupt() explicitly to interrupt a job (or signal the interruptor
// during {read,write}_interruptible()).
//
// However, as a convenience in the case of exception-raising code, if the
// handle is connected, the destructor will log a warning and interrupt the
// job.
virtual ~job_handle_t();
bool connected() { return NULL != worker_; }
// Begins running `job` on `pool`. Must be disconnected beforehand. On
// success, returns 0 and connects us to the spawned job. Returns -1 on
// error.
int begin(pool_t *pool, const job_t &job);
// Indicates the job has either finished normally or experienced an I/O
// error; disconnects the job handle.
void release() THROWS_NOTHING;
// Forcibly interrupts a running job; disconnects the job handle.
//
// MAY NOT be called concurrently with any I/O methods. Instead, pass a
// signal to {read,write}_interruptible().
void interrupt() THROWS_NOTHING;
// On either read or write error or interruption, the job handle becomes
// disconnected and must not be used.
virtual MUST_USE int64_t read_interruptible(void *p, int64_t n, signal_t *interruptor);
virtual int64_t write_interruptible(const void *p, int64_t n, signal_t *interruptor);
private:
friend class pool_t;
friend class interruptor_wrapper_t;
void check_attached();
class interruptor_wrapper_t : public signal_t, public signal_t::subscription_t {
public:
interruptor_wrapper_t(job_handle_t *handle, signal_t *signal);
virtual void run() THROWS_NOTHING;
job_handle_t *handle_;
};
pool_worker_t *worker_;
DISABLE_COPYING(job_handle_t);
};
} // namespace extproc
#endif // EXTPROC_POOL_HPP_
<commit_msg>Added DISABLE_COPYINGs in pool.hpp.<commit_after>// Copyright 2010-2013 RethinkDB, all rights reserved.
#ifndef EXTPROC_POOL_HPP_
#define EXTPROC_POOL_HPP_
#include <sys/types.h> // pid_t
#include "errors.hpp"
#include "concurrency/one_per_thread.hpp"
#include "concurrency/semaphore.hpp"
#include "concurrency/signal.hpp"
#include "containers/archive/interruptible_stream.hpp"
#include "containers/archive/socket_stream.hpp"
#include "containers/intrusive_list.hpp"
#include "extproc/job.hpp"
#include "extproc/spawner.hpp"
namespace extproc {
class job_handle_t;
class pool_t;
// Use this to create one process pool per thread, and access the appropriate
// one (via `get()`).
class pool_group_t {
friend class pool_t;
public:
static const int DEFAULT_MIN_WORKERS = 2;
static const int DEFAULT_MAX_WORKERS = 2;
struct config_t {
config_t()
: min_workers(DEFAULT_MIN_WORKERS), max_workers(DEFAULT_MAX_WORKERS) {}
int min_workers; // >= 0
int max_workers; // >= min_workers, > 0
};
static const config_t DEFAULTS;
pool_group_t(spawner_info_t *info, const config_t &config);
pool_t *get() { return pool_maker_.get(); }
private:
spawner_t spawner_;
config_t config_;
one_per_thread_t<pool_t> pool_maker_;
DISABLE_COPYING(pool_group_t);
};
// A worker process.
class pool_worker_t : public intrusive_list_node_t<pool_worker_t> {
friend class job_handle_t;
public:
pool_worker_t(pool_t *pool, pid_t pid, scoped_fd_t *fd);
~pool_worker_t();
// Called when we get an error on a worker process socket, which usually
// indicates the worker process' death.
void on_error();
// Inherited from unix_socket_stream_t. Called when epoll finds an error
// condition on our socket. Calls on_error().
virtual void do_on_event(int events);
unix_socket_stream_t unix_socket;
private:
friend class pool_t;
pool_t *const pool_;
const pid_t pid_;
bool attached_;
DISABLE_COPYING(pool_worker_t);
};
// A per-thread worker pool.
class pool_t : public home_thread_mixin_debug_only_t {
public:
explicit pool_t(pool_group_t *group);
~pool_t();
private:
friend class job_handle_t;
pool_group_t::config_t *config() { return &group_->config_; }
spawner_t *spawner() { return &group_->spawner_; }
private:
// Checks & repairs invariants, namely:
// - num_workers() >= config()->min_workers
void repair_invariants();
// Connects us to a worker. Private; used only by job_handle_t::spawn().
pool_worker_t *acquire_worker();
// Called by job_handle_t to indicate the job has finished or errored.
void release_worker(pool_worker_t *worker) THROWS_NOTHING;
// Called by job_handle_t to interrupt a running job.
void interrupt_worker(pool_worker_t *worker) THROWS_NOTHING;
// Detaches the worker from the pool, sends it SIGKILL, and ignores further
// errors from it (ie. on_event will not call on_error, and hence will not
// crash). Does not block.
//
// This is used by the interruptor-signal logic in
// job_handle_t::{read,write}_interruptible(), where interrupt_worker()
// cannot be used because it destroys the worker.
//
// It is the caller's responsibility to call cleanup_detached_worker() at
// some point in the near future.
void detach_worker(pool_worker_t *worker);
// Cleans up after a detached worker. Destroys the worker. May block.
void cleanup_detached_worker(pool_worker_t *worker);
void spawn_workers(int n);
void end_worker(intrusive_list_t<pool_worker_t> *list, pool_worker_t *worker);
int num_workers() const {
return idle_workers_.size() + busy_workers_.size() + num_spawning_workers_;
}
private:
pool_group_t *group_;
// Worker processes.
intrusive_list_t<pool_worker_t> idle_workers_;
intrusive_list_t<pool_worker_t> busy_workers_;
// Count of the number of workers in the process of being spawned. Necessary
// in order to maintain (min_workers, max_workers) bounds without race
// conditions.
int num_spawning_workers_;
// Used to signify that you're using a worker. In particular, lets us block
// for a worker to become available when we already have
// config_->max_workers workers running.
semaphore_t worker_semaphore_;
DISABLE_COPYING(pool_t);
};
// A handle to a running job.
class job_handle_t : public interruptible_read_stream_t, public interruptible_write_stream_t {
public:
// When constructed, job handles are "disconnected", not associated with a
// job. They are connected by pool_t::spawn_job().
job_handle_t();
// You MUST call release() to finish a job normally, and you SHOULD call
// interrupt() explicitly to interrupt a job (or signal the interruptor
// during {read,write}_interruptible()).
//
// However, as a convenience in the case of exception-raising code, if the
// handle is connected, the destructor will log a warning and interrupt the
// job.
virtual ~job_handle_t();
bool connected() { return NULL != worker_; }
// Begins running `job` on `pool`. Must be disconnected beforehand. On
// success, returns 0 and connects us to the spawned job. Returns -1 on
// error.
int begin(pool_t *pool, const job_t &job);
// Indicates the job has either finished normally or experienced an I/O
// error; disconnects the job handle.
void release() THROWS_NOTHING;
// Forcibly interrupts a running job; disconnects the job handle.
//
// MAY NOT be called concurrently with any I/O methods. Instead, pass a
// signal to {read,write}_interruptible().
void interrupt() THROWS_NOTHING;
// On either read or write error or interruption, the job handle becomes
// disconnected and must not be used.
virtual MUST_USE int64_t read_interruptible(void *p, int64_t n, signal_t *interruptor);
virtual int64_t write_interruptible(const void *p, int64_t n, signal_t *interruptor);
private:
friend class pool_t;
friend class interruptor_wrapper_t;
void check_attached();
class interruptor_wrapper_t : public signal_t, public signal_t::subscription_t {
public:
interruptor_wrapper_t(job_handle_t *handle, signal_t *signal);
virtual void run() THROWS_NOTHING;
job_handle_t *handle_;
};
pool_worker_t *worker_;
DISABLE_COPYING(job_handle_t);
};
} // namespace extproc
#endif // EXTPROC_POOL_HPP_
<|endoftext|> |
<commit_before>// Copyright 2013 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.
//
// Library for preprocessing fonts as part of the WOFF 2.0 conversion.
#include "./transform.h"
#include <complex> // for std::abs
#include "./buffer.h"
#include "./font.h"
#include "./glyph.h"
#include "./table_tags.h"
#include "./variable_length.h"
namespace woff2 {
namespace {
const int FLAG_ARG_1_AND_2_ARE_WORDS = 1 << 0;
const int FLAG_WE_HAVE_INSTRUCTIONS = 1 << 8;
void WriteBytes(std::vector<uint8_t>* out, const uint8_t* data, size_t len) {
if (len == 0) return;
size_t offset = out->size();
out->resize(offset + len);
memcpy(&(*out)[offset], data, len);
}
void WriteBytes(std::vector<uint8_t>* out, const std::vector<uint8_t>& in) {
for (int i = 0; i < in.size(); ++i) {
out->push_back(in[i]);
}
}
void WriteUShort(std::vector<uint8_t>* out, int value) {
out->push_back(value >> 8);
out->push_back(value & 255);
}
void WriteLong(std::vector<uint8_t>* out, int value) {
out->push_back((value >> 24) & 255);
out->push_back((value >> 16) & 255);
out->push_back((value >> 8) & 255);
out->push_back(value & 255);
}
// Glyf table preprocessing, based on
// GlyfEncoder.java
class GlyfEncoder {
public:
explicit GlyfEncoder(int num_glyphs)
: n_glyphs_(num_glyphs) {
bbox_bitmap_.resize(((num_glyphs + 31) >> 5) << 2);
}
bool Encode(int glyph_id, const Glyph& glyph) {
if (glyph.composite_data_size > 0) {
WriteCompositeGlyph(glyph_id, glyph);
} else if (glyph.contours.size() > 0) {
WriteSimpleGlyph(glyph_id, glyph);
} else {
WriteUShort(&n_contour_stream_, 0);
}
return true;
}
void GetTransformedGlyfBytes(std::vector<uint8_t>* result) {
WriteLong(result, 0); // version
WriteUShort(result, n_glyphs_);
WriteUShort(result, 0); // index_format, will be set later
WriteLong(result, n_contour_stream_.size());
WriteLong(result, n_points_stream_.size());
WriteLong(result, flag_byte_stream_.size());
WriteLong(result, glyph_stream_.size());
WriteLong(result, composite_stream_.size());
WriteLong(result, bbox_bitmap_.size() + bbox_stream_.size());
WriteLong(result, instruction_stream_.size());
WriteBytes(result, n_contour_stream_);
WriteBytes(result, n_points_stream_);
WriteBytes(result, flag_byte_stream_);
WriteBytes(result, glyph_stream_);
WriteBytes(result, composite_stream_);
WriteBytes(result, bbox_bitmap_);
WriteBytes(result, bbox_stream_);
WriteBytes(result, instruction_stream_);
}
private:
void WriteInstructions(const Glyph& glyph) {
Write255UShort(&glyph_stream_, glyph.instructions_size);
WriteBytes(&instruction_stream_,
glyph.instructions_data, glyph.instructions_size);
}
bool ShouldWriteSimpleGlyphBbox(const Glyph& glyph) {
if (glyph.contours.empty() || glyph.contours[0].empty()) {
return glyph.x_min || glyph.y_min || glyph.x_max || glyph.y_max;
}
int16_t x_min = glyph.contours[0][0].x;
int16_t y_min = glyph.contours[0][0].y;
int16_t x_max = x_min;
int16_t y_max = y_min;
for (const auto& contour : glyph.contours) {
for (const auto& point : contour) {
if (point.x < x_min) x_min = point.x;
if (point.x > x_max) x_max = point.x;
if (point.y < y_min) y_min = point.y;
if (point.y > y_max) y_max = point.y;
}
}
if (glyph.x_min != x_min)
return true;
if (glyph.y_min != y_min)
return true;
if (glyph.x_max != x_max)
return true;
if (glyph.y_max != y_max)
return true;
return false;
}
void WriteSimpleGlyph(int glyph_id, const Glyph& glyph) {
int num_contours = glyph.contours.size();
WriteUShort(&n_contour_stream_, num_contours);
if (ShouldWriteSimpleGlyphBbox(glyph)) {
WriteBbox(glyph_id, glyph);
}
// TODO: check that bbox matches, write bbox if not
for (int i = 0; i < num_contours; i++) {
Write255UShort(&n_points_stream_, glyph.contours[i].size());
}
int lastX = 0;
int lastY = 0;
for (int i = 0; i < num_contours; i++) {
int num_points = glyph.contours[i].size();
for (int j = 0; j < num_points; j++) {
int x = glyph.contours[i][j].x;
int y = glyph.contours[i][j].y;
int dx = x - lastX;
int dy = y - lastY;
WriteTriplet(glyph.contours[i][j].on_curve, dx, dy);
lastX = x;
lastY = y;
}
}
if (num_contours > 0) {
WriteInstructions(glyph);
}
}
void WriteCompositeGlyph(int glyph_id, const Glyph& glyph) {
WriteUShort(&n_contour_stream_, -1);
WriteBbox(glyph_id, glyph);
WriteBytes(&composite_stream_,
glyph.composite_data,
glyph.composite_data_size);
if (glyph.have_instructions) {
WriteInstructions(glyph);
}
}
void WriteBbox(int glyph_id, const Glyph& glyph) {
bbox_bitmap_[glyph_id >> 3] |= 0x80 >> (glyph_id & 7);
WriteUShort(&bbox_stream_, glyph.x_min);
WriteUShort(&bbox_stream_, glyph.y_min);
WriteUShort(&bbox_stream_, glyph.x_max);
WriteUShort(&bbox_stream_, glyph.y_max);
}
void WriteTriplet(bool on_curve, int x, int y) {
int abs_x = std::abs(x);
int abs_y = std::abs(y);
int on_curve_bit = on_curve ? 0 : 128;
int x_sign_bit = (x < 0) ? 0 : 1;
int y_sign_bit = (y < 0) ? 0 : 1;
int xy_sign_bits = x_sign_bit + 2 * y_sign_bit;
if (x == 0 && abs_y < 1280) {
flag_byte_stream_.push_back(on_curve_bit +
((abs_y & 0xf00) >> 7) + y_sign_bit);
glyph_stream_.push_back(abs_y & 0xff);
} else if (y == 0 && abs_x < 1280) {
flag_byte_stream_.push_back(on_curve_bit + 10 +
((abs_x & 0xf00) >> 7) + x_sign_bit);
glyph_stream_.push_back(abs_x & 0xff);
} else if (abs_x < 65 && abs_y < 65) {
flag_byte_stream_.push_back(on_curve_bit + 20 +
((abs_x - 1) & 0x30) +
(((abs_y - 1) & 0x30) >> 2) +
xy_sign_bits);
glyph_stream_.push_back((((abs_x - 1) & 0xf) << 4) | ((abs_y - 1) & 0xf));
} else if (abs_x < 769 && abs_y < 769) {
flag_byte_stream_.push_back(on_curve_bit + 84 +
12 * (((abs_x - 1) & 0x300) >> 8) +
(((abs_y - 1) & 0x300) >> 6) + xy_sign_bits);
glyph_stream_.push_back((abs_x - 1) & 0xff);
glyph_stream_.push_back((abs_y - 1) & 0xff);
} else if (abs_x < 4096 && abs_y < 4096) {
flag_byte_stream_.push_back(on_curve_bit + 120 + xy_sign_bits);
glyph_stream_.push_back(abs_x >> 4);
glyph_stream_.push_back(((abs_x & 0xf) << 4) | (abs_y >> 8));
glyph_stream_.push_back(abs_y & 0xff);
} else {
flag_byte_stream_.push_back(on_curve_bit + 124 + xy_sign_bits);
glyph_stream_.push_back(abs_x >> 8);
glyph_stream_.push_back(abs_x & 0xff);
glyph_stream_.push_back(abs_y >> 8);
glyph_stream_.push_back(abs_y & 0xff);
}
}
std::vector<uint8_t> n_contour_stream_;
std::vector<uint8_t> n_points_stream_;
std::vector<uint8_t> flag_byte_stream_;
std::vector<uint8_t> composite_stream_;
std::vector<uint8_t> bbox_bitmap_;
std::vector<uint8_t> bbox_stream_;
std::vector<uint8_t> glyph_stream_;
std::vector<uint8_t> instruction_stream_;
int n_glyphs_;
};
} // namespace
bool TransformGlyfAndLocaTables(Font* font) {
// no transform for CFF
const Font::Table* glyf_table = font->FindTable(kGlyfTableTag);
const Font::Table* loca_table = font->FindTable(kLocaTableTag);
if (font->FindTable(kCffTableTag) != NULL
&& glyf_table == NULL
&& loca_table == NULL) {
return true;
}
// Must share neither or both loca/glyf
if (glyf_table->IsReused() != loca_table->IsReused()) {
return FONT_COMPRESSION_FAILURE();
}
if (glyf_table->IsReused()) {
return true;
}
Font::Table* transformed_glyf = &font->tables[kGlyfTableTag ^ 0x80808080];
Font::Table* transformed_loca = &font->tables[kLocaTableTag ^ 0x80808080];
int num_glyphs = NumGlyphs(*font);
GlyfEncoder encoder(num_glyphs);
for (int i = 0; i < num_glyphs; ++i) {
Glyph glyph;
const uint8_t* glyph_data;
size_t glyph_size;
if (!GetGlyphData(*font, i, &glyph_data, &glyph_size) ||
(glyph_size > 0 && !ReadGlyph(glyph_data, glyph_size, &glyph))) {
return FONT_COMPRESSION_FAILURE();
}
encoder.Encode(i, glyph);
}
encoder.GetTransformedGlyfBytes(&transformed_glyf->buffer);
const Font::Table* head_table = font->FindTable(kHeadTableTag);
if (head_table == NULL || head_table->length < 52) {
return FONT_COMPRESSION_FAILURE();
}
transformed_glyf->buffer[7] = head_table->data[51]; // index_format
transformed_glyf->tag = kGlyfTableTag ^ 0x80808080;
transformed_glyf->length = transformed_glyf->buffer.size();
transformed_glyf->data = transformed_glyf->buffer.data();
transformed_loca->tag = kLocaTableTag ^ 0x80808080;
transformed_loca->length = 0;
transformed_loca->data = NULL;
return true;
}
} // namespace woff2
<commit_msg>remove comment that has been addressed<commit_after>// Copyright 2013 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.
//
// Library for preprocessing fonts as part of the WOFF 2.0 conversion.
#include "./transform.h"
#include <complex> // for std::abs
#include "./buffer.h"
#include "./font.h"
#include "./glyph.h"
#include "./table_tags.h"
#include "./variable_length.h"
namespace woff2 {
namespace {
const int FLAG_ARG_1_AND_2_ARE_WORDS = 1 << 0;
const int FLAG_WE_HAVE_INSTRUCTIONS = 1 << 8;
void WriteBytes(std::vector<uint8_t>* out, const uint8_t* data, size_t len) {
if (len == 0) return;
size_t offset = out->size();
out->resize(offset + len);
memcpy(&(*out)[offset], data, len);
}
void WriteBytes(std::vector<uint8_t>* out, const std::vector<uint8_t>& in) {
for (int i = 0; i < in.size(); ++i) {
out->push_back(in[i]);
}
}
void WriteUShort(std::vector<uint8_t>* out, int value) {
out->push_back(value >> 8);
out->push_back(value & 255);
}
void WriteLong(std::vector<uint8_t>* out, int value) {
out->push_back((value >> 24) & 255);
out->push_back((value >> 16) & 255);
out->push_back((value >> 8) & 255);
out->push_back(value & 255);
}
// Glyf table preprocessing, based on
// GlyfEncoder.java
class GlyfEncoder {
public:
explicit GlyfEncoder(int num_glyphs)
: n_glyphs_(num_glyphs) {
bbox_bitmap_.resize(((num_glyphs + 31) >> 5) << 2);
}
bool Encode(int glyph_id, const Glyph& glyph) {
if (glyph.composite_data_size > 0) {
WriteCompositeGlyph(glyph_id, glyph);
} else if (glyph.contours.size() > 0) {
WriteSimpleGlyph(glyph_id, glyph);
} else {
WriteUShort(&n_contour_stream_, 0);
}
return true;
}
void GetTransformedGlyfBytes(std::vector<uint8_t>* result) {
WriteLong(result, 0); // version
WriteUShort(result, n_glyphs_);
WriteUShort(result, 0); // index_format, will be set later
WriteLong(result, n_contour_stream_.size());
WriteLong(result, n_points_stream_.size());
WriteLong(result, flag_byte_stream_.size());
WriteLong(result, glyph_stream_.size());
WriteLong(result, composite_stream_.size());
WriteLong(result, bbox_bitmap_.size() + bbox_stream_.size());
WriteLong(result, instruction_stream_.size());
WriteBytes(result, n_contour_stream_);
WriteBytes(result, n_points_stream_);
WriteBytes(result, flag_byte_stream_);
WriteBytes(result, glyph_stream_);
WriteBytes(result, composite_stream_);
WriteBytes(result, bbox_bitmap_);
WriteBytes(result, bbox_stream_);
WriteBytes(result, instruction_stream_);
}
private:
void WriteInstructions(const Glyph& glyph) {
Write255UShort(&glyph_stream_, glyph.instructions_size);
WriteBytes(&instruction_stream_,
glyph.instructions_data, glyph.instructions_size);
}
bool ShouldWriteSimpleGlyphBbox(const Glyph& glyph) {
if (glyph.contours.empty() || glyph.contours[0].empty()) {
return glyph.x_min || glyph.y_min || glyph.x_max || glyph.y_max;
}
int16_t x_min = glyph.contours[0][0].x;
int16_t y_min = glyph.contours[0][0].y;
int16_t x_max = x_min;
int16_t y_max = y_min;
for (const auto& contour : glyph.contours) {
for (const auto& point : contour) {
if (point.x < x_min) x_min = point.x;
if (point.x > x_max) x_max = point.x;
if (point.y < y_min) y_min = point.y;
if (point.y > y_max) y_max = point.y;
}
}
if (glyph.x_min != x_min)
return true;
if (glyph.y_min != y_min)
return true;
if (glyph.x_max != x_max)
return true;
if (glyph.y_max != y_max)
return true;
return false;
}
void WriteSimpleGlyph(int glyph_id, const Glyph& glyph) {
int num_contours = glyph.contours.size();
WriteUShort(&n_contour_stream_, num_contours);
if (ShouldWriteSimpleGlyphBbox(glyph)) {
WriteBbox(glyph_id, glyph);
}
for (int i = 0; i < num_contours; i++) {
Write255UShort(&n_points_stream_, glyph.contours[i].size());
}
int lastX = 0;
int lastY = 0;
for (int i = 0; i < num_contours; i++) {
int num_points = glyph.contours[i].size();
for (int j = 0; j < num_points; j++) {
int x = glyph.contours[i][j].x;
int y = glyph.contours[i][j].y;
int dx = x - lastX;
int dy = y - lastY;
WriteTriplet(glyph.contours[i][j].on_curve, dx, dy);
lastX = x;
lastY = y;
}
}
if (num_contours > 0) {
WriteInstructions(glyph);
}
}
void WriteCompositeGlyph(int glyph_id, const Glyph& glyph) {
WriteUShort(&n_contour_stream_, -1);
WriteBbox(glyph_id, glyph);
WriteBytes(&composite_stream_,
glyph.composite_data,
glyph.composite_data_size);
if (glyph.have_instructions) {
WriteInstructions(glyph);
}
}
void WriteBbox(int glyph_id, const Glyph& glyph) {
bbox_bitmap_[glyph_id >> 3] |= 0x80 >> (glyph_id & 7);
WriteUShort(&bbox_stream_, glyph.x_min);
WriteUShort(&bbox_stream_, glyph.y_min);
WriteUShort(&bbox_stream_, glyph.x_max);
WriteUShort(&bbox_stream_, glyph.y_max);
}
void WriteTriplet(bool on_curve, int x, int y) {
int abs_x = std::abs(x);
int abs_y = std::abs(y);
int on_curve_bit = on_curve ? 0 : 128;
int x_sign_bit = (x < 0) ? 0 : 1;
int y_sign_bit = (y < 0) ? 0 : 1;
int xy_sign_bits = x_sign_bit + 2 * y_sign_bit;
if (x == 0 && abs_y < 1280) {
flag_byte_stream_.push_back(on_curve_bit +
((abs_y & 0xf00) >> 7) + y_sign_bit);
glyph_stream_.push_back(abs_y & 0xff);
} else if (y == 0 && abs_x < 1280) {
flag_byte_stream_.push_back(on_curve_bit + 10 +
((abs_x & 0xf00) >> 7) + x_sign_bit);
glyph_stream_.push_back(abs_x & 0xff);
} else if (abs_x < 65 && abs_y < 65) {
flag_byte_stream_.push_back(on_curve_bit + 20 +
((abs_x - 1) & 0x30) +
(((abs_y - 1) & 0x30) >> 2) +
xy_sign_bits);
glyph_stream_.push_back((((abs_x - 1) & 0xf) << 4) | ((abs_y - 1) & 0xf));
} else if (abs_x < 769 && abs_y < 769) {
flag_byte_stream_.push_back(on_curve_bit + 84 +
12 * (((abs_x - 1) & 0x300) >> 8) +
(((abs_y - 1) & 0x300) >> 6) + xy_sign_bits);
glyph_stream_.push_back((abs_x - 1) & 0xff);
glyph_stream_.push_back((abs_y - 1) & 0xff);
} else if (abs_x < 4096 && abs_y < 4096) {
flag_byte_stream_.push_back(on_curve_bit + 120 + xy_sign_bits);
glyph_stream_.push_back(abs_x >> 4);
glyph_stream_.push_back(((abs_x & 0xf) << 4) | (abs_y >> 8));
glyph_stream_.push_back(abs_y & 0xff);
} else {
flag_byte_stream_.push_back(on_curve_bit + 124 + xy_sign_bits);
glyph_stream_.push_back(abs_x >> 8);
glyph_stream_.push_back(abs_x & 0xff);
glyph_stream_.push_back(abs_y >> 8);
glyph_stream_.push_back(abs_y & 0xff);
}
}
std::vector<uint8_t> n_contour_stream_;
std::vector<uint8_t> n_points_stream_;
std::vector<uint8_t> flag_byte_stream_;
std::vector<uint8_t> composite_stream_;
std::vector<uint8_t> bbox_bitmap_;
std::vector<uint8_t> bbox_stream_;
std::vector<uint8_t> glyph_stream_;
std::vector<uint8_t> instruction_stream_;
int n_glyphs_;
};
} // namespace
bool TransformGlyfAndLocaTables(Font* font) {
// no transform for CFF
const Font::Table* glyf_table = font->FindTable(kGlyfTableTag);
const Font::Table* loca_table = font->FindTable(kLocaTableTag);
if (font->FindTable(kCffTableTag) != NULL
&& glyf_table == NULL
&& loca_table == NULL) {
return true;
}
// Must share neither or both loca/glyf
if (glyf_table->IsReused() != loca_table->IsReused()) {
return FONT_COMPRESSION_FAILURE();
}
if (glyf_table->IsReused()) {
return true;
}
Font::Table* transformed_glyf = &font->tables[kGlyfTableTag ^ 0x80808080];
Font::Table* transformed_loca = &font->tables[kLocaTableTag ^ 0x80808080];
int num_glyphs = NumGlyphs(*font);
GlyfEncoder encoder(num_glyphs);
for (int i = 0; i < num_glyphs; ++i) {
Glyph glyph;
const uint8_t* glyph_data;
size_t glyph_size;
if (!GetGlyphData(*font, i, &glyph_data, &glyph_size) ||
(glyph_size > 0 && !ReadGlyph(glyph_data, glyph_size, &glyph))) {
return FONT_COMPRESSION_FAILURE();
}
encoder.Encode(i, glyph);
}
encoder.GetTransformedGlyfBytes(&transformed_glyf->buffer);
const Font::Table* head_table = font->FindTable(kHeadTableTag);
if (head_table == NULL || head_table->length < 52) {
return FONT_COMPRESSION_FAILURE();
}
transformed_glyf->buffer[7] = head_table->data[51]; // index_format
transformed_glyf->tag = kGlyfTableTag ^ 0x80808080;
transformed_glyf->length = transformed_glyf->buffer.size();
transformed_glyf->data = transformed_glyf->buffer.data();
transformed_loca->tag = kLocaTableTag ^ 0x80808080;
transformed_loca->length = 0;
transformed_loca->data = NULL;
return true;
}
} // namespace woff2
<|endoftext|> |
<commit_before>//
// fdf2nii_main.cpp
//
// Created by Tobias Wood on 29/08/2013.
//
//
#include <string>
#include <iostream>
#include <iterator>
#include <getopt.h>
#include "fdf.h"
#include "Nifti.h"
using namespace std;
static bool zip = false, procpar = false;
static double scale = 1.;
static string outPrefix;
static struct option long_options[] =
{
{"scale", required_argument, 0, 's'},
{"out", required_argument, 0, 'o'},
{"zip", no_argument, 0, 'z'},
{"procpar", no_argument, 0, 'p'},
{0, 0, 0, 0}
};
const string usage {
"fdf2nii - A utility to convert Agilent fdf files to nifti.\n\
\n\
Usage: fdf2nii [opts] image1 image2 ... imageN\n\
image1 to imageN are paths to the Agilent .img folders, not individual .fdf\n\
files\n\
Options:\n\
-s, --scale: Scale factor for image dimensions (set to 10 for use with SPM).\n\
-o, --out: Specify an output prefix.\n\
-z, --zip: Create .nii.gz files\n\
-p, --procpar: Embed procpar in the nifti header.\n"
};
int main(int argc, char **argv) {
int indexptr = 0, c;
while ((c = getopt_long(argc, argv, "s:o:zp", long_options, &indexptr)) != -1) {
switch (c) {
case 0: break; // It was an option that just sets a flag.
case 's': scale = atof(optarg); break;
case 'o': outPrefix = string(optarg); break;
case 'z': zip = true; break;
case 'p': procpar = true; break;
default: cout << "Unknown option " << optarg << endl;
}
}
if ((argc - optind) <= 0) {
cout << "No input images specified." << endl << usage << endl;
exit(EXIT_FAILURE);
}
while (optind < argc) {
string inPath(argv[optind]);
optind++;
string outPath = outPrefix + inPath.substr(inPath.find_last_of("/") + 1, inPath.find_last_of(".")) + ".nii";
if (zip)
outPath += ".gz";
cout << "Converting " << inPath << " to " << outPath << endl;
try {
Agilent::fdfImage input(inPath);
try {
Nifti::File output(input.dim(0), input.dim(1), input.dim(2), input.dim(3),
input.voxdim(0) * scale, input.voxdim(1) * scale, input.voxdim(2) * scale, 1.,
DT_FLOAT32, input.ijk_to_xyz().cast<float>());
if (procpar) {
ifstream pp_file(inPath + "/procpar", ios::binary);
pp_file.seekg(ios::end);
size_t fileSize = pp_file.tellg();
pp_file.seekg(ios::beg);
vector<char> data; data.reserve(fileSize);
data.assign(istreambuf_iterator<char>(pp_file), istreambuf_iterator<char>());
output.addExtension(NIFTI_ECODE_COMMENT, data);
}
output.open(outPath, Nifti::Modes::Write);
for (size_t v = 0; v < input.dim(3); v++) {
output.writeVolume<float>(v, input.readVolume<float>(v));
}
output.close();
} catch (exception &e) {
cerr << "Error, skipping to next input. " << e.what() << outPath << endl;
continue;
}
} catch (exception &e) {
cerr << "Error, skipping to next input. " << e.what() << endl;
continue;
}
}
return EXIT_SUCCESS;
}
<commit_msg>Fixed a bug with working out the output path.<commit_after>//
// fdf2nii_main.cpp
//
// Created by Tobias Wood on 29/08/2013.
//
//
#include <string>
#include <iostream>
#include <iterator>
#include <getopt.h>
#include "fdf.h"
#include "Nifti.h"
using namespace std;
static bool zip = false, procpar = false;
static double scale = 1.;
static string outPrefix;
static struct option long_options[] =
{
{"scale", required_argument, 0, 's'},
{"out", required_argument, 0, 'o'},
{"zip", no_argument, 0, 'z'},
{"procpar", no_argument, 0, 'p'},
{0, 0, 0, 0}
};
const string usage {
"fdf2nii - A utility to convert Agilent fdf files to nifti.\n\
\n\
Usage: fdf2nii [opts] image1 image2 ... imageN\n\
image1 to imageN are paths to the Agilent .img folders, not individual .fdf\n\
files\n\
Options:\n\
-s, --scale: Scale factor for image dimensions (set to 10 for use with SPM).\n\
-o, --out: Specify an output prefix.\n\
-z, --zip: Create .nii.gz files\n\
-p, --procpar: Embed procpar in the nifti header.\n"
};
int main(int argc, char **argv) {
int indexptr = 0, c;
while ((c = getopt_long(argc, argv, "s:o:zp", long_options, &indexptr)) != -1) {
switch (c) {
case 0: break; // It was an option that just sets a flag.
case 's': scale = atof(optarg); break;
case 'o': outPrefix = string(optarg); break;
case 'z': zip = true; break;
case 'p': procpar = true; break;
default: cout << "Unknown option " << optarg << endl;
}
}
if ((argc - optind) <= 0) {
cout << "No input images specified." << endl << usage << endl;
exit(EXIT_FAILURE);
}
while (optind < argc) {
string inPath(argv[optind]);
optind++;
size_t fileSep = inPath.find_last_of("/") + 1;
size_t fileExt = inPath.find_last_of(".");
if (inPath.substr(fileExt) != ".img") {
cerr << inPath << " is not a valid .img folder. Skipping." << endl;
continue;
}
string outPath = outPrefix + inPath.substr(fileSep, fileExt - fileSep) + ".nii";
if (zip)
outPath += ".gz";
cout << "Converting " << inPath << " to " << outPath << endl;
try {
Agilent::fdfImage input(inPath);
try {
Nifti::File output(input.dim(0), input.dim(1), input.dim(2), input.dim(3),
input.voxdim(0) * scale, input.voxdim(1) * scale, input.voxdim(2) * scale, 1.,
DT_FLOAT32, input.ijk_to_xyz().cast<float>());
if (procpar) {
ifstream pp_file(inPath + "/procpar", ios::binary);
pp_file.seekg(ios::end);
size_t fileSize = pp_file.tellg();
pp_file.seekg(ios::beg);
vector<char> data; data.reserve(fileSize);
data.assign(istreambuf_iterator<char>(pp_file), istreambuf_iterator<char>());
output.addExtension(NIFTI_ECODE_COMMENT, data);
}
output.open(outPath, Nifti::Modes::Write);
for (size_t v = 0; v < input.dim(3); v++) {
output.writeVolume<float>(v, input.readVolume<float>(v));
}
output.close();
} catch (exception &e) {
cerr << "Error, skipping to next input. " << e.what() << outPath << endl;
continue;
}
} catch (exception &e) {
cerr << "Error, skipping to next input. " << e.what() << endl;
continue;
}
}
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2007-2017 Content Management AG
* All rights reserved.
*
* author: Max Kellermann <mk@cm4all.com>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef BENG_PROXY_FILE_ADDRESS_HXX
#define BENG_PROXY_FILE_ADDRESS_HXX
#include "spawn/ChildOptions.hxx"
#include "util/ConstBuffer.hxx"
#include "util/Compiler.h"
class AllocatorPtr;
class MatchInfo;
struct DelegateAddress;
/**
* The address of a local static file.
*/
struct FileAddress {
const char *path;
const char *deflated = nullptr;
const char *gzipped = nullptr;
const char *content_type = nullptr;
ConstBuffer<void> content_type_lookup = nullptr;
const char *document_root = nullptr;
/**
* The value of #TRANSLATE_EXPAND_PATH. Only used by the
* translation cache.
*/
const char *expand_path = nullptr;
/**
* The value of #TRANSLATE_EXPAND_DOCUMENT_ROOT. Only used by the
* translation cache.
*/
const char *expand_document_root = nullptr;
DelegateAddress *delegate = nullptr;
bool auto_gzipped = false;
/**
* @param _path the new path pointer (taken as-is, no deep copy)
*/
constexpr FileAddress(const char *_path) noexcept
:path(_path)
{
}
FileAddress(AllocatorPtr alloc, const FileAddress &src) noexcept;
FileAddress(const FileAddress &) = delete;
FileAddress &operator=(const FileAddress &) = delete;
gcc_pure
bool HasQueryString() const noexcept {
return false;
}
/**
* Throws std::runtime_error on error.
*/
void Check() const;
gcc_pure
bool IsValidBase() const noexcept;
FileAddress *SaveBase(AllocatorPtr alloc,
const char *suffix) const noexcept;
FileAddress *LoadBase(AllocatorPtr alloc,
const char *suffix) const noexcept;
/**
* Does this address need to be expanded with Expand()?
*/
gcc_pure
bool IsExpandable() const noexcept;
/**
* Throws std::runtime_error on error.
*/
void Expand(AllocatorPtr alloc, const MatchInfo &match_info);
};
#endif
<commit_msg>file_address: make constructor explicit<commit_after>/*
* Copyright 2007-2017 Content Management AG
* All rights reserved.
*
* author: Max Kellermann <mk@cm4all.com>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef BENG_PROXY_FILE_ADDRESS_HXX
#define BENG_PROXY_FILE_ADDRESS_HXX
#include "spawn/ChildOptions.hxx"
#include "util/ConstBuffer.hxx"
#include "util/Compiler.h"
class AllocatorPtr;
class MatchInfo;
struct DelegateAddress;
/**
* The address of a local static file.
*/
struct FileAddress {
const char *path;
const char *deflated = nullptr;
const char *gzipped = nullptr;
const char *content_type = nullptr;
ConstBuffer<void> content_type_lookup = nullptr;
const char *document_root = nullptr;
/**
* The value of #TRANSLATE_EXPAND_PATH. Only used by the
* translation cache.
*/
const char *expand_path = nullptr;
/**
* The value of #TRANSLATE_EXPAND_DOCUMENT_ROOT. Only used by the
* translation cache.
*/
const char *expand_document_root = nullptr;
DelegateAddress *delegate = nullptr;
bool auto_gzipped = false;
/**
* @param _path the new path pointer (taken as-is, no deep copy)
*/
explicit constexpr FileAddress(const char *_path) noexcept
:path(_path)
{
}
FileAddress(AllocatorPtr alloc, const FileAddress &src) noexcept;
FileAddress(const FileAddress &) = delete;
FileAddress &operator=(const FileAddress &) = delete;
gcc_pure
bool HasQueryString() const noexcept {
return false;
}
/**
* Throws std::runtime_error on error.
*/
void Check() const;
gcc_pure
bool IsValidBase() const noexcept;
FileAddress *SaveBase(AllocatorPtr alloc,
const char *suffix) const noexcept;
FileAddress *LoadBase(AllocatorPtr alloc,
const char *suffix) const noexcept;
/**
* Does this address need to be expanded with Expand()?
*/
gcc_pure
bool IsExpandable() const noexcept;
/**
* Throws std::runtime_error on error.
*/
void Expand(AllocatorPtr alloc, const MatchInfo &match_info);
};
#endif
<|endoftext|> |
<commit_before>/*
* Copyright 2007-2017 Content Management AG
* All rights reserved.
*
* author: Max Kellermann <mk@cm4all.com>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "file_headers.hxx"
#include "static_headers.hxx"
#include "GrowingBuffer.hxx"
#include "header_writer.hxx"
#include "request.hxx"
#include "http_server/Request.hxx"
#include "http_headers.hxx"
#include "translation/Vary.hxx"
#include "http/List.hxx"
#include "http/Date.hxx"
#include "util/DecimalFormat.h"
#include <attr/xattr.h>
#include <assert.h>
#include <stdlib.h>
#include <sys/stat.h>
gcc_pure
static std::chrono::seconds
read_xattr_max_age(int fd)
{
assert(fd >= 0);
char buffer[32];
ssize_t nbytes = fgetxattr(fd, "user.MaxAge",
buffer, sizeof(buffer) - 1);
if (nbytes <= 0)
return std::chrono::seconds::zero();
buffer[nbytes] = 0;
char *endptr;
unsigned long max_age = strtoul(buffer, &endptr, 10);
if (*endptr != 0)
return std::chrono::seconds::zero();
return std::chrono::seconds(max_age);
}
static void
generate_expires(GrowingBuffer &headers,
std::chrono::system_clock::duration max_age)
{
constexpr std::chrono::system_clock::duration max_max_age =
std::chrono::hours(365 * 24);
if (max_age > max_max_age)
/* limit max_age to approximately one year */
max_age = max_max_age;
/* generate an "Expires" response header */
header_write(headers, "expires",
http_date_format(std::chrono::system_clock::now() + max_age));
}
static bool
ReadETag(int fd, char *buffer, size_t size) noexcept
{
assert(fd >= 0);
assert(size > 4);
const auto nbytes = fgetxattr(fd, "user.ETag", buffer + 1, size - 3);
if (nbytes <= 0)
return false;
assert((size_t)nbytes < size);
buffer[0] = '"';
buffer[nbytes + 1] = '"';
buffer[nbytes + 2] = 0;
return true;
}
static void
MakeETag(GrowingBuffer &headers, int fd, const struct stat &st)
{
char buffer[512];
if (fd < 0 || !ReadETag(fd, buffer, sizeof(buffer)))
static_etag(buffer, st);
header_write(headers, "etag", buffer);
}
static void
file_cache_headers(GrowingBuffer &headers,
int fd, const struct stat &st,
std::chrono::seconds max_age)
{
MakeETag(headers, fd, st);
if (max_age == std::chrono::seconds::zero() && fd >= 0)
max_age = read_xattr_max_age(fd);
if (max_age > std::chrono::seconds::zero())
generate_expires(headers, max_age);
}
/**
* Verifies the If-Range request header (RFC 2616 14.27).
*/
static bool
check_if_range(const char *if_range, const struct stat &st)
{
if (if_range == nullptr)
return true;
const auto t = http_date_parse(if_range);
if (t != std::chrono::system_clock::from_time_t(-1))
return std::chrono::system_clock::from_time_t(st.st_mtime) == t;
char etag[64];
static_etag(etag, st);
return strcmp(if_range, etag) == 0;
}
bool
file_evaluate_request(Request &request2,
int fd, const struct stat &st,
struct file_request &file_request)
{
const auto &request = request2.request;
const auto &request_headers = request.headers;
const auto &tr = *request2.translate.response;
bool ignore_if_modified_since = false;
if (tr.status == 0 && request.method == HTTP_METHOD_GET &&
!request2.IsTransformationEnabled()) {
const char *p = request_headers.Get("range");
if (p != nullptr &&
check_if_range(request_headers.Get("if-range"), st))
file_request.range.ParseRangeHeader(p);
}
if (!request2.IsTransformationEnabled()) {
const char *p = request_headers.Get("if-match");
if (p != nullptr && strcmp(p, "*") != 0) {
char buffer[64];
static_etag(buffer, st);
if (!http_list_contains(p, buffer)) {
response_dispatch(request2, HTTP_STATUS_PRECONDITION_FAILED,
HttpHeaders(request2.pool), nullptr);
return false;
}
}
p = request_headers.Get("if-none-match");
if (p != nullptr && strcmp(p, "*") == 0) {
response_dispatch(request2, HTTP_STATUS_PRECONDITION_FAILED,
HttpHeaders(request2.pool), nullptr);
return false;
}
if (p != nullptr) {
char buffer[64];
static_etag(buffer, st);
if (http_list_contains(p, buffer)) {
response_dispatch(request2, HTTP_STATUS_PRECONDITION_FAILED,
HttpHeaders(request2.pool), nullptr);
return false;
}
/* RFC 2616 14.26: "If none of the entity tags match, then
the server MAY perform the requested method as if the
If-None-Match header field did not exist, but MUST also
ignore any If-Modified-Since header field(s) in the
request." */
ignore_if_modified_since = true;
}
}
if (!request2.IsProcessorEnabled()) {
const char *p = ignore_if_modified_since
? nullptr
: request_headers.Get("if-modified-since");
if (p != nullptr) {
const auto t = http_date_parse(p);
if (t != std::chrono::system_clock::from_time_t(-1) &&
std::chrono::system_clock::from_time_t(st.st_mtime) <= t) {
HttpHeaders headers(request2.pool);
auto &headers2 = headers.GetBuffer();
file_cache_headers(headers2, fd, st, tr.expires_relative);
write_translation_vary_header(headers2, tr);
response_dispatch(request2, HTTP_STATUS_NOT_MODIFIED,
std::move(headers), nullptr);
return false;
}
}
p = request_headers.Get("if-unmodified-since");
if (p != nullptr) {
const auto t = http_date_parse(p);
if (t != std::chrono::system_clock::from_time_t(-1) &&
std::chrono::system_clock::from_time_t(st.st_mtime) > t) {
response_dispatch(request2, HTTP_STATUS_PRECONDITION_FAILED,
HttpHeaders(request2.pool), nullptr);
return false;
}
}
}
return true;
}
void
file_response_headers(GrowingBuffer &headers,
const char *override_content_type,
int fd, const struct stat &st,
std::chrono::seconds expires_relative,
bool processor_enabled, bool processor_first)
{
if (!processor_first && fd >= 0)
file_cache_headers(headers, fd, st, expires_relative);
else {
char etag[64];
static_etag(etag, st);
header_write(headers, "etag", etag);
if (expires_relative > std::chrono::seconds::zero())
generate_expires(headers, expires_relative);
}
if (override_content_type != nullptr) {
/* content type override from the translation server */
header_write(headers, "content-type", override_content_type);
} else {
char content_type[256];
if (load_xattr_content_type(content_type, sizeof(content_type), fd)) {
header_write(headers, "content-type", content_type);
} else {
header_write(headers, "content-type", "application/octet-stream");
}
}
#ifndef NO_LAST_MODIFIED_HEADER
if (!processor_enabled)
header_write(headers, "last-modified",
http_date_format(std::chrono::system_clock::from_time_t(st.st_mtime)));
#endif
}
<commit_msg>file_headers: move code to DispatchNotModified()<commit_after>/*
* Copyright 2007-2017 Content Management AG
* All rights reserved.
*
* author: Max Kellermann <mk@cm4all.com>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "file_headers.hxx"
#include "static_headers.hxx"
#include "GrowingBuffer.hxx"
#include "header_writer.hxx"
#include "request.hxx"
#include "http_server/Request.hxx"
#include "http_headers.hxx"
#include "translation/Vary.hxx"
#include "http/List.hxx"
#include "http/Date.hxx"
#include "util/DecimalFormat.h"
#include <attr/xattr.h>
#include <assert.h>
#include <stdlib.h>
#include <sys/stat.h>
gcc_pure
static std::chrono::seconds
read_xattr_max_age(int fd)
{
assert(fd >= 0);
char buffer[32];
ssize_t nbytes = fgetxattr(fd, "user.MaxAge",
buffer, sizeof(buffer) - 1);
if (nbytes <= 0)
return std::chrono::seconds::zero();
buffer[nbytes] = 0;
char *endptr;
unsigned long max_age = strtoul(buffer, &endptr, 10);
if (*endptr != 0)
return std::chrono::seconds::zero();
return std::chrono::seconds(max_age);
}
static void
generate_expires(GrowingBuffer &headers,
std::chrono::system_clock::duration max_age)
{
constexpr std::chrono::system_clock::duration max_max_age =
std::chrono::hours(365 * 24);
if (max_age > max_max_age)
/* limit max_age to approximately one year */
max_age = max_max_age;
/* generate an "Expires" response header */
header_write(headers, "expires",
http_date_format(std::chrono::system_clock::now() + max_age));
}
static bool
ReadETag(int fd, char *buffer, size_t size) noexcept
{
assert(fd >= 0);
assert(size > 4);
const auto nbytes = fgetxattr(fd, "user.ETag", buffer + 1, size - 3);
if (nbytes <= 0)
return false;
assert((size_t)nbytes < size);
buffer[0] = '"';
buffer[nbytes + 1] = '"';
buffer[nbytes + 2] = 0;
return true;
}
static void
MakeETag(GrowingBuffer &headers, int fd, const struct stat &st)
{
char buffer[512];
if (fd < 0 || !ReadETag(fd, buffer, sizeof(buffer)))
static_etag(buffer, st);
header_write(headers, "etag", buffer);
}
static void
file_cache_headers(GrowingBuffer &headers,
int fd, const struct stat &st,
std::chrono::seconds max_age)
{
MakeETag(headers, fd, st);
if (max_age == std::chrono::seconds::zero() && fd >= 0)
max_age = read_xattr_max_age(fd);
if (max_age > std::chrono::seconds::zero())
generate_expires(headers, max_age);
}
/**
* Verifies the If-Range request header (RFC 2616 14.27).
*/
static bool
check_if_range(const char *if_range, const struct stat &st)
{
if (if_range == nullptr)
return true;
const auto t = http_date_parse(if_range);
if (t != std::chrono::system_clock::from_time_t(-1))
return std::chrono::system_clock::from_time_t(st.st_mtime) == t;
char etag[64];
static_etag(etag, st);
return strcmp(if_range, etag) == 0;
}
/**
* Generate a "304 Not Modified" response.
*/
static void
DispatchNotModified(Request &request2, const TranslateResponse &tr,
int fd, const struct stat &st)
{
HttpHeaders headers(request2.pool);
auto &headers2 = headers.GetBuffer();
file_cache_headers(headers2, fd, st, tr.expires_relative);
write_translation_vary_header(headers2, tr);
response_dispatch(request2, HTTP_STATUS_NOT_MODIFIED,
std::move(headers), nullptr);
}
bool
file_evaluate_request(Request &request2,
int fd, const struct stat &st,
struct file_request &file_request)
{
const auto &request = request2.request;
const auto &request_headers = request.headers;
const auto &tr = *request2.translate.response;
bool ignore_if_modified_since = false;
if (tr.status == 0 && request.method == HTTP_METHOD_GET &&
!request2.IsTransformationEnabled()) {
const char *p = request_headers.Get("range");
if (p != nullptr &&
check_if_range(request_headers.Get("if-range"), st))
file_request.range.ParseRangeHeader(p);
}
if (!request2.IsTransformationEnabled()) {
const char *p = request_headers.Get("if-match");
if (p != nullptr && strcmp(p, "*") != 0) {
char buffer[64];
static_etag(buffer, st);
if (!http_list_contains(p, buffer)) {
response_dispatch(request2, HTTP_STATUS_PRECONDITION_FAILED,
HttpHeaders(request2.pool), nullptr);
return false;
}
}
p = request_headers.Get("if-none-match");
if (p != nullptr && strcmp(p, "*") == 0) {
response_dispatch(request2, HTTP_STATUS_PRECONDITION_FAILED,
HttpHeaders(request2.pool), nullptr);
return false;
}
if (p != nullptr) {
char buffer[64];
static_etag(buffer, st);
if (http_list_contains(p, buffer)) {
response_dispatch(request2, HTTP_STATUS_PRECONDITION_FAILED,
HttpHeaders(request2.pool), nullptr);
return false;
}
/* RFC 2616 14.26: "If none of the entity tags match, then
the server MAY perform the requested method as if the
If-None-Match header field did not exist, but MUST also
ignore any If-Modified-Since header field(s) in the
request." */
ignore_if_modified_since = true;
}
}
if (!request2.IsProcessorEnabled()) {
const char *p = ignore_if_modified_since
? nullptr
: request_headers.Get("if-modified-since");
if (p != nullptr) {
const auto t = http_date_parse(p);
if (t != std::chrono::system_clock::from_time_t(-1) &&
std::chrono::system_clock::from_time_t(st.st_mtime) <= t) {
DispatchNotModified(request2, tr, fd, st);
return false;
}
}
p = request_headers.Get("if-unmodified-since");
if (p != nullptr) {
const auto t = http_date_parse(p);
if (t != std::chrono::system_clock::from_time_t(-1) &&
std::chrono::system_clock::from_time_t(st.st_mtime) > t) {
response_dispatch(request2, HTTP_STATUS_PRECONDITION_FAILED,
HttpHeaders(request2.pool), nullptr);
return false;
}
}
}
return true;
}
void
file_response_headers(GrowingBuffer &headers,
const char *override_content_type,
int fd, const struct stat &st,
std::chrono::seconds expires_relative,
bool processor_enabled, bool processor_first)
{
if (!processor_first && fd >= 0)
file_cache_headers(headers, fd, st, expires_relative);
else {
char etag[64];
static_etag(etag, st);
header_write(headers, "etag", etag);
if (expires_relative > std::chrono::seconds::zero())
generate_expires(headers, expires_relative);
}
if (override_content_type != nullptr) {
/* content type override from the translation server */
header_write(headers, "content-type", override_content_type);
} else {
char content_type[256];
if (load_xattr_content_type(content_type, sizeof(content_type), fd)) {
header_write(headers, "content-type", content_type);
} else {
header_write(headers, "content-type", "application/octet-stream");
}
}
#ifndef NO_LAST_MODIFIED_HEADER
if (!processor_enabled)
header_write(headers, "last-modified",
http_date_format(std::chrono::system_clock::from_time_t(st.st_mtime)));
#endif
}
<|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->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->VoxelCount = 0;
}
//----------------------------------------------------------------------------
vtkImageAccumulate::~vtkImageAccumulate()
{
}
//----------------------------------------------------------------------------
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];
}
}
//----------------------------------------------------------------------------
void vtkImageAccumulate::SetStencil(vtkImageStencilData *stencil)
{
this->vtkProcessObject::SetNthInput(1, stencil);
}
//----------------------------------------------------------------------------
vtkImageStencilData *vtkImageAccumulate::GetStencil()
{
if (this->NumberOfInputs < 2)
{
return NULL;
}
else
{
return (vtkImageStencilData *)(this->Inputs[1]);
}
}
//----------------------------------------------------------------------------
// 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 *VoxelCount)
{
int idX, idY, idZ, idxC;
int r1, r2, cr1, cr2, iter, rval;
int pmin0, pmax0, 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;
*VoxelCount = 0;
vtkImageStencilData *stencil = self->GetStencil();
// 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++;
// loop over stencil sub-extents
iter = 0;
cr1 = min0;
rval = 1;
while (rval)
{
rval = 0;
r1 = max0 + 1;
r2 = max0;
if (stencil)
{ // get sub extent [r1,r2]
rval = stencil->GetNextExtent(r1, r2, min0, max0, idY, idZ, iter);
}
// sub extents [cr1,cr2] are the complement of sub extents [r1,r2]
cr2 = r1 - 1;
pmin0 = cr1;
pmax0 = cr2;
// check whether to use [r1,r2] or its complement [cr1,cr2]
if (stencil && !self->GetReverseStencil())
{
if (rval == 0)
{
break;
}
pmin0 = r1;
pmax0 = r2;
}
// set up cr1 for next iteration
cr1 = r2 + 1;
// set up pointer for sub extent
tempPtr = inPtr + (inInc2*(idZ - min2) +
inInc1*(idY - min1) +
numC*(pmin0 - min0));
// accumulate over the sub extent
for (idX = pmin0; idX <= pmax0; 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;
}
(*VoxelCount)++;
// 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 (*VoxelCount) // avoid the div0
{
Mean[0] = sum[0] / (double)*VoxelCount;
Mean[1] = sum[1] / (double)*VoxelCount;
Mean[2] = sum[2] / (double)*VoxelCount;
}
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->VoxelCount);
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);
// need to set the spacing and origin of the stencil to match the output
vtkImageStencilData *stencil = this->GetStencil();
if (stencil)
{
stencil->SetSpacing(input->GetSpacing());
stencil->SetOrigin(input->GetOrigin());
}
}
//----------------------------------------------------------------------------
// 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 << "Mean: " << this->Mean << "\n";
os << indent << "Min: " << this->Min << "\n";
os << indent << "Max: " << this->Max << "\n";
os << indent << "VoxelCount: " << this->VoxelCount << "\n";
os << indent << "Stencil: " << this->GetStencil() << "\n";
os << indent << "ReverseStencil: " << (this->ReverseStencil ?
"On\n" : "Off\n");
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>ENH: simplify reversal of stencil, also some 'progress' stuff was missing<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->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->VoxelCount = 0;
}
//----------------------------------------------------------------------------
vtkImageAccumulate::~vtkImageAccumulate()
{
}
//----------------------------------------------------------------------------
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];
}
}
//----------------------------------------------------------------------------
void vtkImageAccumulate::SetStencil(vtkImageStencilData *stencil)
{
this->vtkProcessObject::SetNthInput(1, stencil);
}
//----------------------------------------------------------------------------
vtkImageStencilData *vtkImageAccumulate::GetStencil()
{
if (this->NumberOfInputs < 2)
{
return NULL;
}
else
{
return (vtkImageStencilData *)(this->Inputs[1]);
}
}
//----------------------------------------------------------------------------
// 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 *VoxelCount)
{
int idX, idY, idZ, idxC;
int iter, pmin0, pmax0, 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;
*VoxelCount = 0;
vtkImageStencilData *stencil = self->GetStencil();
// 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++;
// loop over stencil sub-extents
iter = 0;
if (self->GetReverseStencil())
{ // flag that we want the complementary extents
iter = -1;
}
pmin0 = min0;
pmax0 = max0;
while ((stencil != 0 &&
stencil->GetNextExtent(pmin0,pmax0,min0,max0,idY,idZ,iter)) ||
(stencil == 0 && iter++ == 0))
{
// set up pointer for sub extent
tempPtr = inPtr + (inInc2*(idZ - min2) +
inInc1*(idY - min1) +
numC*(pmin0 - min0));
// accumulate over the sub extent
for (idX = pmin0; idX <= pmax0; 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;
}
(*VoxelCount)++;
// 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 (*VoxelCount) // avoid the div0
{
Mean[0] = sum[0] / (double)*VoxelCount;
Mean[1] = sum[1] / (double)*VoxelCount;
Mean[2] = sum[2] / (double)*VoxelCount;
}
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->VoxelCount);
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);
// need to set the spacing and origin of the stencil to match the output
vtkImageStencilData *stencil = this->GetStencil();
if (stencil)
{
stencil->SetSpacing(input->GetSpacing());
stencil->SetOrigin(input->GetOrigin());
}
}
//----------------------------------------------------------------------------
// 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 << "Mean: " << this->Mean << "\n";
os << indent << "Min: " << this->Min << "\n";
os << indent << "Max: " << this->Max << "\n";
os << indent << "VoxelCount: " << this->VoxelCount << "\n";
os << indent << "Stencil: " << this->GetStencil() << "\n";
os << indent << "ReverseStencil: " << (this->ReverseStencil ?
"On\n" : "Off\n");
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";
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2014-2016 Kartik Kumar, Dinamica Srl (me@kartikkumar.com)
* Distributed under the MIT License.
* See accompanying file LICENSE.md or copy at http://opensource.org/licenses/MIT
*/
#ifndef D2D_LAMBERT_SCANNER_HPP
#define D2D_LAMBERT_SCANNER_HPP
#include <string>
#include <keplerian_toolbox.h>
#include <libsgp4/DateTime.h>
#include <rapidjson/document.h>
#include <SQLiteCpp/SQLiteCpp.h>
namespace d2d
{
//! Execute lambert_scanner.
/*!
* Executes lambert_scanner application mode that performs a grid search to compute \f$\Delta V\f$
* for debris-to-debris transfers. The transfers are modelled as conic sections. The Lambert
* targeter employed is based on Izzo (2014), implemented in PyKEP (Izzo, 2012).
*
* The results obtained from the grid search are stored in a SQLite database, containing the
* following table:
*
* - "lambert_scanner_results": contains all Lambert transfers computed during grid search
*
* @param[in] config User-defined configuration options (extracted from JSON input file)
*/
void executeLambertScanner( const rapidjson::Document& config );
//! lambert_scanner input.
/*!
* Data struct containing all valid lambert_scanner input parameters. This struct is populated by
* the checkLambertScannerInput() function and can be used to execute the lambert_scanner
* application mode.
*
* @sa checkLambertScannerInput, executeLambertScanner
*/
struct LambertScannerInput
{
public:
//! Construct data struct.
/*!
* Constructs data struct based on verified input parameters.
*
* @sa checkLambertScannerInput, executeLambertScanner
* @param[in] aCatalogPath Path to TLE catalog
* @param[in] aDatabasePath Path to SQLite database
* @param[in] aDepartureEpoch Departure epoch for all transfers
* @param[in] aTimeOfFlightMinimum Minimum time-of-flight [s]
* @param[in] aTimeOfFlightMaximum Maximum time-of-flight [s]
* @param[in] someTimeOfFlightSteps Number of steps to take in time-of-flight grid
* @param[in] aTimeOfFlightStepSize Time-of-flight step size (derived parameter) [s]
* @param[in] progradeFlag Flag indicating if prograde transfer should be computed
* (false = retrograde)
* @param[in] aRevolutionsMaximum Maximum number of revolutions
* @param[in] aShortlistLength Number of transfers to include in shortlist
* @param[in] aShortlistPath Path to shortlist file
*/
LambertScannerInput( const std::string& aCatalogPath,
const std::string& aDatabasePath,
const DateTime& aDepartureEpoch,
const double aTimeOfFlightMinimum,
const double aTimeOfFlightMaximum,
const double someTimeOfFlightSteps,
const double aTimeOfFlightStepSize,
const bool progradeFlag,
const int aRevolutionsMaximum,
const int aShortlistLength,
const std::string& aShortlistPath )
: catalogPath( aCatalogPath ),
databasePath( aDatabasePath ),
departureEpoch( aDepartureEpoch ),
timeOfFlightMinimum( aTimeOfFlightMinimum ),
timeOfFlightMaximum( aTimeOfFlightMaximum ),
timeOfFlightSteps( someTimeOfFlightSteps ),
timeOfFlightStepSize( aTimeOfFlightStepSize ),
isPrograde( progradeFlag ),
revolutionsMaximum( aRevolutionsMaximum ),
shortlistLength( aShortlistLength ),
shortlistPath( aShortlistPath )
{ }
//! Path to TLE catalog.
const std::string catalogPath;
//! Path to SQLite database to store output.
const std::string databasePath;
//! Departure epoch.
const DateTime departureEpoch;
//! Minimum time-of-flight [s].
const double timeOfFlightMinimum;
//! Maximum time-of-flight [s].
const double timeOfFlightMaximum;
//! Number of time-of-flight steps.
const double timeOfFlightSteps;
//! Time-of-flight step size [s].
const double timeOfFlightStepSize;
//! Flag indicating if transfers are prograde. False indicates retrograde.
const bool isPrograde;
//! Maximum number of revolutions (N) for transfer. Number of revolutions is 2*N+1.
const int revolutionsMaximum;
//! Number of entries (lowest transfer \f$\Delta V\f$) to include in shortlist.
const int shortlistLength;
//! Path to shortlist file.
const std::string shortlistPath;
protected:
private:
};
//! Check lambert_scanner input parameters.
/*!
* Checks that all inputs for the lambert_scanner application mode are valid. If not, an error is
* thrown with a short description of the problem. If all inputs are valid, a data struct
* containing all the inputs is returned, which is subsequently used to execute lambert_scanner
* and related functions.
*
* @sa executeLambertScanner, LambertScannerInput
* @param[in] config User-defined configuration options (extracted from JSON input file)
* @return Struct containing all valid input to execute lambert_scanner
*/
LambertScannerInput checkLambertScannerInput( const rapidjson::Document& config );
//! Create lambert_scanner table.
/*!
* Creates lambert_scanner table in SQLite database used to store results obtaned from running
* the lambert_scanner application mode.
*
* @sa executeLambertScanner
* @param[in] database SQLite database handle
*/
void createLambertScannerTable( SQLite::Database& database );
//! Write transfer shortlist to file.
/*!
* Writes shortlist of debris-to-debris Lambert transfers to file. The shortlist is based on the
* requested number of transfers with the lowest transfer \f$\Delta V\f$, retrieved by sorting the
* transfers in the SQLite database.
*
* @sa executeLambertScanner, createLambertScannerTable
* @param[in] database SQLite database handle
* @param[in] shortlistNumber Number of entries to include in shortlist (if it exceeds number of
* entries in database table, the whole table is written to file)
* @param[in] shortlistPath Path to shortlist file
*/
void writeTransferShortlist( SQLite::Database& database,
const int shortlistNumber,
const std::string& shortlistPath );
} // namespace d2d
/*!
* Izzo, D. (2014) Revisiting Lambert's problem, http://arxiv.org/abs/1403.2705.
* Izzo, D. (2012) PyGMO and PyKEP: open source tools for massively parallel optimization in
* astrodynamics (the case of interplanetary trajectory optimization). Proceed. Fifth
* International Conf. Astrodynam. Tools and Techniques, ESA/ESTEC, The Netherlands.
*/
#endif // D2D_LAMBERT_SCANNER_HPP
<commit_msg>Update Doxygen short description for Lambert scanner input struct.<commit_after>/*
* Copyright (c) 2014-2016 Kartik Kumar, Dinamica Srl (me@kartikkumar.com)
* Distributed under the MIT License.
* See accompanying file LICENSE.md or copy at http://opensource.org/licenses/MIT
*/
#ifndef D2D_LAMBERT_SCANNER_HPP
#define D2D_LAMBERT_SCANNER_HPP
#include <string>
#include <keplerian_toolbox.h>
#include <libsgp4/DateTime.h>
#include <rapidjson/document.h>
#include <SQLiteCpp/SQLiteCpp.h>
namespace d2d
{
//! Execute lambert_scanner.
/*!
* Executes lambert_scanner application mode that performs a grid search to compute \f$\Delta V\f$
* for debris-to-debris transfers. The transfers are modelled as conic sections. The Lambert
* targeter employed is based on Izzo (2014), implemented in PyKEP (Izzo, 2012).
*
* The results obtained from the grid search are stored in a SQLite database, containing the
* following table:
*
* - "lambert_scanner_results": contains all Lambert transfers computed during grid search
*
* @param[in] config User-defined configuration options (extracted from JSON input file)
*/
void executeLambertScanner( const rapidjson::Document& config );
//! Input for lambert_scanner application mode.
/*!
* Data struct containing all valid lambert_scanner input parameters. This struct is populated by
* the checkLambertScannerInput() function and can be used to execute the lambert_scanner
* application mode.
*
* @sa checkLambertScannerInput, executeLambertScanner
*/
struct LambertScannerInput
{
public:
//! Construct data struct.
/*!
* Constructs data struct based on verified input parameters.
*
* @sa checkLambertScannerInput, executeLambertScanner
* @param[in] aCatalogPath Path to TLE catalog
* @param[in] aDatabasePath Path to SQLite database
* @param[in] aDepartureEpoch Departure epoch for all transfers
* @param[in] aTimeOfFlightMinimum Minimum time-of-flight [s]
* @param[in] aTimeOfFlightMaximum Maximum time-of-flight [s]
* @param[in] someTimeOfFlightSteps Number of steps to take in time-of-flight grid
* @param[in] aTimeOfFlightStepSize Time-of-flight step size (derived parameter) [s]
* @param[in] progradeFlag Flag indicating if prograde transfer should be computed
* (false = retrograde)
* @param[in] aRevolutionsMaximum Maximum number of revolutions
* @param[in] aShortlistLength Number of transfers to include in shortlist
* @param[in] aShortlistPath Path to shortlist file
*/
LambertScannerInput( const std::string& aCatalogPath,
const std::string& aDatabasePath,
const DateTime& aDepartureEpoch,
const double aTimeOfFlightMinimum,
const double aTimeOfFlightMaximum,
const double someTimeOfFlightSteps,
const double aTimeOfFlightStepSize,
const bool progradeFlag,
const int aRevolutionsMaximum,
const int aShortlistLength,
const std::string& aShortlistPath )
: catalogPath( aCatalogPath ),
databasePath( aDatabasePath ),
departureEpoch( aDepartureEpoch ),
timeOfFlightMinimum( aTimeOfFlightMinimum ),
timeOfFlightMaximum( aTimeOfFlightMaximum ),
timeOfFlightSteps( someTimeOfFlightSteps ),
timeOfFlightStepSize( aTimeOfFlightStepSize ),
isPrograde( progradeFlag ),
revolutionsMaximum( aRevolutionsMaximum ),
shortlistLength( aShortlistLength ),
shortlistPath( aShortlistPath )
{ }
//! Path to TLE catalog.
const std::string catalogPath;
//! Path to SQLite database to store output.
const std::string databasePath;
//! Departure epoch.
const DateTime departureEpoch;
//! Minimum time-of-flight [s].
const double timeOfFlightMinimum;
//! Maximum time-of-flight [s].
const double timeOfFlightMaximum;
//! Number of time-of-flight steps.
const double timeOfFlightSteps;
//! Time-of-flight step size [s].
const double timeOfFlightStepSize;
//! Flag indicating if transfers are prograde. False indicates retrograde.
const bool isPrograde;
//! Maximum number of revolutions (N) for transfer. Number of revolutions is 2*N+1.
const int revolutionsMaximum;
//! Number of entries (lowest transfer \f$\Delta V\f$) to include in shortlist.
const int shortlistLength;
//! Path to shortlist file.
const std::string shortlistPath;
protected:
private:
};
//! Check lambert_scanner input parameters.
/*!
* Checks that all inputs for the lambert_scanner application mode are valid. If not, an error is
* thrown with a short description of the problem. If all inputs are valid, a data struct
* containing all the inputs is returned, which is subsequently used to execute lambert_scanner
* and related functions.
*
* @sa executeLambertScanner, LambertScannerInput
* @param[in] config User-defined configuration options (extracted from JSON input file)
* @return Struct containing all valid input to execute lambert_scanner
*/
LambertScannerInput checkLambertScannerInput( const rapidjson::Document& config );
//! Create lambert_scanner table.
/*!
* Creates lambert_scanner table in SQLite database used to store results obtaned from running
* the lambert_scanner application mode.
*
* @sa executeLambertScanner
* @param[in] database SQLite database handle
*/
void createLambertScannerTable( SQLite::Database& database );
//! Write transfer shortlist to file.
/*!
* Writes shortlist of debris-to-debris Lambert transfers to file. The shortlist is based on the
* requested number of transfers with the lowest transfer \f$\Delta V\f$, retrieved by sorting the
* transfers in the SQLite database.
*
* @sa executeLambertScanner, createLambertScannerTable
* @param[in] database SQLite database handle
* @param[in] shortlistNumber Number of entries to include in shortlist (if it exceeds number of
* entries in database table, the whole table is written to file)
* @param[in] shortlistPath Path to shortlist file
*/
void writeTransferShortlist( SQLite::Database& database,
const int shortlistNumber,
const std::string& shortlistPath );
} // namespace d2d
/*!
* Izzo, D. (2014) Revisiting Lambert's problem, http://arxiv.org/abs/1403.2705.
* Izzo, D. (2012) PyGMO and PyKEP: open source tools for massively parallel optimization in
* astrodynamics (the case of interplanetary trajectory optimization). Proceed. Fifth
* International Conf. Astrodynam. Tools and Techniques, ESA/ESTEC, The Netherlands.
*/
#endif // D2D_LAMBERT_SCANNER_HPP
<|endoftext|> |
<commit_before>#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <map>
#include <set>
#include <stack>
#include <cstring>
#include <string>
#include <vector>
#include <iomanip>
#include <cmath>
#include <list>
#include <bitset>
using namespace std;
#define ll long long
#define lson l,mid,id<<1
#define rson mid+1,r,id<<1|1
typedef pair<int, int>pii;
typedef pair<ll, ll>pll;
typedef pair<double, double>pdd;
const double eps = 1e-6;
const ll LINF = 0x3f3f3f3f3f3f3f3fLL;
const int INF = 0x3f3f3f3f;
const double FINF = 1e18;
#define x first
#define y second
#define REP(i,j,k) for(int i =(j);i<=(k);i++)
#define REPD(i,j,k) for(int i =(j);i>=(k);i--)
#define print(x) cout<<(x)<<endl;
#define IOS ios::sync_with_stdio(0);cin.tie(0);
int dpa[1005],dpb[1005];
int c[1005];
int fa[1005];
int fb[1005];
int n,f;
int p1,p2;
int mina=INF,minb=INF;
void Init(){
cin>>n>>f>>p1>>p2;
REP(i,1,n){
cin>>c[i];
}
REP(i,1,n){
cin>>fa[i];
mina=min(mina,fa[i]);
}
REP(i,1,n){
cin>>fb[i];
minb=min(minb,fb[i]);
}
memset(dpa , 0 ,sizeof dpa);
memset(dpb , 0, sizeof dpb);
return ;
}
void Solve(){
int ansa,ansb;
REP(i,mina,f)
{
REP(j,1,n){
if(i>=fa[j]){
dpa[i]=max(dpa[i],dpa[i-fa[j]]+c[j]);
}
}
if(dpa[i]>=p1){
ansa=i;
break;
}
}
REP(i,minb,f){
REP(j,1,n){
if(i>=fb[j]){
dpb[i]=max(dpb[i],dpb[i-fb[j]]+c[j]);
}
}
if(dpb[i]>=p2){
ansb=i;
break;
}
}
if(ansa+ansb<=f){
print(1);
}else{
print(0);
}
return ;
}
int main(){
freopen("uoj10680.in","r",stdin);
int t;
scanf("%d",&t);
while(t--)
Init(),Solve();
return 0;
}<commit_msg>update uoj10680<commit_after>#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <map>
#include <set>
#include <stack>
#include <cstring>
#include <string>
#include <vector>
#include <iomanip>
#include <cmath>
#include <list>
#include <bitset>
using namespace std;
#define ll long long
#define lson l,mid,id<<1
#define rson mid+1,r,id<<1|1
typedef pair<int, int>pii;
typedef pair<ll, ll>pll;
typedef pair<double, double>pdd;
const double eps = 1e-6;
const ll LINF = 0x3f3f3f3f3f3f3f3fLL;
const int INF = 0x3f3f3f3f;
const double FINF = 1e18;
#define x first
#define y second
#define REP(i,j,k) for(int i =(j);i<=(k);i++)
#define REPD(i,j,k) for(int i =(j);i>=(k);i--)
#define print(x) cout<<(x)<<endl;
#define IOS ios::sync_with_stdio(0);cin.tie(0);
int dpa[1005],dpb[1005];
int c[1005];
int fa[1005];
int fb[1005];
int n,f;
int p1,p2;
int mina=INF,minb=INF;
void Init(){
cin>>n>>f>>p1>>p2;
REP(i,1,n){
cin>>c[i];
}
REP(i,1,n){
cin>>fa[i];
mina=min(mina,fa[i]);
}
REP(i,1,n){
cin>>fb[i];
minb=min(minb,fb[i]);
}
memset(dpa , 0 ,sizeof dpa);
memset(dpb , 0, sizeof dpb);
return ;
}
void Solve(){
int ansa,ansb;
REP(i,mina,f)
{
REP(j,1,n){
if(i>=fa[j]){
dpa[i]=max(dpa[i],dpa[i-fa[j]]+c[j]);
}
}
if(dpa[i]>=p1){
ansa=i;
break;
}
}
REP(i,minb,f){
REP(j,1,n){
if(i>=fb[j]){
dpb[i]=max(dpb[i],dpb[i-fb[j]]+c[j]);
}
}
if(dpb[i]>=p2){
ansb=i;
break;
}
}
if(ansa+ansb<=f){
print(1);
}else{
print(0);
}
return ;
}
int main(){
#ifdef LOCAL
freopen("uoj10680.in","r",stdin);
#endif
int t;
scanf("%d",&t);
while(t--)
Init(),Solve();
return 0;
}<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2012 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_VALUE_TYPES_HPP
#define MAPNIK_VALUE_TYPES_HPP
// mapnik
#include <mapnik/config.hpp>
// icu
#include <unicode/uversion.h> // for U_NAMESPACE_QUALIFIER
// stl
#include <type_traits>
#include <iosfwd>
#include <cstddef>
namespace U_ICU_NAMESPACE {
class UnicodeString;
}
namespace mapnik {
#ifdef BIGINT
//using value_integer = boost::long_long_type;
using value_integer = long long;
#else
using value_integer = int;
#endif
using value_double = double;
using value_unicode_string = U_NAMESPACE_QUALIFIER UnicodeString;
using value_bool = bool;
struct MAPNIK_DECL value_null
{
bool operator==(value_null const&) const
{
return true;
}
template <typename T>
bool operator==(T const&) const
{
return false;
}
bool operator!=(value_null const&) const
{
return false;
}
template <typename T>
bool operator!=(T const&) const
{
return true;
}
template <typename T>
value_null operator+ (T const&) const
{
return *this;
}
template <typename T>
value_null operator- (T const&) const
{
return *this;
}
template <typename T>
value_null operator* (T const&) const
{
return *this;
}
template <typename T>
value_null operator/ (T const&) const
{
return *this;
}
template <typename T>
value_null operator% (T const&) const
{
return *this;
}
};
inline std::size_t hash_value(value_null const&)
{
return 0;
}
template <typename TChar, typename TTraits>
inline std::basic_ostream<TChar, TTraits>& operator<<(std::basic_ostream<TChar, TTraits>& out, value_null const& v)
{
return out;
}
inline std::istream& operator>> ( std::istream & s, value_null & )
{
return s;
}
namespace detail {
// to mapnik::value_type conversions traits
template <typename T>
struct is_value_bool
{
bool value = std::is_same<T, bool>::value;
};
template <typename T>
struct is_value_integer
{
bool value = std::is_integral<T>::value && !std::is_same<T, bool>::value;
};
template <typename T>
struct is_value_double
{
bool value = std::is_floating_point<T>::value;
};
template <typename T>
struct is_value_unicode_string
{
bool value = std::is_same<T,mapnik::value_unicode_string>::value;
};
template <typename T>
struct is_value_string
{
bool value = std::is_same<T,std::string>::value;
};
template <typename T>
struct is_value_null
{
bool value = std::is_same<T, value_null>::value;
};
template <typename T, class Enable = void>
struct mapnik_value_type
{
using type = T;
};
// value_null
template <typename T>
struct mapnik_value_type<T, typename std::enable_if<detail::is_value_null<T>::value>::type>
{
using type = mapnik::value_null;
};
// value_bool
template <typename T>
struct mapnik_value_type<T, typename std::enable_if<detail::is_value_bool<T>::value>::type>
{
using type = mapnik::value_bool;
};
// value_integer
template <typename T>
struct mapnik_value_type<T, typename std::enable_if<detail::is_value_integer<T>::value>::type>
{
using type = mapnik::value_integer;
};
// value_double
template <typename T>
struct mapnik_value_type<T, typename std::enable_if<detail::is_value_double<T>::value>::type>
{
using type = mapnik::value_double;
};
// value_unicode_string
template <typename T>
struct mapnik_value_type<T, typename std::enable_if<detail::is_value_unicode_string<T>::value>::type>
{
using type = mapnik::value_unicode_string;
};
} // namespace detail
} // namespace mapnik
#endif // MAPNIK_VALUE_TYPES_HPP
<commit_msg>fix compile with gcc<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2012 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_VALUE_TYPES_HPP
#define MAPNIK_VALUE_TYPES_HPP
// mapnik
#include <mapnik/config.hpp>
// icu
#include <unicode/uversion.h> // for U_NAMESPACE_QUALIFIER
// stl
#include <type_traits>
#include <iosfwd>
#include <cstddef>
namespace U_ICU_NAMESPACE {
class UnicodeString;
}
namespace mapnik {
#ifdef BIGINT
//using value_integer = boost::long_long_type;
using value_integer = long long;
#else
using value_integer = int;
#endif
using value_double = double;
using value_unicode_string = U_NAMESPACE_QUALIFIER UnicodeString;
using value_bool = bool;
struct MAPNIK_DECL value_null
{
bool operator==(value_null const&) const
{
return true;
}
template <typename T>
bool operator==(T const&) const
{
return false;
}
bool operator!=(value_null const&) const
{
return false;
}
template <typename T>
bool operator!=(T const&) const
{
return true;
}
template <typename T>
value_null operator+ (T const&) const
{
return *this;
}
template <typename T>
value_null operator- (T const&) const
{
return *this;
}
template <typename T>
value_null operator* (T const&) const
{
return *this;
}
template <typename T>
value_null operator/ (T const&) const
{
return *this;
}
template <typename T>
value_null operator% (T const&) const
{
return *this;
}
};
inline std::size_t hash_value(value_null const&)
{
return 0;
}
template <typename TChar, typename TTraits>
inline std::basic_ostream<TChar, TTraits>& operator<<(std::basic_ostream<TChar, TTraits>& out, value_null const& v)
{
return out;
}
inline std::istream& operator>> ( std::istream & s, value_null & )
{
return s;
}
namespace detail {
// to mapnik::value_type conversions traits
template <typename T>
struct is_value_bool
{
constexpr static bool value = std::is_same<T, bool>::value;
};
template <typename T>
struct is_value_integer
{
constexpr static bool value = std::is_integral<T>::value && !std::is_same<T, bool>::value;
};
template <typename T>
struct is_value_double
{
constexpr static bool value = std::is_floating_point<T>::value;
};
template <typename T>
struct is_value_unicode_string
{
constexpr static bool value = std::is_same<T, typename mapnik::value_unicode_string>::value;
};
template <typename T>
struct is_value_string
{
constexpr static bool value = std::is_same<T, typename std::string>::value;
};
template <typename T>
struct is_value_null
{
constexpr static bool value = std::is_same<T, typename mapnik::value_null>::value;
};
template <typename T, class Enable = void>
struct mapnik_value_type
{
using type = T;
};
// value_null
template <typename T>
struct mapnik_value_type<T, typename std::enable_if<detail::is_value_null<T>::value>::type>
{
using type = mapnik::value_null;
};
// value_bool
template <typename T>
struct mapnik_value_type<T, typename std::enable_if<detail::is_value_bool<T>::value>::type>
{
using type = mapnik::value_bool;
};
// value_integer
template <typename T>
struct mapnik_value_type<T, typename std::enable_if<detail::is_value_integer<T>::value>::type>
{
using type = mapnik::value_integer;
};
// value_double
template <typename T>
struct mapnik_value_type<T, typename std::enable_if<detail::is_value_double<T>::value>::type>
{
using type = mapnik::value_double;
};
// value_unicode_string
template <typename T>
struct mapnik_value_type<T, typename std::enable_if<detail::is_value_unicode_string<T>::value>::type>
{
using type = mapnik::value_unicode_string;
};
} // namespace detail
} // namespace mapnik
#endif // MAPNIK_VALUE_TYPES_HPP
<|endoftext|> |
<commit_before>/**
* \file
*/
#pragma once
#include "bases.hpp"
#include "type_name.hpp"
#include <string>
#include <type_traits>
#include <typeindex>
#include <unordered_set>
#include <utility>
namespace module_loader {
/**
* A convenience base class for implementing
* \ref object or \ref offer.
*
* \tparam T
* The type being represented or offered.
* \tparam Base
* \ref object or \ref offer.
*/
template <typename T, typename Base>
class base : public Base {
template <typename, typename>
friend class base;
public:
using provides_type = typename Base::provides_type;
private:
std::string name_;
provides_type provides_;
static constexpr bool is_nothrow = std::is_same<T,void>::value &&
std::is_nothrow_default_constructible<provides_type>::value &&
std::is_nothrow_move_constructible<provides_type>::value;
static provides_type get_provides (std::true_type) noexcept(is_nothrow) {
return provides_type{};
}
static provides_type get_provides (std::false_type) {
return public_unambiguous_bases<T>();
}
static provides_type get_provides () noexcept(is_nothrow) {
return get_provides(typename std::is_same<T,void>::type{});
}
public:
base ()
: name_(type_name<T>()),
provides_(get_provides())
{ }
template <typename U, typename V>
explicit base (base<U,V> & other) noexcept(
std::is_nothrow_default_constructible<std::string>::value &&
std::is_nothrow_default_constructible<provides_type>::value &&
std::is_nothrow_default_constructible<Base>::value
) {
using std::swap;
swap(name_,other.name_);
swap(provides_,other.provides_);
}
explicit base (std::string name) noexcept(is_nothrow && std::is_nothrow_move_constructible<std::string>::value)
: name_(std::move(name)),
provides_(get_provides())
{ }
virtual const std::string & name () const noexcept override {
return name_;
}
virtual const provides_type & provides () const noexcept override {
return provides_;
}
};
}
<commit_msg>module_loader::base - Copy<commit_after>/**
* \file
*/
#pragma once
#include "bases.hpp"
#include "type_name.hpp"
#include <string>
#include <type_traits>
#include <typeindex>
#include <unordered_set>
#include <utility>
namespace module_loader {
/**
* A convenience base class for implementing
* \ref object or \ref offer.
*
* \tparam T
* The type being represented or offered.
* \tparam Base
* \ref object or \ref offer.
*/
template <typename T, typename Base>
class base : public Base {
public:
using provides_type = typename Base::provides_type;
private:
std::string name_;
provides_type provides_;
static constexpr bool is_nothrow = std::is_same<T,void>::value &&
std::is_nothrow_default_constructible<provides_type>::value &&
std::is_nothrow_move_constructible<provides_type>::value;
static provides_type get_provides (std::true_type) noexcept(is_nothrow) {
return provides_type{};
}
static provides_type get_provides (std::false_type) {
return public_unambiguous_bases<T>();
}
static provides_type get_provides () noexcept(is_nothrow) {
return get_provides(typename std::is_same<T,void>::type{});
}
public:
base ()
: name_(type_name<T>()),
provides_(get_provides())
{ }
template <typename U, typename V>
explicit base (base<U,V> & other)
: name_(other.name()),
provides_(get_provides())
{ }
explicit base (std::string name) noexcept(is_nothrow && std::is_nothrow_move_constructible<std::string>::value)
: name_(std::move(name)),
provides_(get_provides())
{ }
virtual const std::string & name () const noexcept override {
return name_;
}
virtual const provides_type & provides () const noexcept override {
return provides_;
}
};
}
<|endoftext|> |
<commit_before>#ifndef _NEVIL_ARENA_SWITCH_HPP_
#define _NEVIL_ARENA_SWITCH_HPP_
#include "nevil/arena/object.hpp"
namespace nevil
{
class switch_object : public object
{
public:
switch_object();
switch_object(int x, int y, double size_x, double size_y, double height,
const Enki::Color &off_color=Enki::Color(0.4, 0.0, 1.0),
const Enki::Color &on_color=Enki::Color(0.7, 1.0, 1.0));
virtual ~switch_object();
void turn_on();
void turn_off();
};
}
#endif // _NEVIL_ARENA_SWITCH_HPP_<commit_msg>changed red value of the on switch<commit_after>#ifndef _NEVIL_ARENA_SWITCH_HPP_
#define _NEVIL_ARENA_SWITCH_HPP_
#include "nevil/arena/object.hpp"
namespace nevil
{
class switch_object : public object
{
public:
switch_object();
switch_object(int x, int y, double size_x, double size_y, double height,
const Enki::Color &off_color=Enki::Color(0.4, 0.0, 1.0),
const Enki::Color &on_color=Enki::Color(0.9, 1.0, 1.0));
virtual ~switch_object();
void turn_on();
void turn_off();
};
}
#endif // _NEVIL_ARENA_SWITCH_HPP_<|endoftext|> |
<commit_before>#ifndef __SGE_ASSET_MANAGER_HPP
#define __SGE_ASSET_MANAGER_HPP
#include <sge/assets/locator.hpp>
#include <sge/assets/loader.hpp>
#include <sge/assets/asset.hpp>
#include <sge/assets/cache.hpp>
#include <unordered_map>
#include <iostream>
#include <memory>
#include <string>
#include <vector>
namespace sge
{
class AssetManager
{
private:
std::vector<std::shared_ptr<AssetLocator>> locators;
std::unordered_map<std::string, std::shared_ptr<AssetLoader>> loaders;
AssetCache cache;
public:
void register_locator(std::shared_ptr<AssetLocator> locator);
void register_loader(std::shared_ptr<AssetLoader> loader, const std::vector<std::string> &extensions);
void unload(BaseAsset *asset);
template <typename A, typename D>
std::shared_ptr<A> load(const D &assetdesc)
{
static_assert(std::is_base_of<BaseAsset, A>::value, "Supplied asset type does not inherit from Asset");
static_assert(std::is_base_of<AssetDescriptor, D>::value, "Supplied descriptor type does not inherit from AssetDescriptor");
auto passetdesc = std::make_shared<D>(assetdesc);
std::shared_ptr<A> asset = nullptr;
if (cache.find(passetdesc) == cache.end())
{
SDL_RWops *input = nullptr;
for (auto &locator : locators)
{
try
{
input = locator->locate(passetdesc->name());
}
catch (const AssetLocatorError &e)
{
std::cerr << "[AssetLocatorError] " << e.what() << std::endl;
input = nullptr;
}
if (input != nullptr)
{
break;
}
}
if (input != nullptr)
{
if (loaders.find(passetdesc->extension()) != loaders.end())
{
auto loader = loaders[passetdesc->extension()];
asset = std::shared_ptr<A>(
new A(loader, passetdesc),
[&](A *ptr_asset)
{
BaseAsset *ptr_basset = static_cast<BaseAsset *>(ptr_asset);
unload(ptr_basset);
}
);
try
{
loader->load(asset, input);
}
catch (const AssetLoaderError &e)
{
std::cerr << "[AssetLoaderError] " << e.what() << std::endl;
asset.reset();
}
if (asset != nullptr)
{
cache[passetdesc] = std::static_pointer_cast<BaseAsset>(asset);
}
}
else
{
std::cerr << "[AssetLoaderError] No loader found for extension: " << passetdesc->extension() << std::endl;
}
}
else
{
std::cerr << "[AssetLocatorError] Request asset not found by any locator: " << passetdesc->name() << std::endl;
}
}
else
{
asset = std::static_pointer_cast<A>(cache[passetdesc].lock());
}
return asset;
}
};
}
#endif /* __SGE_ASSET_MANAGER_HPP */
<commit_msg>make AssetManager::unload() private<commit_after>#ifndef __SGE_ASSET_MANAGER_HPP
#define __SGE_ASSET_MANAGER_HPP
#include <sge/assets/locator.hpp>
#include <sge/assets/loader.hpp>
#include <sge/assets/asset.hpp>
#include <sge/assets/cache.hpp>
#include <unordered_map>
#include <iostream>
#include <memory>
#include <string>
#include <vector>
namespace sge
{
class AssetManager
{
private:
std::vector<std::shared_ptr<AssetLocator>> locators;
std::unordered_map<std::string, std::shared_ptr<AssetLoader>> loaders;
AssetCache cache;
public:
void register_locator(std::shared_ptr<AssetLocator> locator);
void register_loader(std::shared_ptr<AssetLoader> loader, const std::vector<std::string> &extensions);
template <typename A, typename D>
std::shared_ptr<A> load(const D &assetdesc)
{
static_assert(std::is_base_of<BaseAsset, A>::value, "Supplied asset type does not inherit from Asset");
static_assert(std::is_base_of<AssetDescriptor, D>::value, "Supplied descriptor type does not inherit from AssetDescriptor");
auto passetdesc = std::make_shared<D>(assetdesc);
std::shared_ptr<A> asset = nullptr;
if (cache.find(passetdesc) == cache.end())
{
SDL_RWops *input = nullptr;
for (auto &locator : locators)
{
try
{
input = locator->locate(passetdesc->name());
}
catch (const AssetLocatorError &e)
{
std::cerr << "[AssetLocatorError] " << e.what() << std::endl;
input = nullptr;
}
if (input != nullptr)
{
break;
}
}
if (input != nullptr)
{
if (loaders.find(passetdesc->extension()) != loaders.end())
{
auto loader = loaders[passetdesc->extension()];
asset = std::shared_ptr<A>(
new A(loader, passetdesc),
[&](A *ptr_asset)
{
BaseAsset *ptr_basset = static_cast<BaseAsset *>(ptr_asset);
unload(ptr_basset);
}
);
try
{
loader->load(asset, input);
}
catch (const AssetLoaderError &e)
{
std::cerr << "[AssetLoaderError] " << e.what() << std::endl;
asset.reset();
}
if (asset != nullptr)
{
cache[passetdesc] = std::static_pointer_cast<BaseAsset>(asset);
}
}
else
{
std::cerr << "[AssetLoaderError] No loader found for extension: " << passetdesc->extension() << std::endl;
}
}
else
{
std::cerr << "[AssetLocatorError] Request asset not found by any locator: " << passetdesc->name() << std::endl;
}
}
else
{
asset = std::static_pointer_cast<A>(cache[passetdesc].lock());
}
return asset;
}
private:
void unload(BaseAsset *asset);
};
}
#endif /* __SGE_ASSET_MANAGER_HPP */
<|endoftext|> |
<commit_before>//============================================================================
// include/vsmc/utility/rdtsc.hpp
//----------------------------------------------------------------------------
//
// vSMC: Scalable Monte Carlo
//
// This file is distributed under the 2-clauses BSD License.
// See LICENSE for details.
//============================================================================
#ifndef VSMC_UTILITY_RDTSC_HPP
#define VSMC_UTILITY_RDTSC_HPP
#include <vsmc/internal/common.hpp>
#ifdef _MSC_VER
#include <intrin.h>
#endif
namespace vsmc {
/// \brief Return the TSC value using RDTSC instruction after synchronization
/// with CPUID instruction
/// \ingroup RDTSC
inline uint64_t rdtsc ()
{
#ifdef _MSC_VER
int aux[4];
__cpuidex(aux, 0, 0);
return static_cast<uint64_t>(__rdtsc());
#else // _MSC_VER
unsigned eax = 0;
unsigned ecx = 0;
unsigned edx = 0;
__asm__ volatile
(
"cpuid\n\t"
"rdtsc\n"
: "=a" (eax), "=d" (edx)
: "a" (eax), "c" (ecx)
);
return (static_cast<uint64_t>(edx) << 32) + static_cast<uint64_t>(eax);
#endif // _MSC_VER
}
/// \brief Return the TSC and TSC_AUX values using RDTSCP instruction
/// \ingroup RDTSC
inline uint64_t rdtscp (unsigned *aux)
{
#ifdef _MSC_VER
return static_cast<uint64_t>(__rdtscp(aux));
#else // _MSC_VER
unsigned eax = 0;
unsigned edx = 0;
unsigned ecx = 0;
__asm__ volatile
(
"rdtscp\n"
: "=a" (eax), "=c" (ecx), "=d" (edx)
);
*aux = ecx;
return static_cast<uint64_t>(eax) + (static_cast<uint64_t>(edx) << 32);
#endif // _MSC_VER
}
/// \brief CPU clock cycle counter using RDTSC
/// \ingroup RDTSC
class RDTSCCounter
{
public :
RDTSCCounter () : elapsed_(0), start_(0), running_(false) {}
/// \brief If the counter is running
///
/// \details
/// If `start()` has been called and no `stop()` call since, then it is
/// running, otherwise it is stoped.
bool running () const {return running_;}
/// \brief Start the counter, no effect if already started
///
/// \return `true` if it is started by this call, and the elapsed cycle
/// count will be incremented next time `stop()` is called. The increment
/// will be relative to the time point of this call. `false` if it is
/// already started earlier.
bool start ()
{
if (running_)
return false;
running_ = true;
start_ = rdtsc();
return true;
}
/// \brief Stop the counter, no effect if already stopped
///
/// \return `true` if it is stoped by this call, and the elapsed cycle
/// count has been incremented. `false` in one of the following situations.
/// In all these situations, the elapsed cycle count will not be
/// incremented.
/// - It already stopped or wasn't started before.
/// - The cycle count appears to decrease. This is most likely in the case
/// that the TSC MSR has been reset.
bool stop ()
{
if (!running_)
return false;
uint64_t stop = rdtsc();
if (stop < start_)
return false;
elapsed_ += stop - start_;
running_ = false;
return true;
}
/// \brief Stop and reset the elapsed cycle count to zero
void reset ()
{
elapsed_ = 0;
running_ = false;
}
/// \brief Return the accumulated elapsed cycle count
uint64_t cycles () const {return elapsed_;}
private :
uint64_t elapsed_;
uint64_t start_;
bool running_;
}; // class RDTSCCounter
/// \brief CPU clock cycle counter using RDTSCP
/// \ingroup RDTSC
///
/// \details
/// This class shall only be used if RDTSCP is supported. For example,
/// ~~~{.cpp}
/// RDTSCCouner c1;
/// RDTSCPCouner c2;
/// CPUID::has_feature<CPUIDFeatureExtRDTSCP>() ? c2.start() : c1.start();
/// ~~~
class RDTSCPCounter
{
public :
RDTSCPCounter () : elapsed_(0), start_(0), start_id_(0), running_(false) {}
/// \brief If the counter is running
///
/// \details
/// If `start()` has been called and no `stop()` call since, then it is
/// running, otherwise it is stoped.
bool running () const {return running_;}
/// \brief Start the counter, no effect if already started
///
/// \return `true` if it is started by this call, and the elapsed cycle
/// count will be incremented next time `stop()` is called. The increment
/// will be relative to the time point of this call. `false` if it is
/// already started earlier.
bool start ()
{
if (running_)
return false;
running_ = true;
start_ = rdtscp(&start_id_);
return true;
}
/// \brief Stop the counter, no effect if already stopped
///
/// \return `true` if it is stoped by this call, and the elapsed cycle
/// count has been incremented. `false` in one of the following situations.
/// In all these situations, the elapsed cycle count will not be
/// incremented.
/// - It already stopped or wasn't started before.
/// - The logical processor has changed since the last successful `start()`
/// call. The user is repsonsible for assure threads affinity.
/// - The cycle count appears to decrease. This is most likely in the case
/// that the TSC MSR has been reset.
bool stop ()
{
if (!running_)
return false;
unsigned stop_id = 0;
uint64_t stop = rdtscp(&stop_id);
if (stop_id != start_id_ || stop < start_)
return false;
elapsed_ += stop - start_;
running_ = false;
return true;
}
/// \brief Stop and reset the elapsed cycle count to zero
void reset ()
{
elapsed_ = 0;
running_ = false;
}
/// \brief Return the accumulated elapsed cycle count
uint64_t cycles () const {return elapsed_;}
private :
uint64_t elapsed_;
uint64_t start_;
unsigned start_id_;
bool running_;
}; // class RDTSCPCounter
} // namespace vsmc
#endif // VSMC_UTILITY_RDTSC_HPP
<commit_msg>Fix RDTSC counter and remove sync by CPUID<commit_after>//============================================================================
// include/vsmc/utility/rdtsc.hpp
//----------------------------------------------------------------------------
//
// vSMC: Scalable Monte Carlo
//
// This file is distributed under the 2-clauses BSD License.
// See LICENSE for details.
//============================================================================
#ifndef VSMC_UTILITY_RDTSC_HPP
#define VSMC_UTILITY_RDTSC_HPP
#include <vsmc/internal/common.hpp>
#ifdef _MSC_VER
#include <intrin.h>
#endif
namespace vsmc {
/// \brief Return the TSC value using RDTSC instruction
/// \ingroup RDTSC
inline uint64_t rdtsc ()
{
#ifdef _MSC_VER
return static_cast<uint64_t>(__rdtsc());
#else // _MSC_VER
unsigned eax = 0;
unsigned edx = 0;
__asm__ volatile
(
"rdtsc\n"
: "=a" (eax), "=d" (edx)
);
return (static_cast<uint64_t>(edx) << 32) + static_cast<uint64_t>(eax);
#endif // _MSC_VER
}
/// \brief Return the TSC and TSC_AUX values using RDTSCP instruction
/// \ingroup RDTSC
inline uint64_t rdtscp (unsigned *aux)
{
#ifdef _MSC_VER
return static_cast<uint64_t>(__rdtscp(aux));
#else // _MSC_VER
unsigned eax = 0;
unsigned ecx = 0;
unsigned edx = 0;
__asm__ volatile
(
"rdtscp\n"
: "=a" (eax), "=c" (ecx), "=d" (edx)
);
*aux = ecx;
return static_cast<uint64_t>(eax) + (static_cast<uint64_t>(edx) << 32);
#endif // _MSC_VER
}
/// \brief CPU clock cycle counter using RDTSC
/// \ingroup RDTSC
class RDTSCCounter
{
public :
RDTSCCounter () : elapsed_(0), start_(0), running_(false) {}
/// \brief If the counter is running
///
/// \details
/// If `start()` has been called and no `stop()` call since, then it is
/// running, otherwise it is stoped.
bool running () const {return running_;}
/// \brief Start the counter, no effect if already started
///
/// \return `true` if it is started by this call, and the elapsed cycle
/// count will be incremented next time `stop()` is called. The increment
/// will be relative to the time point of this call. `false` if it is
/// already started earlier.
bool start ()
{
if (running_)
return false;
running_ = true;
start_ = rdtsc();
return true;
}
/// \brief Stop the counter, no effect if already stopped
///
/// \return `true` if it is stoped by this call, and the elapsed cycle
/// count has been incremented. `false` in one of the following situations.
/// In all these situations, the elapsed cycle count will not be
/// incremented.
/// - It already stopped or wasn't started before.
/// - The cycle count appears to decrease. This is most likely in the case
/// that the TSC MSR has been reset.
bool stop ()
{
if (!running_)
return false;
uint64_t stop = rdtsc();
if (stop < start_)
return false;
elapsed_ += stop - start_;
running_ = false;
return true;
}
/// \brief Stop and reset the elapsed cycle count to zero
void reset ()
{
elapsed_ = 0;
running_ = false;
}
/// \brief Return the accumulated elapsed cycle count
uint64_t cycles () const {return elapsed_;}
private :
uint64_t elapsed_;
uint64_t start_;
bool running_;
}; // class RDTSCCounter
/// \brief CPU clock cycle counter using RDTSCP
/// \ingroup RDTSC
///
/// \details
/// This class shall only be used if RDTSCP is supported. For example,
/// ~~~{.cpp}
/// RDTSCCouner c1;
/// RDTSCPCouner c2;
/// CPUID::has_feature<CPUIDFeatureExtRDTSCP>() ? c2.start() : c1.start();
/// ~~~
class RDTSCPCounter
{
public :
RDTSCPCounter () : elapsed_(0), start_(0), start_id_(0), running_(false) {}
/// \brief If the counter is running
///
/// \details
/// If `start()` has been called and no `stop()` call since, then it is
/// running, otherwise it is stoped.
bool running () const {return running_;}
/// \brief Start the counter, no effect if already started
///
/// \return `true` if it is started by this call, and the elapsed cycle
/// count will be incremented next time `stop()` is called. The increment
/// will be relative to the time point of this call. `false` if it is
/// already started earlier.
bool start ()
{
if (running_)
return false;
running_ = true;
start_ = rdtscp(&start_id_);
return true;
}
/// \brief Stop the counter, no effect if already stopped
///
/// \return `true` if it is stoped by this call, and the elapsed cycle
/// count has been incremented. `false` in one of the following situations.
/// In all these situations, the elapsed cycle count will not be
/// incremented.
/// - It already stopped or wasn't started before.
/// - The logical processor has changed since the last successful `start()`
/// call. The user is repsonsible for assure threads affinity.
/// - The cycle count appears to decrease. This is most likely in the case
/// that the TSC MSR has been reset.
bool stop ()
{
if (!running_)
return false;
unsigned stop_id = 0;
uint64_t stop = rdtscp(&stop_id);
if (stop_id != start_id_ || stop < start_)
return false;
elapsed_ += stop - start_;
running_ = false;
return true;
}
/// \brief Stop and reset the elapsed cycle count to zero
void reset ()
{
elapsed_ = 0;
running_ = false;
}
/// \brief Return the accumulated elapsed cycle count
uint64_t cycles () const {return elapsed_;}
private :
uint64_t elapsed_;
uint64_t start_;
unsigned start_id_;
bool running_;
}; // class RDTSCPCounter
} // namespace vsmc
#endif // VSMC_UTILITY_RDTSC_HPP
<|endoftext|> |
<commit_before>#pragma once
#include <gcl/mp/meta/functional.hpp>
namespace gcl::mp
{
template <std::size_t index>
struct type_index {};
template <typename... types>
struct tuple {
constexpr static auto size = sizeof...(types);
constexpr static auto empty = size == 0;
constexpr tuple() requires(not empty)
: storage{generate_storage(types{}...)}
{}
constexpr tuple(types&&... values)
: storage{generate_storage(std::forward<decltype(values)>(values)...)}
{}
constexpr tuple(tuple&&) = default;
private:
// storage : by-pass missing features : auto non-static members, lambdas in unevaluated context
/*static constexpr auto generate_storage(types&&... values)
{
return [&values...]<std::size_t... indexes>(std::index_sequence<indexes...>)
{
static_assert(sizeof...(indexes) == sizeof...(types));
static_assert(sizeof...(indexes) == sizeof...(values));
const auto generate_storage_entry = []<typename T, std::size_t index>(T && init_value) constexpr
{
return [value = init_value](type_index<index>) mutable -> auto& { return value; };
};
return gcl::mp::meta::functional::overload{generate_storage_entry.template operator()<types, indexes>(
std::forward<decltype(values)>(values))...};
}
(std::make_index_sequence<sizeof...(types)>{});
};*/
static constexpr auto generate_storage(types&&... values)
{
const auto generate_storage_entry = []<typename T, std::size_t index>(T && init_value) constexpr
{
return [value = init_value](type_index<index>) mutable -> auto& { return value; };
};
#if defined(_MSC_VER) and not defined(__clang__)
return [&]<std::size_t... indexes>(std::index_sequence<indexes...>)
#else
return [&generate_storage_entry, &values... ]<std::size_t... indexes>(std::index_sequence<indexes...>)
#endif
{
static_assert(sizeof...(indexes) == sizeof...(types));
static_assert(sizeof...(indexes) == sizeof...(values));
return gcl::mp::meta::functional::overload{generate_storage_entry.template operator()<types, indexes>(
std::forward<decltype(values)>(values))...};
}
(std::make_index_sequence<sizeof...(types)>{});
};
decltype(generate_storage(types{}...)) storage;
template <std::size_t index>
struct type_at_impl { // defer symbol (Clang)
using type = std::remove_reference_t<decltype(std::declval<tuple>().template get<index>())>;
};
public:
template <std::size_t index>
using type_at = typename type_at_impl<index>::type;
template <std::size_t index>
requires(not empty and index <= (size - 1)) constexpr auto& get()
{
return storage(type_index<index>{});
}
template <std::size_t index>
requires(not empty and index <= (size - 1)) constexpr const auto& get() const
{
return const_cast<tuple*>(this)->get<index>(); // violate constness invariants
}
template <typename... arg_types>
requires(sizeof...(arg_types) == size) constexpr bool operator==(const tuple<arg_types...>& other) const
{
return [ this, &other ]<std::size_t... indexes>(std::index_sequence<indexes...>)
{
return (((get<indexes>() == other.template get<indexes>()) && ...));
}
(std::make_index_sequence<size>{});
}
};
}
namespace gcl::mp::tests
{
using namespace gcl::mp;
using empty_tuple = tuple<>;
using one_element_tuple = tuple<int>;
using two_element_tuple = tuple<int, char>;
static constexpr auto empty_tuple_default_init = empty_tuple{};
//static constexpr auto one_element_tuple_default_init = one_element_tuple{};
/*static constexpr auto one_element_tuple_values_init = one_element_tuple{42};
static constexpr auto two_element_tuple_default_init = two_element_tuple{};
static constexpr auto two_element_tuple_values_init = two_element_tuple{42, 'a'};
static_assert(std::is_same_v<tuple<int, char>, decltype(tuple{42, 'a'})>);
static_assert(std::is_same_v<two_element_tuple::type_at<0>, int>);
static_assert(std::is_same_v<two_element_tuple::type_at<1>, char>);
static_assert(std::is_same_v<decltype(std::declval<two_element_tuple>().get<0>()), int&>);
static_assert(std::is_same_v<decltype(std::declval<const two_element_tuple&>().get<1>()), const char&>);*/
}<commit_msg>[mp/meta/tuple] : fix Clang, msvc-cl ICEs<commit_after>#pragma once
#include <gcl/mp/meta/functional.hpp>
namespace gcl::mp
{
template <std::size_t index>
struct type_index {};
template <typename... types>
struct tuple {
constexpr static auto size = sizeof...(types);
constexpr static auto empty = size == 0;
constexpr tuple() requires(not empty)
: storage{generate_storage(types{}...)}
{}
constexpr tuple(types&&... values)
: storage{generate_storage(std::forward<decltype(values)>(values)...)}
{}
constexpr tuple(tuple&&) = default;
private:
// storage : by-pass missing features : auto non-static members, lambdas in unevaluated context
using index_sequence = std::make_index_sequence<sizeof...(types)>;
static constexpr auto generate_storage(types&&... values)
{ // defer parameter pack expansion (msvc-cl, Clang)
return generate_storage_impl(index_sequence{}, std::forward<decltype(values)>(values)...);
}
template <std::size_t... indexes>
static constexpr auto generate_storage_impl(std::index_sequence<indexes...>, types&&... values)
{
static_assert(sizeof...(indexes) == sizeof...(types));
static_assert(sizeof...(indexes) == sizeof...(values));
const auto generate_storage_entry = []<typename T, std::size_t index>(T && init_value) constexpr
{
return [value = init_value](type_index<index>) mutable -> auto& { return value; };
};
return gcl::mp::meta::functional::overload{
generate_storage_entry.template operator()<types, indexes>(std::forward<decltype(values)>(values))...};
};
using storage_type = decltype(generate_storage(types{}...));
storage_type storage;
template <std::size_t index>
struct type_at_impl { // defer symbol (Clang)
using type = std::remove_reference_t<decltype(std::declval<tuple>().template get<index>())>;
};
public:
template <std::size_t index>
using type_at = typename type_at_impl<index>::type;
template <std::size_t index>
requires(not empty and index <= (size - 1)) constexpr auto& get()
{
return storage(type_index<index>{});
}
template <std::size_t index>
requires(not empty and index <= (size - 1)) constexpr const auto& get() const
{
return const_cast<tuple*>(this)->get<index>(); // violate constness invariants
}
template <typename... arg_types>
requires(sizeof...(arg_types) == size) constexpr bool operator==(const tuple<arg_types...>& other) const
{
return [ this, &other ]<std::size_t... indexes>(std::index_sequence<indexes...>)
{
return (((get<indexes>() == other.template get<indexes>()) && ...));
}
(std::make_index_sequence<size>{});
}
};
}
// When Clang, Msvc-cl gets better, replace `tuple::generate_storage` implementation by :
/*static constexpr auto generate_storage(types&&... values)
{
return [&values...]<std::size_t... indexes>(std::index_sequence<indexes...>)
{
static_assert(sizeof...(indexes) == sizeof...(types));
static_assert(sizeof...(indexes) == sizeof...(values));
const auto generate_storage_entry = []<typename T, std::size_t index>(T && init_value) constexpr
{
return [value = init_value](type_index<index>) mutable -> auto& { return value; };
};
return gcl::mp::meta::functional::overload{generate_storage_entry.template operator()<types, indexes>(
std::forward<decltype(values)>(values))...};
}
(std::make_index_sequence<sizeof...(types)>{});
};*/
namespace gcl::mp::tests
{
using namespace gcl::mp;
using empty_tuple = tuple<>;
using one_element_tuple = tuple<int>;
using two_element_tuple = tuple<int, char>;
static constexpr auto empty_tuple_default_init = empty_tuple{};
static constexpr auto one_element_tuple_default_init = one_element_tuple{};
static constexpr auto one_element_tuple_values_init = one_element_tuple{42};
static constexpr auto two_element_tuple_default_init = two_element_tuple{};
static constexpr auto two_element_tuple_values_init = two_element_tuple{42, 'a'};
static_assert(std::is_same_v<tuple<int, char>, decltype(tuple{42, 'a'})>);
static_assert(std::is_same_v<two_element_tuple::type_at<0>, int>);
static_assert(std::is_same_v<two_element_tuple::type_at<1>, char>);
static_assert(std::is_same_v<decltype(std::declval<two_element_tuple>().get<0>()), int&>);
static_assert(std::is_same_v<decltype(std::declval<const two_element_tuple&>().get<1>()), const char&>);
}<|endoftext|> |
<commit_before>#pragma once
#include <new>
#include <memory>
#include <utility>
#include <uv.h>
#include <type_traits>
#include "error.hpp"
namespace uvw {
class Loop;
template<typename R>
class Handle {
friend class Loop;
template<typename... Args>
explicit constexpr Handle(uv_loop_t *loop, Args&&... args)
: res{std::make_shared<R>(loop, std::forward<Args>(args)...)}
{ }
public:
constexpr Handle(const Handle &other): res{other.res} { }
constexpr Handle(Handle &&other): res{std::move(other.res)} { }
constexpr void operator=(const Handle &other) { res = other.res; }
constexpr void operator=(Handle &&other) { res = std::move(other.res); }
constexpr operator R&() noexcept { return *res; }
operator const R&() const noexcept { return *res; }
private:
std::shared_ptr<R> res;
};
class Loop final {
public:
Loop(bool def = true)
: loop{def ? uv_default_loop() : new uv_loop_t, [def](uv_loop_t *l){ if(!def) delete l; }}
{
if(!def) {
auto err = uv_loop_init(loop.get());
if(err) {
throw UVWException{err};
}
} else if(!loop) {
throw std::bad_alloc{};
}
}
Loop(const Loop &) = delete;
Loop(Loop &&other) = delete;
Loop& operator=(const Loop &) = delete;
Loop& operator=(Loop &&other) = delete;
~Loop() {
if(loop) {
close();
}
}
template<typename R, typename... Args>
Handle<R> handle(Args&&... args) {
return Handle<R>{loop.get(), std::forward<Args>(args)...};
}
bool close() noexcept {
return (uv_loop_close(loop.get()) == 0);
}
bool run() noexcept {
return (uv_run(loop.get(), UV_RUN_DEFAULT) == 0);
}
bool runOnce() noexcept {
return (uv_run(loop.get(), UV_RUN_ONCE) == 0);
}
bool runWait() noexcept {
return (uv_run(loop.get(), UV_RUN_NOWAIT) == 0);
}
bool alive() const noexcept {
return !(uv_loop_alive(loop.get()) == 0);
}
void stop() noexcept {
uv_stop(loop.get());
}
private:
using Deleter = std::function<void(uv_loop_t *)>;
std::unique_ptr<uv_loop_t, Deleter> loop;
};
}
<commit_msg>clean up<commit_after>#pragma once
#include <new>
#include <memory>
#include <utility>
#include <uv.h>
#include "error.hpp"
namespace uvw {
class Loop;
template<typename R>
class Handle {
friend class Loop;
template<typename... Args>
explicit constexpr Handle(uv_loop_t *loop, Args&&... args)
: res{std::make_shared<R>(loop, std::forward<Args>(args)...)}
{ }
public:
constexpr Handle(const Handle &other): res{other.res} { }
constexpr Handle(Handle &&other): res{std::move(other.res)} { }
constexpr void operator=(const Handle &other) { res = other.res; }
constexpr void operator=(Handle &&other) { res = std::move(other.res); }
constexpr operator R&() noexcept { return *res; }
operator const R&() const noexcept { return *res; }
private:
std::shared_ptr<R> res;
};
class Loop final {
public:
Loop(bool def = true)
: loop{def ? uv_default_loop() : new uv_loop_t, [def](uv_loop_t *l){ if(!def) delete l; }}
{
if(!def) {
auto err = uv_loop_init(loop.get());
if(err) {
throw UVWException{err};
}
} else if(!loop) {
throw std::bad_alloc{};
}
}
Loop(const Loop &) = delete;
Loop(Loop &&other) = delete;
Loop& operator=(const Loop &) = delete;
Loop& operator=(Loop &&other) = delete;
~Loop() {
if(loop) {
close();
}
}
template<typename R, typename... Args>
Handle<R> handle(Args&&... args) {
return Handle<R>{loop.get(), std::forward<Args>(args)...};
}
bool close() noexcept {
return (uv_loop_close(loop.get()) == 0);
}
bool run() noexcept {
return (uv_run(loop.get(), UV_RUN_DEFAULT) == 0);
}
bool runOnce() noexcept {
return (uv_run(loop.get(), UV_RUN_ONCE) == 0);
}
bool runWait() noexcept {
return (uv_run(loop.get(), UV_RUN_NOWAIT) == 0);
}
bool alive() const noexcept {
return !(uv_loop_alive(loop.get()) == 0);
}
void stop() noexcept {
uv_stop(loop.get());
}
private:
using Deleter = std::function<void(uv_loop_t *)>;
std::unique_ptr<uv_loop_t, Deleter> loop;
};
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <boost/lexical_cast.hpp>
#include <bitcoin/bitcoin.hpp>
#include "util.hpp"
using namespace bc;
bool validsig(transaction_type& tx, size_t input_index,
elliptic_curve_key& key, const script_type& script_code,
data_chunk signature)
{
uint32_t hash_type = 0;
hash_type = signature.back();
signature.pop_back();
hash_digest tx_hash =
script_type::generate_signature_hash(
tx, input_index, script_code, hash_type);
return key.verify(tx_hash, signature);
}
int main(int argc, char** argv)
{
if (argc != 5)
{
std::cerr << "Usage: sign-input FILENAME N SCRIPT_CODE SIGNATURE" << std::endl;
return -1;
}
const std::string filename = argv[1];
transaction_type tx;
if (!load_tx(tx, filename))
return -1;
const std::string index_str = argv[2];
size_t input_index;
try
{
input_index = boost::lexical_cast<size_t>(index_str);
}
catch (const boost::bad_lexical_cast&)
{
std::cerr << "sign-input: Bad N provided." << std::endl;
return -1;
}
const script_type script_code = parse_script(decode_hex(argv[3]));
if (input_index >= tx.inputs.size())
{
std::cerr << "sign-input: N out of range." << std::endl;
return -1;
}
const data_chunk signature = decode_hex(argv[4]);
elliptic_curve_key key;
if (!read_public_or_private_key(key))
return -1;
if (!validsig(tx, input_index, key, script_code, signature))
{
std::cout << "Status: Failed" << std::endl;
return 0;
}
std::cout << "Status: OK" << std::endl;
return 0;
}
<commit_msg>Fix validsig usage and error messages.<commit_after>#include <iostream>
#include <boost/lexical_cast.hpp>
#include <bitcoin/bitcoin.hpp>
#include "util.hpp"
using namespace bc;
bool validsig(transaction_type& tx, size_t input_index,
elliptic_curve_key& key, const script_type& script_code,
data_chunk signature)
{
uint32_t hash_type = 0;
hash_type = signature.back();
signature.pop_back();
hash_digest tx_hash =
script_type::generate_signature_hash(
tx, input_index, script_code, hash_type);
return key.verify(tx_hash, signature);
}
int main(int argc, char** argv)
{
if (argc != 5)
{
std::cerr << "Usage: validsig FILENAME N SCRIPT_CODE SIGNATURE" << std::endl;
return -1;
}
const std::string filename = argv[1];
transaction_type tx;
if (!load_tx(tx, filename))
return -1;
const std::string index_str = argv[2];
size_t input_index;
try
{
input_index = boost::lexical_cast<size_t>(index_str);
}
catch (const boost::bad_lexical_cast&)
{
std::cerr << "validsig: Bad N provided." << std::endl;
return -1;
}
const script_type script_code = parse_script(decode_hex(argv[3]));
if (input_index >= tx.inputs.size())
{
std::cerr << "validsig: N out of range." << std::endl;
return -1;
}
const data_chunk signature = decode_hex(argv[4]);
elliptic_curve_key key;
if (!read_public_or_private_key(key))
return -1;
if (!validsig(tx, input_index, key, script_code, signature))
{
std::cout << "Status: Failed" << std::endl;
return 0;
}
std::cout << "Status: OK" << std::endl;
return 0;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2017 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <sync.h>
#include <clientversion.h>
#include <util.h>
#include <warnings.h>
CCriticalSection cs_warnings;
std::string strMiscWarning;
bool fLargeWorkForkFound = false;
bool fLargeWorkInvalidChainFound = false;
void SetMiscWarning(const std::string& strWarning)
{
LOCK(cs_warnings);
strMiscWarning = strWarning;
}
void SetfLargeWorkForkFound(bool flag)
{
LOCK(cs_warnings);
fLargeWorkForkFound = flag;
}
bool GetfLargeWorkForkFound()
{
LOCK(cs_warnings);
return fLargeWorkForkFound;
}
void SetfLargeWorkInvalidChainFound(bool flag)
{
LOCK(cs_warnings);
fLargeWorkInvalidChainFound = flag;
}
std::string GetWarnings(const std::string& strFor)
{
std::string strStatusBar;
std::string strGUI;
const std::string uiAlertSeperator = "<hr />";
LOCK(cs_warnings);
if (!CLIENT_VERSION_IS_RELEASE) {
strStatusBar = "This is a pre-release test build - use at your own risk - do not use for privatesend, mining or merchant applications";
strGUI = _("This is a pre-release test build - use at your own risk - do not use for privatesend, mining or merchant applications");
}
// Misc warnings like out of disk space and clock is wrong
if (strMiscWarning != "")
{
strStatusBar = strMiscWarning;
strGUI += (strGUI.empty() ? "" : uiAlertSeperator) + strMiscWarning;
}
if (fLargeWorkForkFound)
{
strStatusBar = "Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.";
strGUI += (strGUI.empty() ? "" : uiAlertSeperator) + _("Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.");
}
else if (fLargeWorkInvalidChainFound)
{
strStatusBar = "Warning: We do not appear to fully agree with our peers! You may need to upgrade, or other nodes may need to upgrade.";
strGUI += (strGUI.empty() ? "" : uiAlertSeperator) + _("Warning: We do not appear to fully agree with our peers! You may need to upgrade, or other nodes may need to upgrade.");
}
if (strFor == "gui")
return strGUI;
else if (strFor == "statusbar")
return strStatusBar;
assert(!"GetWarnings(): invalid parameter");
return "error";
}
<commit_msg>Add Clang thread safety annotations for variables guarded by cs_warnings<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2017 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <sync.h>
#include <clientversion.h>
#include <util.h>
#include <warnings.h>
CCriticalSection cs_warnings;
std::string strMiscWarning GUARDED_BY(cs_warnings);
bool fLargeWorkForkFound GUARDED_BY(cs_warnings) = false;
bool fLargeWorkInvalidChainFound GUARDED_BY(cs_warnings) = false;
void SetMiscWarning(const std::string& strWarning)
{
LOCK(cs_warnings);
strMiscWarning = strWarning;
}
void SetfLargeWorkForkFound(bool flag)
{
LOCK(cs_warnings);
fLargeWorkForkFound = flag;
}
bool GetfLargeWorkForkFound()
{
LOCK(cs_warnings);
return fLargeWorkForkFound;
}
void SetfLargeWorkInvalidChainFound(bool flag)
{
LOCK(cs_warnings);
fLargeWorkInvalidChainFound = flag;
}
std::string GetWarnings(const std::string& strFor)
{
std::string strStatusBar;
std::string strGUI;
const std::string uiAlertSeperator = "<hr />";
LOCK(cs_warnings);
if (!CLIENT_VERSION_IS_RELEASE) {
strStatusBar = "This is a pre-release test build - use at your own risk - do not use for privatesend, mining or merchant applications";
strGUI = _("This is a pre-release test build - use at your own risk - do not use for privatesend, mining or merchant applications");
}
// Misc warnings like out of disk space and clock is wrong
if (strMiscWarning != "")
{
strStatusBar = strMiscWarning;
strGUI += (strGUI.empty() ? "" : uiAlertSeperator) + strMiscWarning;
}
if (fLargeWorkForkFound)
{
strStatusBar = "Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.";
strGUI += (strGUI.empty() ? "" : uiAlertSeperator) + _("Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.");
}
else if (fLargeWorkInvalidChainFound)
{
strStatusBar = "Warning: We do not appear to fully agree with our peers! You may need to upgrade, or other nodes may need to upgrade.";
strGUI += (strGUI.empty() ? "" : uiAlertSeperator) + _("Warning: We do not appear to fully agree with our peers! You may need to upgrade, or other nodes may need to upgrade.");
}
if (strFor == "gui")
return strGUI;
else if (strFor == "statusbar")
return strStatusBar;
assert(!"GetWarnings(): invalid parameter");
return "error";
}
<|endoftext|> |
<commit_before>/*************************************************
* ANSI X9.31 RNG Source File *
* (C) 1999-2007 Jack Lloyd *
*************************************************/
#include <botan/x931_rng.h>
#include <botan/lookup.h>
#include <botan/randpool.h>
#include <botan/bit_ops.h>
#include <algorithm>
namespace Botan {
/*************************************************
* Generate a buffer of random bytes *
*************************************************/
void ANSI_X931_RNG::randomize(byte out[], u32bit length) throw(PRNG_Unseeded)
{
if(!is_seeded())
throw PRNG_Unseeded(name());
while(length)
{
const u32bit copied = std::min(length, R.size() - position);
copy_mem(out, R + position, copied);
out += copied;
length -= copied;
position += copied;
if(position == R.size())
update_buffer();
}
}
/*************************************************
* Refill the internal state *
*************************************************/
void ANSI_X931_RNG::update_buffer()
{
const u32bit BLOCK_SIZE = cipher->BLOCK_SIZE;
SecureVector<byte> DT(BLOCK_SIZE);
prng->randomize(DT, DT.size());
cipher->encrypt(DT);
xor_buf(R, V, DT, BLOCK_SIZE);
cipher->encrypt(R);
xor_buf(V, R, DT, BLOCK_SIZE);
cipher->encrypt(V);
position = 0;
}
/*************************************************
* Add entropy to internal state *
*************************************************/
void ANSI_X931_RNG::add_randomness(const byte data[], u32bit length)
{
prng->add_entropy(data, length);
if(is_seeded())
{
SecureVector<byte> key(cipher->MAXIMUM_KEYLENGTH);
prng->randomize(key, key.size());
cipher->set_key(key, key.size());
prng->randomize(V, V.size());
update_buffer();
}
}
/*************************************************
* Check if the the PRNG is seeded *
*************************************************/
bool ANSI_X931_RNG::is_seeded() const
{
return prng->is_seeded();
}
/*************************************************
* Clear memory of sensitive data *
*************************************************/
void ANSI_X931_RNG::clear() throw()
{
cipher->clear();
prng->clear();
R.clear();
V.clear();
position = 0;
}
/*************************************************
* Return the name of this type *
*************************************************/
std::string ANSI_X931_RNG::name() const
{
return "X9.31(" + cipher->name() + ")";
}
/*************************************************
* ANSI X931 RNG Constructor *
*************************************************/
ANSI_X931_RNG::ANSI_X931_RNG(const std::string& cipher_name,
RandomNumberGenerator* prng_ptr)
{
if(!prng_ptr)
throw Invalid_Argument("ANSI_X931_RNG constructor: NULL prng");
prng = prng_ptr;
cipher = get_block_cipher(cipher_name);
const u32bit BLOCK_SIZE = cipher->BLOCK_SIZE;
V.create(BLOCK_SIZE);
R.create(BLOCK_SIZE);
position = 0;
}
/*************************************************
* ANSI X931 RNG Destructor *
*************************************************/
ANSI_X931_RNG::~ANSI_X931_RNG()
{
delete cipher;
delete prng;
}
}
<commit_msg>Change how the ANSI X9.31 generator tells that it is seeded. Previously, it was seeded if and only if the underlying PRNG was seeded. However if the PRNG always returned as being seeded, we would never generate a V value, etc (leaving them at the default zero). This would not occur with any of Botan's built in PRNGs since their implementations require that add_randomness be called at least once before is_seeded will return true. However this is not an invariant of the general RandomNumberGenerator interface.<commit_after>/*************************************************
* ANSI X9.31 RNG Source File *
* (C) 1999-2007 Jack Lloyd *
*************************************************/
#include <botan/x931_rng.h>
#include <botan/lookup.h>
#include <botan/randpool.h>
#include <botan/bit_ops.h>
#include <algorithm>
namespace Botan {
/*************************************************
* Generate a buffer of random bytes *
*************************************************/
void ANSI_X931_RNG::randomize(byte out[], u32bit length) throw(PRNG_Unseeded)
{
if(!is_seeded())
throw PRNG_Unseeded(name());
while(length)
{
if(position == R.size())
update_buffer();
const u32bit copied = std::min(length, R.size() - position);
copy_mem(out, R + position, copied);
out += copied;
length -= copied;
position += copied;
}
}
/*************************************************
* Refill the internal state *
*************************************************/
void ANSI_X931_RNG::update_buffer()
{
SecureVector<byte> DT(cipher->BLOCK_SIZE);
prng->randomize(DT, DT.size());
cipher->encrypt(DT);
xor_buf(R, V, DT, cipher->BLOCK_SIZE);
cipher->encrypt(R);
xor_buf(V, R, DT, cipher->BLOCK_SIZE);
cipher->encrypt(V);
position = 0;
}
/*************************************************
* Add entropy to internal state *
*************************************************/
void ANSI_X931_RNG::add_randomness(const byte data[], u32bit length)
{
prng->add_entropy(data, length);
if(prng->is_seeded())
{
SecureVector<byte> key(cipher->MAXIMUM_KEYLENGTH);
prng->randomize(key, key.size());
cipher->set_key(key, key.size());
if(V.size() != cipher->BLOCK_SIZE)
V.create(cipher->BLOCK_SIZE);
prng->randomize(V, V.size());
update_buffer();
}
}
/*************************************************
* Check if the the PRNG is seeded *
*************************************************/
bool ANSI_X931_RNG::is_seeded() const
{
return V.has_items();
}
/*************************************************
* Clear memory of sensitive data *
*************************************************/
void ANSI_X931_RNG::clear() throw()
{
cipher->clear();
prng->clear();
R.clear();
V.clear();
position = 0;
}
/*************************************************
* Return the name of this type *
*************************************************/
std::string ANSI_X931_RNG::name() const
{
return "X9.31(" + cipher->name() + ")";
}
/*************************************************
* ANSI X931 RNG Constructor *
*************************************************/
ANSI_X931_RNG::ANSI_X931_RNG(const std::string& cipher_name,
RandomNumberGenerator* prng_ptr)
{
if(!prng_ptr)
throw Invalid_Argument("ANSI_X931_RNG constructor: NULL prng");
prng = prng_ptr;
cipher = get_block_cipher(cipher_name);
R.create(cipher->BLOCK_SIZE);
position = 0;
}
/*************************************************
* ANSI X931 RNG Destructor *
*************************************************/
ANSI_X931_RNG::~ANSI_X931_RNG()
{
delete cipher;
delete prng;
}
}
<|endoftext|> |
<commit_before>#ifndef IMAGE_MANAGER_HPP_INCLUDED
#define IMAGE_MANAGER_HPP_INCLUDED
#include <boost/shared_ptr.hpp>
struct ImageType
{
int shmid;
unsigned char *shmaddr;
double time;
};
struct ConvertedImage;
class ImageManager
{
public:
static boost::shared_ptr<ImageManager> create(int width, int height);
virtual boost::shared_ptr<ImageType> getImage() = 0;
virtual boost::shared_ptr<ConvertedImage> getConvertedImage() =0;
protected:
~ImageManager()
{}
};
#endif
<commit_msg>Spacing<commit_after>#ifndef IMAGE_MANAGER_HPP_INCLUDED
#define IMAGE_MANAGER_HPP_INCLUDED
#include <boost/shared_ptr.hpp>
struct ImageType
{
int shmid;
unsigned char *shmaddr;
double time;
};
struct ConvertedImage;
class ImageManager
{
public:
static boost::shared_ptr<ImageManager> create(int width, int height);
virtual boost::shared_ptr<ImageType> getImage() = 0;
virtual boost::shared_ptr<ConvertedImage> getConvertedImage() =0;
protected:
~ImageManager()
{}
};
#endif
<|endoftext|> |
<commit_before>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
Copyright (c) 2008 Aristid Breitkreuz, Ruediger Sonderfeld
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated nodeation 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 "flusspferd/xml/node.hpp"
#include "flusspferd/xml/document.hpp"
#include "flusspferd/string.hpp"
#include "flusspferd/create.hpp"
#include "flusspferd/tracer.hpp"
#include "flusspferd/exception.hpp"
#include "flusspferd/local_root_scope.hpp"
using namespace flusspferd;
using namespace flusspferd::xml;
object node::create(xmlNodePtr ptr) {
if (ptr->_private)
return value::from_permanent_ptr(ptr->_private).to_object();
switch (ptr->type) {
case XML_DOCUMENT_NODE:
return create_native_object<document>(object(), xmlDocPtr(ptr));
default:
return create_native_object<node>(object(), ptr);
}
}
xmlNodePtr node::c_from_js(object const &obj) {
if (!obj.is_valid())
return 0;
try {
xml::node *p = dynamic_cast<xml::node*>(native_object_base::get_native(obj));
if (!p)
return 0;
return p->c_obj();
} catch (std::exception&) {
return 0;
}
}
node::node(xmlNodePtr ptr)
: ptr(ptr)
{
ptr->_private = permanent_ptr();
}
node::node(call_context &x) {
local_root_scope scope;
string name(x.arg[0]);
ptr = xmlNewNode(0, (xmlChar const *) name.c_str());
if (!ptr)
throw exception("Could not create XML node");
ptr->_private = permanent_ptr();
}
node::~node() {
if (ptr && !ptr->parent && ptr->_private == permanent_ptr()) {
xmlFreeNode(ptr);
}
}
void node::post_initialize() {
ptr->_private = permanent_ptr();
register_native_method("copy", &node::copy);
define_native_property("name", permanent_property, &node::prop_name);
define_native_property("lang", permanent_property, &node::prop_lang);
define_native_property("parent", permanent_property, &node::prop_parent);
define_native_property("next", permanent_property, &node::prop_next);
define_native_property(
"document", permanent_property | read_only_property, &node::prop_document);
define_native_property(
"type", permanent_property | read_only_property, &node::prop_type);
}
object node::class_info::create_prototype() {
object proto = create_object();
create_native_method(proto, "copy", 1);
return proto;
}
char const *node::class_info::constructor_name() {
return "Node";
}
std::size_t node::class_info::constructor_arity() {
return 1;
}
static void trace_children(tracer &trc, xmlNodePtr ptr) {
while (ptr) {
trc("node-children", value::from_permanent_ptr(ptr->_private));
trace_children(trc, ptr->children);
ptr = ptr->next;
}
}
static void trace_parents(tracer &trc, xmlNodePtr ptr) {
while (ptr) {
trc("node-parent", value::from_permanent_ptr(ptr->_private));
ptr = ptr->parent;
}
}
void node::trace(tracer &trc) {
trc("node-self", value::from_permanent_ptr(ptr->_private));
trace_children(trc, ptr->children);
trace_parents(trc, ptr->parent);
if (ptr->doc)
trc("node-doc", value::from_permanent_ptr(ptr->doc->_private));
if (ptr->next)
trc("node-next", value::from_permanent_ptr(ptr->next->_private));
if (ptr->prev)
trc("node-prev", value::from_permanent_ptr(ptr->prev->_private));
}
void node::prop_name(property_mode mode, value &data) {
switch (mode) {
case property_get:
if (!ptr->name)
data = value();
else
data = string((char const *) ptr->name);
break;
case property_set:
xmlNodeSetName(ptr, (xmlChar const *) data.to_string().c_str());
break;
default: break;
};
}
void node::prop_lang(property_mode mode, value &data) {
switch (mode) {
case property_get:
{
xmlChar const *lang = xmlNodeGetLang(ptr);
if (!lang)
data = value();
else
data = string((char const *) lang);
}
break;
case property_set:
xmlNodeSetLang(ptr, (xmlChar const *) data.to_string().c_str());
break;
default: break;
};
}
void node::prop_parent(property_mode mode, value &data) {
switch (mode) {
case property_get:
if (!ptr->parent)
data = object();
else
data = create(ptr->parent);
break;
case property_set:
if (data.is_void() || data.is_null()) {
xmlUnlinkNode(ptr);
data = object();
} else if (!data.is_object()) {
data = value();
} else {
xmlNodePtr parent = c_from_js(data.get_object());
if (!parent) {
data = value();
break;
}
if (ptr->parent)
xmlUnlinkNode(ptr);
xmlAddChild(parent, ptr);
}
break;
default: break;
}
}
void node::prop_next(property_mode mode, value &data) {
switch (mode) {
case property_get:
if (!ptr->parent)
data = object();
else
data = create(ptr->next);
break;
case property_set:
if (data.is_void() || data.is_null()) {
ptr->next = 0;
data = object();
} else if (!data.is_object()) {
data = value();
} else {
xmlNodePtr next = c_from_js(data.get_object());
if (!next) {
data = value();
break;
}
ptr->next = next;
while (next) {
next->parent = ptr->parent;
if (!next->next)
next->parent->last = next;
next = next->next;
}
xmlSetListDoc(ptr->next, ptr->doc);
}
break;
default: break;
}
}
void node::prop_document(property_mode mode, value &data) {
if (mode != property_get)
return;
if (!ptr->doc)
data = object();
else
data = create(xmlNodePtr(ptr->doc));
}
void node::prop_type(property_mode mode, value &data) {
if (mode != property_get)
return;
switch (ptr->type) {
case XML_ELEMENT_NODE:
data = string("ELEMENT");
break;
case XML_ATTRIBUTE_NODE:
data = string("ATTRIBUTE");
break;
case XML_TEXT_NODE:
data = string("TEXT");
break;
case XML_CDATA_SECTION_NODE:
data = string("CDATA-SECTION");
break;
case XML_ENTITY_REF_NODE:
data = string("ENTITY-REFERENCE");
break;
case XML_ENTITY_NODE:
data = string("ENTITY");
break;
case XML_PI_NODE:
data = string("PI");
break;
case XML_COMMENT_NODE:
data = string("COMMENT");
break;
case XML_DOCUMENT_NODE:
data = string("DOCUMENT");
break;
case XML_DOCUMENT_TYPE_NODE:
data = string("DOCUMENT-TYPE");
break;
case XML_DOCUMENT_FRAG_NODE:
data = string("DOCUMENT-FRAGMENT");
break;
case XML_NOTATION_NODE:
data = string("NOTATION");
break;
case XML_HTML_DOCUMENT_NODE:
data = string("HTML-DOCUMENT");
break;
case XML_DTD_NODE:
data = string("DTD");
break;
case XML_ELEMENT_DECL:
data = string("ELEMENT-DECLARATION");
break;
case XML_ATTRIBUTE_DECL:
data = string("ATTRIBUTE-DECLARATION");
break;
case XML_ENTITY_DECL:
data = string("ENTITY-DECLARATION");
break;
case XML_NAMESPACE_DECL:
data = string("NAMESPACE-DECLARATION");
break;
case XML_XINCLUDE_START:
data = string("XINCLUDE-START");
break;
case XML_XINCLUDE_END:
data = string("XINCLUDE-END");
break;
default:
data = string("OTHER");
break;
}
}
object node::copy(bool recursive) {
xmlNodePtr copy = xmlCopyNode(ptr, recursive);
if (!copy)
throw exception("Could not copy XML node");
return create(copy);
}
<commit_msg>simplify<commit_after>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
Copyright (c) 2008 Aristid Breitkreuz, Ruediger Sonderfeld
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated nodeation 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 "flusspferd/xml/node.hpp"
#include "flusspferd/xml/document.hpp"
#include "flusspferd/string.hpp"
#include "flusspferd/create.hpp"
#include "flusspferd/tracer.hpp"
#include "flusspferd/exception.hpp"
#include "flusspferd/local_root_scope.hpp"
using namespace flusspferd;
using namespace flusspferd::xml;
object node::create(xmlNodePtr ptr) {
if (ptr->_private)
return from_permanent_ptr(ptr->_private);
switch (ptr->type) {
case XML_DOCUMENT_NODE:
return create_native_object<document>(object(), xmlDocPtr(ptr));
default:
return create_native_object<node>(object(), ptr);
}
}
xmlNodePtr node::c_from_js(object const &obj) {
if (!obj.is_valid())
return 0;
try {
xml::node *p = dynamic_cast<xml::node*>(native_object_base::get_native(obj));
if (!p)
return 0;
return p->c_obj();
} catch (std::exception&) {
return 0;
}
}
node::node(xmlNodePtr ptr)
: ptr(ptr)
{
ptr->_private = permanent_ptr();
}
node::node(call_context &x) {
local_root_scope scope;
string name(x.arg[0]);
ptr = xmlNewNode(0, (xmlChar const *) name.c_str());
if (!ptr)
throw exception("Could not create XML node");
ptr->_private = permanent_ptr();
}
node::~node() {
if (ptr && !ptr->parent && ptr->_private == permanent_ptr()) {
xmlFreeNode(ptr);
}
}
void node::post_initialize() {
ptr->_private = permanent_ptr();
register_native_method("copy", &node::copy);
define_native_property("name", permanent_property, &node::prop_name);
define_native_property("lang", permanent_property, &node::prop_lang);
define_native_property("parent", permanent_property, &node::prop_parent);
define_native_property("next", permanent_property, &node::prop_next);
define_native_property(
"document", permanent_property | read_only_property, &node::prop_document);
define_native_property(
"type", permanent_property | read_only_property, &node::prop_type);
}
object node::class_info::create_prototype() {
object proto = create_object();
create_native_method(proto, "copy", 1);
return proto;
}
char const *node::class_info::constructor_name() {
return "Node";
}
std::size_t node::class_info::constructor_arity() {
return 1;
}
static void trace_children(tracer &trc, xmlNodePtr ptr) {
while (ptr) {
trc("node-children", value::from_permanent_ptr(ptr->_private));
trace_children(trc, ptr->children);
ptr = ptr->next;
}
}
static void trace_parents(tracer &trc, xmlNodePtr ptr) {
while (ptr) {
trc("node-parent", value::from_permanent_ptr(ptr->_private));
ptr = ptr->parent;
}
}
void node::trace(tracer &trc) {
trc("node-self", value::from_permanent_ptr(ptr->_private));
trace_children(trc, ptr->children);
trace_parents(trc, ptr->parent);
if (ptr->doc)
trc("node-doc", value::from_permanent_ptr(ptr->doc->_private));
if (ptr->next)
trc("node-next", value::from_permanent_ptr(ptr->next->_private));
if (ptr->prev)
trc("node-prev", value::from_permanent_ptr(ptr->prev->_private));
}
void node::prop_name(property_mode mode, value &data) {
switch (mode) {
case property_get:
if (!ptr->name)
data = value();
else
data = string((char const *) ptr->name);
break;
case property_set:
xmlNodeSetName(ptr, (xmlChar const *) data.to_string().c_str());
break;
default: break;
};
}
void node::prop_lang(property_mode mode, value &data) {
switch (mode) {
case property_get:
{
xmlChar const *lang = xmlNodeGetLang(ptr);
if (!lang)
data = value();
else
data = string((char const *) lang);
}
break;
case property_set:
xmlNodeSetLang(ptr, (xmlChar const *) data.to_string().c_str());
break;
default: break;
};
}
void node::prop_parent(property_mode mode, value &data) {
switch (mode) {
case property_get:
if (!ptr->parent)
data = object();
else
data = create(ptr->parent);
break;
case property_set:
if (data.is_void() || data.is_null()) {
xmlUnlinkNode(ptr);
data = object();
} else if (!data.is_object()) {
data = value();
} else {
xmlNodePtr parent = c_from_js(data.get_object());
if (!parent) {
data = value();
break;
}
if (ptr->parent)
xmlUnlinkNode(ptr);
xmlAddChild(parent, ptr);
}
break;
default: break;
}
}
void node::prop_next(property_mode mode, value &data) {
switch (mode) {
case property_get:
if (!ptr->parent)
data = object();
else
data = create(ptr->next);
break;
case property_set:
if (data.is_void() || data.is_null()) {
ptr->next = 0;
data = object();
} else if (!data.is_object()) {
data = value();
} else {
xmlNodePtr next = c_from_js(data.get_object());
if (!next) {
data = value();
break;
}
ptr->next = next;
while (next) {
next->parent = ptr->parent;
if (!next->next)
next->parent->last = next;
next = next->next;
}
xmlSetListDoc(ptr->next, ptr->doc);
}
break;
default: break;
}
}
void node::prop_document(property_mode mode, value &data) {
if (mode != property_get)
return;
if (!ptr->doc)
data = object();
else
data = create(xmlNodePtr(ptr->doc));
}
void node::prop_type(property_mode mode, value &data) {
if (mode != property_get)
return;
switch (ptr->type) {
case XML_ELEMENT_NODE:
data = string("ELEMENT");
break;
case XML_ATTRIBUTE_NODE:
data = string("ATTRIBUTE");
break;
case XML_TEXT_NODE:
data = string("TEXT");
break;
case XML_CDATA_SECTION_NODE:
data = string("CDATA-SECTION");
break;
case XML_ENTITY_REF_NODE:
data = string("ENTITY-REFERENCE");
break;
case XML_ENTITY_NODE:
data = string("ENTITY");
break;
case XML_PI_NODE:
data = string("PI");
break;
case XML_COMMENT_NODE:
data = string("COMMENT");
break;
case XML_DOCUMENT_NODE:
data = string("DOCUMENT");
break;
case XML_DOCUMENT_TYPE_NODE:
data = string("DOCUMENT-TYPE");
break;
case XML_DOCUMENT_FRAG_NODE:
data = string("DOCUMENT-FRAGMENT");
break;
case XML_NOTATION_NODE:
data = string("NOTATION");
break;
case XML_HTML_DOCUMENT_NODE:
data = string("HTML-DOCUMENT");
break;
case XML_DTD_NODE:
data = string("DTD");
break;
case XML_ELEMENT_DECL:
data = string("ELEMENT-DECLARATION");
break;
case XML_ATTRIBUTE_DECL:
data = string("ATTRIBUTE-DECLARATION");
break;
case XML_ENTITY_DECL:
data = string("ENTITY-DECLARATION");
break;
case XML_NAMESPACE_DECL:
data = string("NAMESPACE-DECLARATION");
break;
case XML_XINCLUDE_START:
data = string("XINCLUDE-START");
break;
case XML_XINCLUDE_END:
data = string("XINCLUDE-END");
break;
default:
data = string("OTHER");
break;
}
}
object node::copy(bool recursive) {
xmlNodePtr copy = xmlCopyNode(ptr, recursive);
if (!copy)
throw exception("Could not copy XML node");
return create(copy);
}
<|endoftext|> |
<commit_before>#include "arena.h"
#include "image_util.h"
#include "image_writer.h"
#include "logger.h"
#include <fstream>
using namespace wotreplay;
const int element_size = 48;
image_writer_t::image_writer_t()
: filter([](const packet_t &){ return true; }),
image_width(512), image_height(512)
{}
void image_writer_t::draw_element(const boost::multi_array<uint8_t, 3> &element, int x, int y, int mask) {
const size_t *shape = element.shape();
const size_t *image_size = base.shape();
for (int i = 0; i < shape[0]; ++i) {
for (int j = 0; j < shape[1]; ++j) {
// don't touch alpha channel, use from original
for (int k = 0; k < 3; ++k) {
if (((i + y) >= image_size[0]) || ((j + x) >= image_size[1])) {
continue;
}
base[i + y][j + x][k] = mix(base[i + y][j + x][k], base[i + y][j + x][k], (255 - element[i][j][3]) / 255.f,
element[i][j][k] & ((mask >> ((4- (k + 1))*8)) & 0xFF), element[i][j][3] / 255.f);
}
}
}
}
boost::multi_array<uint8_t, 3> image_writer_t::get_element(const std::string &name) {
boost::multi_array<uint8_t, 3> element, resized_element;
std::ifstream is("elements/" + name + ".png", std::ios::binary);
read_png(is, element);
double f = image_width / 512.0; // we need to scale the elements to the right size
resize(element, element_size*f, element_size*f, resized_element);
return resized_element;
}
void image_writer_t::draw_element(const boost::multi_array<uint8_t, 3> &element, std::tuple<float, float> position, int mask) {
auto shape = base.shape();
auto element_shape = element.shape();
float x,y;
auto position3d = std::make_tuple(std::get<0>(position), 0.f, std::get<1>(position));
std::tie(x,y) = get_2d_coord(position3d, arena.bounding_box, (int) shape[1], (int) shape[0]);
draw_element(element, x - element_shape[1]/2, y - element_shape[0]/2, mask);
}
void image_writer_t::draw_grid(boost::multi_array<uint8_t, 3> &image) {
const int grid_line_width = 2;
const int grid_cells = 10;
auto shape = image.shape();
int grid_width = ((int) shape[1] - (grid_cells + 1) * grid_line_width) / grid_cells;
int grid_height = ((int) shape[0] - (grid_cells + 1) * grid_line_width) / grid_cells;
for (int y = 0; y < shape[0]; y += (grid_height + grid_line_width)) {
for (int i = 0; i < grid_line_width; ++i) {
for (int x = 0; x < shape[1]; ++x) {
for (int c = 0; c < 3; ++ c) {
image[y + i][x][c] = std::min(image[y][x][c] + 20, 255);
}
}
}
}
for (int x = 0; x < shape[1]; x += (grid_width + grid_line_width)) {
for (int i = 0; i < grid_line_width; ++i) {
for (int y = 0; y < shape[0]; ++y) {
for (int c = 0; c < 3; ++ c) {
image[y][x + i][c] = std::min(image[y][x][c] + 20, 255);
}
}
}
}
}
void image_writer_t::draw_elements() {
auto it = arena.configurations.find(game_mode);
if (it == arena.configurations.end()) {
wotreplay::logger.writef(log_level_t::warning, "Could not find configuration for game mode '%1%'\n", game_mode);
return;
}
const arena_configuration_t &configuration = arena.configurations[game_mode];
int reference_team_id = use_fixed_teamcolors ? 0 : recorder_team;
if (game_mode == "domination") {
auto neutral_base = get_element("neutral_base");
draw_element(neutral_base, configuration.control_point);
}
auto friendly_base = get_element("friendly_base");
auto enemy_base = get_element("enemy_base");
for(const auto &entry : configuration.team_base_positions) {
for (const auto &position : entry.second) {
draw_element((entry.first - 1) == reference_team_id ? friendly_base : enemy_base, position);
}
}
std::vector<boost::multi_array<uint8_t, 3>> spawns{
get_element("neutral_spawn1"),
get_element("neutral_spawn2"),
get_element("neutral_spawn3"),
get_element("neutral_spawn4")
};
for(const auto &entry : configuration.team_spawn_points) {
for (int i = 0; i < entry.second.size(); ++i) {
int mask = (reference_team_id == (entry.first - 1)) ? 0x00FF00FF : 0xFF0000FF;
draw_element(spawns[i], entry.second[i], mask);
}
}
draw_grid(base);
}
void image_writer_t::draw_death(const packet_t &packet, const game_t &game) {
uint32_t killer, killed;
std::tie(killed, killer) = packet.tank_destroyed();
packet_t position_packet;
bool found = game.find_property(packet.clock(), killed, property_t::position, position_packet);
if (found) {
draw_position(position_packet, game, this->deaths);
}
}
void image_writer_t::draw_position(const packet_t &packet, const game_t &game, boost::multi_array<float, 3> &image) {
uint32_t player_id = packet.player_id();
int team_id = game.get_team_id(player_id);
if (team_id < 0) return;
auto shape = image.shape();
int height = static_cast<int>(shape[1]);
int width = static_cast<int>(shape[2]);
const bounding_box_t &bounding_box = game.get_arena().bounding_box;
std::tuple<float, float> position = get_2d_coord( packet.position(), bounding_box, width, height);
long x = std::lround(std::get<0>(position));
long y = std::lround(std::get<1>(position));
if (x >= 0 && y >= 0 && x < width && y < height) {
image[team_id][y][x]++;
if (player_id == game.get_recorder_id()) {
image[2][y][x]++;
}
}
}
void image_writer_t::update(const game_t &game) {
recorder_team = game.get_team_id(game.get_recorder_id());
std::set<int> dead_players;
for (const packet_t &packet : game.get_packets()) {
if (!filter(packet)) continue;
if (packet.has_property(property_t::position)
&& dead_players.find(packet.player_id()) == dead_players.end()) {
draw_position(packet, game, this->positions);
} else if (packet.has_property(property_t::tank_destroyed)) {
uint32_t target, killer;
std::tie(target, killer) = packet.tank_destroyed();
dead_players.insert(target);
draw_death(packet, game);
}
}
}
void image_writer_t::load_base_map(const std::string &path) {
boost::multi_array<uint8_t, 3> map;
std::ifstream is(path, std::ios::binary);
read_png(is, map);
resize(map, image_width, image_height, this->base);
}
void image_writer_t::write(std::ostream &os) {
write_png(os, result);
}
void image_writer_t::init(const arena_t &arena, const std::string &mode) {
this->arena = arena;
this->game_mode = mode;
positions.resize(boost::extents[3][image_height][image_width]);
deaths.resize(boost::extents[3][image_height][image_width]);
clear();
initialized = true;
}
void image_writer_t::clear() {
std::fill(result.origin(), result.origin() + result.num_elements(), 0.f);
std::fill(deaths.origin(), deaths.origin() + deaths.num_elements(), 0.f);
std::fill(positions.origin(), positions.origin() + positions.num_elements(), 0.f);
}
void image_writer_t::finish() {
draw_basemap();
const size_t *shape = base.shape();
result.resize(boost::extents[shape[0]][shape[1]][shape[2]]);
result = base;
int reference_team_id = use_fixed_teamcolors ? 0 : recorder_team;
for (int i = 0; i < image_height; ++i) {
for (int j = 0; j < image_width; ++j) {
if (positions[0][i][j] > positions[1][i][j]) {
// position claimed by first team
if (reference_team_id == 0) {
result[i][j][0] = result[i][j][2] = 0x00;
result[i][j][1] = result[i][j][3] = 0xFF;
} else {
result[i][j][1] = result[i][j][2] = 0x00;
result[i][j][0] = result[i][j][3] = 0xFF;
}
} else if (positions[0][i][j] < positions[1][i][j]) {
// position claimed by second team
if (reference_team_id == 0) {
result[i][j][1] = result[i][j][2] = 0x00;
result[i][j][0] = result[i][j][3] = 0xFF;
} else {
result[i][j][0] = result[i][j][2] = 0x00;
result[i][j][1] = result[i][j][3] = 0xFF;
}
} else {
// no change
}
if (this->show_self && positions[2][i][j] > 0.f) {
// position claimed by second team
result[i][j][0] = result[i][j][1] = 0x00;
result[i][j][2] = result[i][j][3] = 0xFF;
}
if (deaths[0][i][j] + deaths[1][i][j] > 0.f) {
for (int k = 0; k < 3; k += 1) {
for (int l = 0; l < 3; l += 1) {
int x = j + k - 1;
int y = i + l - 1;
// draw only if within bounds
if (x >= 0 && x < image_width && y >= 0 && y < image_height) {
result[y][x][3] = result[y][x][0] = result[y][x][1] = 0xFF;
result[y][x][2] = 0x00;
}
}
}
}
}
}
}
void image_writer_t::reset() {
// initialize with empty image arrays
initialized = false;
}
bool image_writer_t::is_initialized() const {
return initialized;
}
void image_writer_t::set_show_self(bool show_self) {
this->show_self = show_self;
}
bool image_writer_t::get_show_self() const {
return show_self;
}
void image_writer_t::set_use_fixed_teamcolors(bool use_fixed_teamcolors) {
this->use_fixed_teamcolors = use_fixed_teamcolors;
}
bool image_writer_t::get_use_fixed_teamcolors() const {
return use_fixed_teamcolors;
}
void image_writer_t::set_recorder_team(int recorder_team) {
this->recorder_team = recorder_team;
}
int image_writer_t::get_recorder_team() const {
return recorder_team;
}
void image_writer_t::set_filter(filter_t filter) {
this->filter = filter;
}
const arena_t &image_writer_t::get_arena() const {
return arena;
}
const std::string &image_writer_t::get_game_mode() const {
return game_mode;
}
void image_writer_t::merge(const image_writer_t &writer) {
// TODO: implement this
std::transform(positions.origin(), positions.origin() + positions.num_elements(),
writer.positions.origin(), positions.origin(), std::plus<float>());
}
int image_writer_t::get_image_height() const {
return image_height;
}
void image_writer_t::set_image_height(int image_height) {
this->image_height = image_height;
}
int image_writer_t::get_image_width() const {
return image_width;
}
void image_writer_t::set_image_width(int image_width) {
this->image_width = image_width;
}
bool image_writer_t::get_no_basemap() const {
return no_basemap;
}
void image_writer_t::set_no_basemap(bool no_basemap) {
this->no_basemap = no_basemap;
}
void image_writer_t::draw_basemap() {
if (!no_basemap) {
load_base_map(arena.mini_map);
const size_t *shape = base.shape();
result.resize(boost::extents[shape[0]][shape[1]][shape[2]]);
draw_elements();
} else {
base.resize(boost::extents[image_width][image_height][4]);
}
}
const boost::multi_array<uint8_t, 3> &image_writer_t::get_result() const {
return result;
}<commit_msg>image_writer_t::load_base_map() handle failure to open file<commit_after>#include "arena.h"
#include "image_util.h"
#include "image_writer.h"
#include "logger.h"
#include <fstream>
using namespace wotreplay;
const int element_size = 48;
image_writer_t::image_writer_t()
: filter([](const packet_t &) { return true; }),
image_width(512), image_height(512)
{}
void image_writer_t::draw_element(const boost::multi_array<uint8_t, 3> &element, int x, int y, int mask) {
const size_t *shape = element.shape();
const size_t *image_size = base.shape();
for (int i = 0; i < shape[0]; ++i) {
for (int j = 0; j < shape[1]; ++j) {
// don't touch alpha channel, use from original
for (int k = 0; k < 3; ++k) {
if (((i + y) >= image_size[0]) || ((j + x) >= image_size[1])) {
continue;
}
base[i + y][j + x][k] = mix(base[i + y][j + x][k], base[i + y][j + x][k], (255 - element[i][j][3]) / 255.f,
element[i][j][k] & ((mask >> ((4 - (k + 1)) * 8)) & 0xFF), element[i][j][3] / 255.f);
}
}
}
}
boost::multi_array<uint8_t, 3> image_writer_t::get_element(const std::string &name) {
boost::multi_array<uint8_t, 3> element, resized_element;
std::ifstream is("elements/" + name + ".png", std::ios::binary);
read_png(is, element);
double f = image_width / 512.0; // we need to scale the elements to the right size
resize(element, element_size*f, element_size*f, resized_element);
return resized_element;
}
void image_writer_t::draw_element(const boost::multi_array<uint8_t, 3> &element, std::tuple<float, float> position, int mask) {
auto shape = base.shape();
auto element_shape = element.shape();
float x, y;
auto position3d = std::make_tuple(std::get<0>(position), 0.f, std::get<1>(position));
std::tie(x, y) = get_2d_coord(position3d, arena.bounding_box, (int) shape[1], (int) shape[0]);
draw_element(element, x - element_shape[1] / 2, y - element_shape[0] / 2, mask);
}
void image_writer_t::draw_grid(boost::multi_array<uint8_t, 3> &image) {
const int grid_line_width = 2;
const int grid_cells = 10;
auto shape = image.shape();
int grid_width = ((int) shape[1] - (grid_cells + 1) * grid_line_width) / grid_cells;
int grid_height = ((int) shape[0] - (grid_cells + 1) * grid_line_width) / grid_cells;
for (int y = 0; y < shape[0]; y += (grid_height + grid_line_width)) {
for (int i = 0; i < grid_line_width; ++i) {
for (int x = 0; x < shape[1]; ++x) {
for (int c = 0; c < 3; ++c) {
image[y + i][x][c] = std::min(image[y][x][c] + 20, 255);
}
}
}
}
for (int x = 0; x < shape[1]; x += (grid_width + grid_line_width)) {
for (int i = 0; i < grid_line_width; ++i) {
for (int y = 0; y < shape[0]; ++y) {
for (int c = 0; c < 3; ++c) {
image[y][x + i][c] = std::min(image[y][x][c] + 20, 255);
}
}
}
}
}
void image_writer_t::draw_elements() {
auto it = arena.configurations.find(game_mode);
if (it == arena.configurations.end()) {
wotreplay::logger.writef(log_level_t::warning, "Could not find configuration for game mode '%1%'\n", game_mode);
return;
}
const arena_configuration_t &configuration = arena.configurations[game_mode];
int reference_team_id = use_fixed_teamcolors ? 0 : recorder_team;
if (game_mode == "domination") {
auto neutral_base = get_element("neutral_base");
draw_element(neutral_base, configuration.control_point);
}
auto friendly_base = get_element("friendly_base");
auto enemy_base = get_element("enemy_base");
for (const auto &entry : configuration.team_base_positions) {
for (const auto &position : entry.second) {
draw_element((entry.first - 1) == reference_team_id ? friendly_base : enemy_base, position);
}
}
std::vector<boost::multi_array<uint8_t, 3>> spawns{
get_element("neutral_spawn1"),
get_element("neutral_spawn2"),
get_element("neutral_spawn3"),
get_element("neutral_spawn4")
};
for (const auto &entry : configuration.team_spawn_points) {
for (int i = 0; i < entry.second.size(); ++i) {
int mask = (reference_team_id == (entry.first - 1)) ? 0x00FF00FF : 0xFF0000FF;
draw_element(spawns[i], entry.second[i], mask);
}
}
draw_grid(base);
}
void image_writer_t::draw_death(const packet_t &packet, const game_t &game) {
uint32_t killer, killed;
std::tie(killed, killer) = packet.tank_destroyed();
packet_t position_packet;
bool found = game.find_property(packet.clock(), killed, property_t::position, position_packet);
if (found) {
draw_position(position_packet, game, this->deaths);
}
}
void image_writer_t::draw_position(const packet_t &packet, const game_t &game, boost::multi_array<float, 3> &image) {
uint32_t player_id = packet.player_id();
int team_id = game.get_team_id(player_id);
if (team_id < 0) return;
auto shape = image.shape();
int height = static_cast<int>(shape[1]);
int width = static_cast<int>(shape[2]);
const bounding_box_t &bounding_box = game.get_arena().bounding_box;
std::tuple<float, float> position = get_2d_coord(packet.position(), bounding_box, width, height);
long x = std::lround(std::get<0>(position));
long y = std::lround(std::get<1>(position));
if (x >= 0 && y >= 0 && x < width && y < height) {
image[team_id][y][x]++;
if (player_id == game.get_recorder_id()) {
image[2][y][x]++;
}
}
}
void image_writer_t::update(const game_t &game) {
recorder_team = game.get_team_id(game.get_recorder_id());
std::set<int> dead_players;
for (const packet_t &packet : game.get_packets()) {
if (!filter(packet)) continue;
if (packet.has_property(property_t::position)
&& dead_players.find(packet.player_id()) == dead_players.end()) {
draw_position(packet, game, this->positions);
}
else if (packet.has_property(property_t::tank_destroyed)) {
uint32_t target, killer;
std::tie(target, killer) = packet.tank_destroyed();
dead_players.insert(target);
draw_death(packet, game);
}
}
}
void image_writer_t::load_base_map(const std::string &path) {
boost::multi_array<uint8_t, 3> map;
std::ifstream is(path, std::ios::binary);
if (is) {
read_png(is, map);
resize(map, image_width, image_height, this->base);
}
}
void image_writer_t::write(std::ostream &os) {
write_png(os, result);
}
void image_writer_t::init(const arena_t &arena, const std::string &mode) {
this->arena = arena;
this->game_mode = mode;
positions.resize(boost::extents[3][image_height][image_width]);
deaths.resize(boost::extents[3][image_height][image_width]);
clear();
initialized = true;
}
void image_writer_t::clear() {
std::fill(result.origin(), result.origin() + result.num_elements(), 0.f);
std::fill(deaths.origin(), deaths.origin() + deaths.num_elements(), 0.f);
std::fill(positions.origin(), positions.origin() + positions.num_elements(), 0.f);
}
void image_writer_t::finish() {
draw_basemap();
const size_t *shape = base.shape();
result.resize(boost::extents[shape[0]][shape[1]][shape[2]]);
result = base;
int reference_team_id = use_fixed_teamcolors ? 0 : recorder_team;
for (int i = 0; i < image_height; ++i) {
for (int j = 0; j < image_width; ++j) {
if (positions[0][i][j] > positions[1][i][j]) {
// position claimed by first team
if (reference_team_id == 0) {
result[i][j][0] = result[i][j][2] = 0x00;
result[i][j][1] = result[i][j][3] = 0xFF;
}
else {
result[i][j][1] = result[i][j][2] = 0x00;
result[i][j][0] = result[i][j][3] = 0xFF;
}
}
else if (positions[0][i][j] < positions[1][i][j]) {
// position claimed by second team
if (reference_team_id == 0) {
result[i][j][1] = result[i][j][2] = 0x00;
result[i][j][0] = result[i][j][3] = 0xFF;
}
else {
result[i][j][0] = result[i][j][2] = 0x00;
result[i][j][1] = result[i][j][3] = 0xFF;
}
}
else {
// no change
}
if (this->show_self && positions[2][i][j] > 0.f) {
// position claimed by second team
result[i][j][0] = result[i][j][1] = 0x00;
result[i][j][2] = result[i][j][3] = 0xFF;
}
if (deaths[0][i][j] + deaths[1][i][j] > 0.f) {
for (int k = 0; k < 3; k += 1) {
for (int l = 0; l < 3; l += 1) {
int x = j + k - 1;
int y = i + l - 1;
// draw only if within bounds
if (x >= 0 && x < image_width && y >= 0 && y < image_height) {
result[y][x][3] = result[y][x][0] = result[y][x][1] = 0xFF;
result[y][x][2] = 0x00;
}
}
}
}
}
}
}
void image_writer_t::reset() {
// initialize with empty image arrays
initialized = false;
}
bool image_writer_t::is_initialized() const {
return initialized;
}
void image_writer_t::set_show_self(bool show_self) {
this->show_self = show_self;
}
bool image_writer_t::get_show_self() const {
return show_self;
}
void image_writer_t::set_use_fixed_teamcolors(bool use_fixed_teamcolors) {
this->use_fixed_teamcolors = use_fixed_teamcolors;
}
bool image_writer_t::get_use_fixed_teamcolors() const {
return use_fixed_teamcolors;
}
void image_writer_t::set_recorder_team(int recorder_team) {
this->recorder_team = recorder_team;
}
int image_writer_t::get_recorder_team() const {
return recorder_team;
}
void image_writer_t::set_filter(filter_t filter) {
this->filter = filter;
}
const arena_t &image_writer_t::get_arena() const {
return arena;
}
const std::string &image_writer_t::get_game_mode() const {
return game_mode;
}
void image_writer_t::merge(const image_writer_t &writer) {
// TODO: implement this
std::transform(positions.origin(), positions.origin() + positions.num_elements(),
writer.positions.origin(), positions.origin(), std::plus<float>());
}
int image_writer_t::get_image_height() const {
return image_height;
}
void image_writer_t::set_image_height(int image_height) {
this->image_height = image_height;
}
int image_writer_t::get_image_width() const {
return image_width;
}
void image_writer_t::set_image_width(int image_width) {
this->image_width = image_width;
}
bool image_writer_t::get_no_basemap() const {
return no_basemap;
}
void image_writer_t::set_no_basemap(bool no_basemap) {
this->no_basemap = no_basemap;
}
void image_writer_t::draw_basemap() {
if (!no_basemap) {
load_base_map(arena.mini_map);
const size_t *shape = base.shape();
result.resize(boost::extents[shape[0]][shape[1]][shape[2]]);
draw_elements();
}
else {
base.resize(boost::extents[image_width][image_height][4]);
}
}
const boost::multi_array<uint8_t, 3> &image_writer_t::get_result() const {
return result;
}<|endoftext|> |
<commit_before><commit_msg>Added a new optional command-line flag to allow filtering of open-access records.<commit_after><|endoftext|> |
<commit_before>// Copyright (c) 2014 Wenbin He. All rights reserved.
// Use of this source code is governed by a MIT-style license that can be
// found in the LICENSE file.
#include "io/raw_reader.h"
#include "core/basic_types.h"
#include "core/cartesian_grid.h"
#include "core/field.h"
#include "core/float_array.h"
#include "io/console.h"
namespace itl {
std::unique_ptr<Field> RawReader::LoadData(
std::initializer_list<std::pair<const char*, int>> file_list,
bool with_header) {
if (with_header) {
FILE* file;
file = fopen(file_list.begin()->first, "rb");
int dimensions[3];
fread(dimensions, sizeof(int), 3, file);
set_dimensions(dimensions[0], dimensions[1], dimensions[2]);
fclose(file);
}
int data_size = x_dim_ * y_dim_ * z_dim_;
std::unique_ptr<Grid> grid(new CartesianGrid(x_dim_, y_dim_, z_dim_,
x_bias_, y_bias_, z_bias_));
std::unique_ptr<Field> field(new Field());
field->set_grid(grid.release());
for (auto it = file_list.begin(); it != file_list.end(); ++it) {
FILE* file;
file = fopen(it->first, "rb");
if (with_header) {
int dimensions[3];
fread(dimensions, sizeof(int), 3, file);
}
std::unique_ptr<AbstractArray> array;
switch (it->second) {
case kFloat:
array.reset(new FloatArray(data_size));
fread(static_cast<FloatArray*>(array.get())->data(),
sizeof(float), data_size, file);
break;
default:
Console::Warn("RawReader::LoadData() given unsupported data type.");
}
fclose(file);
field->attach_variable(array.release());
}
return field;
}
} // namespace itl
<commit_msg>Update RawReader<commit_after>// Copyright (c) 2014 Wenbin He. All rights reserved.
// Use of this source code is governed by a MIT-style license that can be
// found in the LICENSE file.
#include "io/raw_reader.h"
#include "core/basic_types.h"
#include "core/cartesian_grid.h"
#include "core/field.h"
#include "core/float_array.h"
#include "core/double_array.h"
#include "core/int32_array.h"
#include "io/console.h"
namespace itl {
std::unique_ptr<Field> RawReader::LoadData(
std::initializer_list<std::pair<const char*, int>> file_list,
bool with_header) {
if (with_header) {
FILE* file;
file = fopen(file_list.begin()->first, "rb");
int dimensions[3];
fread(dimensions, sizeof(int), 3, file);
set_dimensions(dimensions[0], dimensions[1], dimensions[2]);
fclose(file);
}
int data_size = x_dim_ * y_dim_ * z_dim_;
std::unique_ptr<Grid> grid(new CartesianGrid(x_dim_, y_dim_, z_dim_,
x_bias_, y_bias_, z_bias_));
std::unique_ptr<Field> field(new Field());
field->set_grid(grid.release());
for (auto it = file_list.begin(); it != file_list.end(); ++it) {
FILE* file;
file = fopen(it->first, "rb");
if (with_header) {
int dimensions[3];
fread(dimensions, sizeof(int), 3, file);
}
std::unique_ptr<AbstractArray> array;
switch (it->second) {
case kFloat:
array.reset(new FloatArray(data_size));
fread(static_cast<FloatArray*>(array.get())->data(),
sizeof(float), data_size, file);
break;
case kDouble:
array.reset(new DoubleArray(data_size));
fread(static_cast<DoubleArray*>(array.get())->data(),
sizeof(double), data_size, file);
break;
case kInt32:
array.reset(new Int32Array(data_size));
fread(static_cast<Int32Array*>(array.get())->data(),
sizeof(int32_t), data_size, file);
default:
Console::Warn("RawReader::LoadData() given unsupported data type.");
}
fclose(file);
field->attach_variable(array.release());
}
return field;
}
} // namespace itl
<|endoftext|> |
<commit_before>#include "itemrenderer.h"
#include <sstream>
#include "configcontainer.h"
#include "htmlrenderer.h"
#include "rssfeed.h"
#include "textformatter.h"
namespace newsboat {
std::string item_renderer::get_feedtitle(std::shared_ptr<RssItem> item) {
const std::shared_ptr<RssFeed> feedptr = item->get_feedptr();
std::string feedtitle;
if (feedptr) {
if (!feedptr->title().empty()) {
feedtitle = feedptr->title();
utils::remove_soft_hyphens(feedtitle);
} else if (!feedptr->link().empty()) {
feedtitle = feedptr->link();
} else if (!feedptr->rssurl().empty()) {
feedtitle = feedptr->rssurl();
}
}
return feedtitle;
}
void prepare_header(
std::shared_ptr<RssItem> item,
std::vector<std::pair<LineType, std::string>>& lines,
std::vector<LinkPair>& /*links*/)
{
const auto add_line =
[&lines]
(const std::string& value,
const std::string& name,
LineType lineType = LineType::wrappable)
{
if (!value.empty()) {
const auto line = strprintf::fmt("%s%s", name, value);
lines.push_back(std::make_pair(lineType, line));
}
};
const std::string feedtitle = item_renderer::get_feedtitle(item);
add_line(feedtitle, _("Feed: "));
add_line(item->title(), _("Title: "));
add_line(item->author(), _("Author: "));
add_line(item->pubDate(), _("Date: "));
add_line(item->link(), _("Link: "), LineType::softwrappable);
add_line(item->flags(), _("Flags: "));
if (!item->enclosure_url().empty()) {
auto dlurl = strprintf::fmt(
"%s%s",
_("Podcast Download URL: "),
utils::censor_url(item->enclosure_url()));
if (!item->enclosure_type().empty()) {
dlurl.append(
strprintf::fmt(" (%s%s)",
_("type: "),
item->enclosure_type()));
}
lines.push_back(std::make_pair(LineType::softwrappable, dlurl));
}
lines.push_back(std::make_pair(LineType::wrappable, std::string("")));
}
std::string get_item_base_link(const std::shared_ptr<RssItem>& item)
{
if (!item->get_base().empty()) {
return item->get_base();
} else {
return item->feedurl();
}
}
void render_html(
ConfigContainer& cfg,
const std::string& source,
std::vector<std::pair<LineType, std::string>>& lines,
std::vector<LinkPair>& thelinks,
const std::string& url,
bool raw)
{
const std::string renderer = cfg.get_configvalue("html-renderer");
if (renderer == "internal") {
HtmlRenderer rnd(raw);
rnd.render(source, lines, thelinks, url);
} else {
char* argv[4];
argv[0] = const_cast<char*>("/bin/sh");
argv[1] = const_cast<char*>("-c");
argv[2] = const_cast<char*>(renderer.c_str());
argv[3] = nullptr;
LOG(Level::DEBUG,
"item_renderer::render_html: source = %s",
source);
LOG(Level::DEBUG,
"item_renderer::render_html: html-renderer = %s",
argv[2]);
const std::string output = utils::run_program(argv, source);
std::istringstream is(output);
std::string line;
while (!is.eof()) {
getline(is, line);
if (!raw) {
line = utils::quote_for_stfl(line);
}
lines.push_back(std::make_pair(LineType::softwrappable, line));
}
}
}
std::string item_renderer::to_plain_text(
ConfigContainer& cfg,
std::shared_ptr<RssItem> item)
{
std::vector<std::pair<LineType, std::string>> lines;
std::vector<LinkPair> links;
prepare_header(item, lines, links);
const auto base = get_item_base_link(item);
render_html(cfg, item->description(), lines, links, base, true);
TextFormatter txtfmt;
txtfmt.add_lines(lines);
unsigned int width = cfg.get_configvalue_as_int("text-width");
if (width == 0) {
width = 80;
}
return txtfmt.format_text_plain(width);
}
std::pair<std::string, size_t> item_renderer::to_stfl_list(
ConfigContainer& cfg,
std::shared_ptr<RssItem> item,
unsigned int text_width,
unsigned int window_width,
RegexManager* rxman,
const std::string& location,
std::vector<LinkPair>& links)
{
std::vector<std::pair<LineType, std::string>> lines;
prepare_header(item, lines, links);
const std::string baseurl = get_item_base_link(item);
const auto body = item->description();
render_html(cfg, body, lines, links, baseurl, false);
TextFormatter txtfmt;
txtfmt.add_lines(lines);
return txtfmt.format_text_to_list(rxman, location, text_width, window_width);
}
void render_source(
std::vector<std::pair<LineType, std::string>>& lines,
std::string source)
{
/*
* This function is called instead of HtmlRenderer::render() when the
* user requests to have the source displayed instead of seeing the
* rendered HTML.
*/
std::string line;
do {
std::string::size_type pos = source.find_first_of("\r\n");
line = source.substr(0, pos);
if (pos == std::string::npos) {
source.erase();
} else {
source.erase(0, pos + 1);
}
lines.push_back(std::make_pair(LineType::softwrappable, line));
} while (source.length() > 0);
}
std::pair<std::string, size_t> item_renderer::source_to_stfl_list(
std::shared_ptr<RssItem> item,
unsigned int text_width,
unsigned int window_width,
RegexManager* rxman,
const std::string& location)
{
std::vector<std::pair<LineType, std::string>> lines;
std::vector<LinkPair> links;
prepare_header(item, lines, links);
render_source(lines, utils::quote_for_stfl(item->description()));
TextFormatter txtfmt;
txtfmt.add_lines(lines);
return txtfmt.format_text_to_list(rxman, location, text_width, window_width);
}
}
<commit_msg>Minimize nesting in item_renderer::get_feedtitle<commit_after>#include "itemrenderer.h"
#include <sstream>
#include "configcontainer.h"
#include "htmlrenderer.h"
#include "rssfeed.h"
#include "textformatter.h"
namespace newsboat {
std::string item_renderer::get_feedtitle(std::shared_ptr<RssItem> item) {
const std::shared_ptr<RssFeed> feedptr = item->get_feedptr();
if (!feedptr) {
return {};
}
std::string feedtitle;
if (!feedptr->title().empty()) {
feedtitle = feedptr->title();
utils::remove_soft_hyphens(feedtitle);
} else if (!feedptr->link().empty()) {
feedtitle = feedptr->link();
} else if (!feedptr->rssurl().empty()) {
feedtitle = feedptr->rssurl();
}
return feedtitle;
}
void prepare_header(
std::shared_ptr<RssItem> item,
std::vector<std::pair<LineType, std::string>>& lines,
std::vector<LinkPair>& /*links*/)
{
const auto add_line =
[&lines]
(const std::string& value,
const std::string& name,
LineType lineType = LineType::wrappable)
{
if (!value.empty()) {
const auto line = strprintf::fmt("%s%s", name, value);
lines.push_back(std::make_pair(lineType, line));
}
};
const std::string feedtitle = item_renderer::get_feedtitle(item);
add_line(feedtitle, _("Feed: "));
add_line(item->title(), _("Title: "));
add_line(item->author(), _("Author: "));
add_line(item->pubDate(), _("Date: "));
add_line(item->link(), _("Link: "), LineType::softwrappable);
add_line(item->flags(), _("Flags: "));
if (!item->enclosure_url().empty()) {
auto dlurl = strprintf::fmt(
"%s%s",
_("Podcast Download URL: "),
utils::censor_url(item->enclosure_url()));
if (!item->enclosure_type().empty()) {
dlurl.append(
strprintf::fmt(" (%s%s)",
_("type: "),
item->enclosure_type()));
}
lines.push_back(std::make_pair(LineType::softwrappable, dlurl));
}
lines.push_back(std::make_pair(LineType::wrappable, std::string("")));
}
std::string get_item_base_link(const std::shared_ptr<RssItem>& item)
{
if (!item->get_base().empty()) {
return item->get_base();
} else {
return item->feedurl();
}
}
void render_html(
ConfigContainer& cfg,
const std::string& source,
std::vector<std::pair<LineType, std::string>>& lines,
std::vector<LinkPair>& thelinks,
const std::string& url,
bool raw)
{
const std::string renderer = cfg.get_configvalue("html-renderer");
if (renderer == "internal") {
HtmlRenderer rnd(raw);
rnd.render(source, lines, thelinks, url);
} else {
char* argv[4];
argv[0] = const_cast<char*>("/bin/sh");
argv[1] = const_cast<char*>("-c");
argv[2] = const_cast<char*>(renderer.c_str());
argv[3] = nullptr;
LOG(Level::DEBUG,
"item_renderer::render_html: source = %s",
source);
LOG(Level::DEBUG,
"item_renderer::render_html: html-renderer = %s",
argv[2]);
const std::string output = utils::run_program(argv, source);
std::istringstream is(output);
std::string line;
while (!is.eof()) {
getline(is, line);
if (!raw) {
line = utils::quote_for_stfl(line);
}
lines.push_back(std::make_pair(LineType::softwrappable, line));
}
}
}
std::string item_renderer::to_plain_text(
ConfigContainer& cfg,
std::shared_ptr<RssItem> item)
{
std::vector<std::pair<LineType, std::string>> lines;
std::vector<LinkPair> links;
prepare_header(item, lines, links);
const auto base = get_item_base_link(item);
render_html(cfg, item->description(), lines, links, base, true);
TextFormatter txtfmt;
txtfmt.add_lines(lines);
unsigned int width = cfg.get_configvalue_as_int("text-width");
if (width == 0) {
width = 80;
}
return txtfmt.format_text_plain(width);
}
std::pair<std::string, size_t> item_renderer::to_stfl_list(
ConfigContainer& cfg,
std::shared_ptr<RssItem> item,
unsigned int text_width,
unsigned int window_width,
RegexManager* rxman,
const std::string& location,
std::vector<LinkPair>& links)
{
std::vector<std::pair<LineType, std::string>> lines;
prepare_header(item, lines, links);
const std::string baseurl = get_item_base_link(item);
const auto body = item->description();
render_html(cfg, body, lines, links, baseurl, false);
TextFormatter txtfmt;
txtfmt.add_lines(lines);
return txtfmt.format_text_to_list(rxman, location, text_width, window_width);
}
void render_source(
std::vector<std::pair<LineType, std::string>>& lines,
std::string source)
{
/*
* This function is called instead of HtmlRenderer::render() when the
* user requests to have the source displayed instead of seeing the
* rendered HTML.
*/
std::string line;
do {
std::string::size_type pos = source.find_first_of("\r\n");
line = source.substr(0, pos);
if (pos == std::string::npos) {
source.erase();
} else {
source.erase(0, pos + 1);
}
lines.push_back(std::make_pair(LineType::softwrappable, line));
} while (source.length() > 0);
}
std::pair<std::string, size_t> item_renderer::source_to_stfl_list(
std::shared_ptr<RssItem> item,
unsigned int text_width,
unsigned int window_width,
RegexManager* rxman,
const std::string& location)
{
std::vector<std::pair<LineType, std::string>> lines;
std::vector<LinkPair> links;
prepare_header(item, lines, links);
render_source(lines, utils::quote_for_stfl(item->description()));
TextFormatter txtfmt;
txtfmt.add_lines(lines);
return txtfmt.format_text_to_list(rxman, location, text_width, window_width);
}
}
<|endoftext|> |
<commit_before>// @(#)root/dcache:$Name: v3-03-05 $:$Id: TDCacheFile.cxx,v 1.2 2002/03/25 16:43:16 rdm Exp $
// Author: Grzegorz Mazur 20/01/2002
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TDCacheFile //
// //
// A TDCacheFile is like a normal TFile except that it may read and //
// write its data via a dCache server (for more on the dCache daemon //
// see http://www-dcache.desy.de/. Given a path which doesn't belong //
// to the dCache managed filesystem, it falls back to the ordinary //
// TFile behaviour. //
// //
//////////////////////////////////////////////////////////////////////////
#include "TDCacheFile.h"
#include "TError.h"
#include "TSystem.h"
#include "TROOT.h"
#include <errno.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dcap.h>
//______________________________________________________________________________
static const char* const DCACHE_PREFIX = "dcache:";
static const size_t DCACHE_PREFIX_LEN = strlen(DCACHE_PREFIX);
static const char* const DCAP_PREFIX = "dcap:";
static const size_t DCAP_PREFIX_LEN = strlen(DCAP_PREFIX);
//______________________________________________________________________________
ClassImp(TDCacheFile)
//______________________________________________________________________________
TDCacheFile::TDCacheFile(const char *path, Option_t *option,
const char *ftitle, Int_t compress):
TFile(path, "NET", ftitle, compress)
{
// get rid of the optional URI
if (!strncmp(path, DCACHE_PREFIX, DCACHE_PREFIX_LEN))
path += 7;
fOption = option;
fOffset = 0;
Bool_t create = kFALSE;
if (!fOption.CompareTo("NEW", TString::kIgnoreCase) ||
!fOption.CompareTo("CREATE", TString::kIgnoreCase))
create = kTRUE;
Bool_t recreate = fOption.CompareTo("RECREATE", TString::kIgnoreCase)
? kFALSE : kTRUE;
Bool_t update = fOption.CompareTo("UPDATE", TString::kIgnoreCase)
? kFALSE : kTRUE;
Bool_t read = fOption.CompareTo("READ", TString::kIgnoreCase)
? kFALSE : kTRUE;
if (!create && !recreate && !update && !read) {
read = kTRUE;
fOption = "READ";
}
const char *fname;
if (!strncmp(path, DCAP_PREFIX, DCAP_PREFIX_LEN)) {
// Ugh, no PNFS support
if (create || recreate || update) {
Error("TDCacheFile", "Without PNFS support only reading access is allowed.");
goto zombie;
}
SetName(path);
fname = GetName();
} else {
// Metadata provided by PNFS
if ((fname = gSystem->ExpandPathName(path))) {
SetName(fname);
delete [] (char*)fname;
fname = GetName();
} else {
Error("TDCacheFile", "error expanding path %s", path);
goto zombie;
}
if (recreate) {
if (!gSystem->AccessPathName(fname, kFileExists))
gSystem->Unlink(fname);
recreate = kFALSE;
create = kTRUE;
fOption = "CREATE";
}
if (create && !gSystem->AccessPathName(fname, kFileExists)) {
Error("TDCacheFile", "file %s already exists", fname);
goto zombie;
}
if (update) {
if (gSystem->AccessPathName(fname, kFileExists)) {
update = kFALSE;
create = kTRUE;
}
if (update && gSystem->AccessPathName(fname, kWritePermission)) {
Error("TDCacheFile", "no write permission, could not open file %s", fname);
goto zombie;
}
}
if (read) {
if (gSystem->AccessPathName(fname, kFileExists)) {
Error("TDCacheFile", "file %s does not exist", fname);
goto zombie;
}
if (gSystem->AccessPathName(fname, kReadPermission)) {
Error("TDCacheFile", "no read permission, could not open file %s", fname);
goto zombie;
}
}
}
// Connect to file system stream
if (create || update) {
#ifndef WIN32
fD = SysOpen(fname, O_RDWR | O_CREAT, 0644);
#else
fD = SysOpen(fname, O_RDWR | O_CREAT | O_BINARY, S_IREAD | S_IWRITE);
#endif
if (fD == -1) {
SysError("TDCacheFile", "file %s can not be opened", fname);
goto zombie;
}
fWritable = kTRUE;
} else {
#ifndef WIN32
fD = SysOpen(fname, O_RDONLY, 0644);
#else
fD = SysOpen(fname, O_RDONLY | O_BINARY, S_IREAD | S_IWRITE);
#endif
if (fD == -1) {
SysError("TFile", "file %s can not be opened for reading", fname);
goto zombie;
}
fWritable = kFALSE;
}
// Disable dCache read-ahead buffer, as it doesn't cooperate well
// with usually non-sequential file access pattern typical for
// TFile. TCache performs much better, so UseCache() should be used
// instead.
dc_noBuffering(fD);
Init(create);
return;
zombie:
// error in file opening occured, make this object a zombie
MakeZombie();
gDirectory = gROOT;
}
//______________________________________________________________________________
TDCacheFile::~TDCacheFile()
{
// Close and cleanup dCache file.
Close();
}
//______________________________________________________________________________
Bool_t TDCacheFile::ReadBuffer(char *buf, Int_t len)
{
// Read specified byte range from remote file via dCache daemon.
// Returns kTRUE in case of error.
if (fCache) {
Int_t st;
Seek_t off = fOffset;
if ((st = fCache->ReadBuffer(fOffset, buf, len)) < 0) {
Error("ReadBuffer", "error reading from cache");
return kTRUE;
}
if (st > 0) {
// fOffset might have been changed via TCache::ReadBuffer(), reset it
fOffset = off + len;
return kFALSE;
}
}
return TFile::ReadBuffer(buf, len);
}
//______________________________________________________________________________
Bool_t TDCacheFile::WriteBuffer(const char *buf, Int_t len)
{
// Write specified byte range to remote file via dCache daemon.
// Returns kTRUE in case of error.
if (!IsOpen() || !fWritable) return kTRUE;
if (fCache) {
Int_t st;
Seek_t off = fOffset;
if ((st = fCache->WriteBuffer(fOffset, buf, len)) < 0) {
Error("WriteBuffer", "error writing to cache");
return kTRUE;
}
if (st > 0) {
// fOffset might have been changed via TCache::WriteBuffer(), reset it
fOffset = off + len;
return kFALSE;
}
}
return TFile::WriteBuffer(buf, len);
}
//______________________________________________________________________________
Bool_t TDCacheFile::Stage(const char *path, UInt_t after, const char *location)
{
// Stage() returns kTRUE on success and kFALSE on failure.
if (!strncmp(path, DCACHE_PREFIX, DCACHE_PREFIX_LEN))
path += 7;
dc_errno = 0;
if (dc_stage(path, after, location) == 0)
return kTRUE;
if (dc_errno != 0)
gSystem->SetErrorStr(dc_strerror(dc_errno));
else
gSystem->SetErrorStr(strerror(errno));
return kFALSE;
}
//______________________________________________________________________________
Bool_t TDCacheFile::CheckFile(const char *path, const char *location)
{
// Note: Name of the method was changed to avoid collision with Check
// macro #defined in ROOT.
// CheckFile() returns kTRUE on success and kFALSE on failure. In
// case the file exists but is not cached, CheckFile() returns
// kFALSE and errno is set to EAGAIN.
if (!strncmp(path, DCACHE_PREFIX, DCACHE_PREFIX_LEN))
path += 7;
dc_errno = 0;
if (dc_check(path, location) == 0)
return kTRUE;
if (dc_errno != 0)
gSystem->SetErrorStr(dc_strerror(dc_errno));
else
gSystem->SetErrorStr(strerror(errno));
return kFALSE;
}
//______________________________________________________________________________
void TDCacheFile::SetOpenTimeout(UInt_t n)
{
dc_setOpenTimeout(n);
}
//______________________________________________________________________________
void TDCacheFile::SetOnError(OnErrorAction a)
{
dc_setOnError(a);
}
//______________________________________________________________________________
void TDCacheFile::SetReplyHostName(const char *host_name)
{
dc_setReplyHostName((char*)host_name);
}
//______________________________________________________________________________
const char *TDCacheFile::GetDcapVersion()
{
return getDcapVersion();
}
//______________________________________________________________________________
Bool_t TDCacheFile::EnableSSL()
{
#ifdef DCAP_USE_SSL
dc_enableSSL();
return kTRUE;
#else
return kFALSE;
#endif
}
//______________________________________________________________________________
Int_t TDCacheFile::SysOpen(const char *pathname, Int_t flags, UInt_t mode)
{
dc_errno = 0;
Int_t rc = dc_open(pathname, flags, (Int_t) mode);
if (rc < 0) {
if (dc_errno != 0)
gSystem->SetErrorStr(dc_strerror(dc_errno));
else
gSystem->SetErrorStr(strerror(errno));
}
return rc;
}
//______________________________________________________________________________
Int_t TDCacheFile::SysClose(Int_t fd)
{
dc_errno = 0;
Int_t rc = dc_close(fd);
if (rc < 0) {
if (dc_errno != 0)
gSystem->SetErrorStr(dc_strerror(dc_errno));
else
gSystem->SetErrorStr(strerror(errno));
}
return rc;
}
//______________________________________________________________________________
Int_t TDCacheFile::SysRead(Int_t fd, void *buf, Int_t len)
{
fOffset += len;
dc_errno = 0;
Int_t rc = dc_read(fd, buf, len);
if (rc < 0) {
if (dc_errno != 0)
gSystem->SetErrorStr(dc_strerror(dc_errno));
else
gSystem->SetErrorStr(strerror(errno));
}
return rc;
}
//______________________________________________________________________________
Int_t TDCacheFile::SysWrite(Int_t fd, const void *buf, Int_t len)
{
fOffset += len;
dc_errno = 0;
Int_t rc = dc_write(fd, (char *)buf, len);
if (rc < 0) {
if (dc_errno != 0)
gSystem->SetErrorStr(dc_strerror(dc_errno));
else
gSystem->SetErrorStr(strerror(errno));
}
return rc;
}
//______________________________________________________________________________
Seek_t TDCacheFile::SysSeek(Int_t fd, Seek_t offset, Int_t whence)
{
switch (whence) {
case SEEK_SET:
if (offset == fOffset)
return offset;
else
fOffset = offset;
break;
case SEEK_CUR:
fOffset += offset;
break;
case SEEK_END:
fOffset = fEND + offset;
break;
}
dc_errno = 0;
Int_t rc = dc_lseek(fd, offset, whence);
if (rc < 0) {
if (dc_errno != 0)
gSystem->SetErrorStr(dc_strerror(dc_errno));
else
gSystem->SetErrorStr(strerror(errno));
}
return rc;
}
//______________________________________________________________________________
Int_t TDCacheFile::SysSync(Int_t fd)
{
// dCache always keep it's files sync'ed, so there's no need to
// sync() them manually.
return 0;
}
//______________________________________________________________________________
Int_t TDCacheFile::SysStat(Int_t fd, Long_t *id, Long_t *size,
Long_t *flags, Long_t *modtime)
{
// FIXME: dcap library doesn't (yet) provide any stat()
// capabilities, relying on PNFS to provide all meta-level data. In
// spite of this, it is possible to open a file which is not
// accessible via PNFS. In such case we do some dirty tricks to
// provide as much information as possible, but not everything can
// really be done correctly.
if (!strncmp(GetName(), DCAP_PREFIX, DCAP_PREFIX_LEN)) {
// Ugh, no PNFS support.
// Try to provide a unique id
*id = ::Hash(GetName());
// Funny way of checking the file size, isn't it?
Seek_t offset = fOffset;
*size = SysSeek(fd, 0, SEEK_END);
SysSeek(fd, offset, SEEK_SET);
*flags = 0; // This one is easy, only ordinary files are allowed here
*modtime = 0; // FIXME: no way to get it right without dc_stat()
return 0;
} else {
return TFile::SysStat(fd, id, size, flags, modtime);
}
}
//______________________________________________________________________________
void TDCacheFile::ResetErrno() const
{
// Method resetting the dc_errno and errno.
dc_errno = 0;
TSystem::ResetErrno();
}
<commit_msg>small mod in option handling.<commit_after>// @(#)root/dcache:$Name: $:$Id: TDCacheFile.cxx,v 1.3 2002/07/19 11:41:41 rdm Exp $
// Author: Grzegorz Mazur 20/01/2002
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TDCacheFile //
// //
// A TDCacheFile is like a normal TFile except that it may read and //
// write its data via a dCache server (for more on the dCache daemon //
// see http://www-dcache.desy.de/. Given a path which doesn't belong //
// to the dCache managed filesystem, it falls back to the ordinary //
// TFile behaviour. //
// //
//////////////////////////////////////////////////////////////////////////
#include "TDCacheFile.h"
#include "TError.h"
#include "TSystem.h"
#include "TROOT.h"
#include <errno.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dcap.h>
//______________________________________________________________________________
static const char* const DCACHE_PREFIX = "dcache:";
static const size_t DCACHE_PREFIX_LEN = strlen(DCACHE_PREFIX);
static const char* const DCAP_PREFIX = "dcap:";
static const size_t DCAP_PREFIX_LEN = strlen(DCAP_PREFIX);
//______________________________________________________________________________
ClassImp(TDCacheFile)
//______________________________________________________________________________
TDCacheFile::TDCacheFile(const char *path, Option_t *option,
const char *ftitle, Int_t compress):
TFile(path, "NET", ftitle, compress)
{
// get rid of the optional URI
if (!strncmp(path, DCACHE_PREFIX, DCACHE_PREFIX_LEN))
path += 7;
fOffset = 0;
fOption = option;
fOption.ToUpper();
if (fOption == "NEW")
fOption = "CREATE";
Bool_t create = (fOption == "CREATE") ? kTRUE : kFALSE;
Bool_t recreate = (fOption == "RECREATE") ? kTRUE : kFALSE;
Bool_t update = (fOption == "UPDATE") ? kTRUE : kFALSE;
Bool_t read = (fOption == "READ") ? kTRUE : kFALSE;
if (!create && !recreate && !update && !read) {
read = kTRUE;
fOption = "READ";
}
const char *fname;
if (!strncmp(path, DCAP_PREFIX, DCAP_PREFIX_LEN)) {
// Ugh, no PNFS support
if (create || recreate || update) {
Error("TDCacheFile", "Without PNFS support only reading access is allowed.");
goto zombie;
}
SetName(path);
fname = GetName();
} else {
// Metadata provided by PNFS
if ((fname = gSystem->ExpandPathName(path))) {
SetName(fname);
delete [] (char*)fname;
fname = GetName();
} else {
Error("TDCacheFile", "error expanding path %s", path);
goto zombie;
}
if (recreate) {
if (!gSystem->AccessPathName(fname, kFileExists))
gSystem->Unlink(fname);
recreate = kFALSE;
create = kTRUE;
fOption = "CREATE";
}
if (create && !gSystem->AccessPathName(fname, kFileExists)) {
Error("TDCacheFile", "file %s already exists", fname);
goto zombie;
}
if (update) {
if (gSystem->AccessPathName(fname, kFileExists)) {
update = kFALSE;
create = kTRUE;
}
if (update && gSystem->AccessPathName(fname, kWritePermission)) {
Error("TDCacheFile", "no write permission, could not open file %s", fname);
goto zombie;
}
}
if (read) {
if (gSystem->AccessPathName(fname, kFileExists)) {
Error("TDCacheFile", "file %s does not exist", fname);
goto zombie;
}
if (gSystem->AccessPathName(fname, kReadPermission)) {
Error("TDCacheFile", "no read permission, could not open file %s", fname);
goto zombie;
}
}
}
// Connect to file system stream
if (create || update) {
#ifndef WIN32
fD = SysOpen(fname, O_RDWR | O_CREAT, 0644);
#else
fD = SysOpen(fname, O_RDWR | O_CREAT | O_BINARY, S_IREAD | S_IWRITE);
#endif
if (fD == -1) {
SysError("TDCacheFile", "file %s can not be opened", fname);
goto zombie;
}
fWritable = kTRUE;
} else {
#ifndef WIN32
fD = SysOpen(fname, O_RDONLY, 0644);
#else
fD = SysOpen(fname, O_RDONLY | O_BINARY, S_IREAD | S_IWRITE);
#endif
if (fD == -1) {
SysError("TFile", "file %s can not be opened for reading", fname);
goto zombie;
}
fWritable = kFALSE;
}
// Disable dCache read-ahead buffer, as it doesn't cooperate well
// with usually non-sequential file access pattern typical for
// TFile. TCache performs much better, so UseCache() should be used
// instead.
dc_noBuffering(fD);
Init(create);
return;
zombie:
// error in file opening occured, make this object a zombie
MakeZombie();
gDirectory = gROOT;
}
//______________________________________________________________________________
TDCacheFile::~TDCacheFile()
{
// Close and cleanup dCache file.
Close();
}
//______________________________________________________________________________
Bool_t TDCacheFile::ReadBuffer(char *buf, Int_t len)
{
// Read specified byte range from remote file via dCache daemon.
// Returns kTRUE in case of error.
if (fCache) {
Int_t st;
Seek_t off = fOffset;
if ((st = fCache->ReadBuffer(fOffset, buf, len)) < 0) {
Error("ReadBuffer", "error reading from cache");
return kTRUE;
}
if (st > 0) {
// fOffset might have been changed via TCache::ReadBuffer(), reset it
fOffset = off + len;
return kFALSE;
}
}
return TFile::ReadBuffer(buf, len);
}
//______________________________________________________________________________
Bool_t TDCacheFile::WriteBuffer(const char *buf, Int_t len)
{
// Write specified byte range to remote file via dCache daemon.
// Returns kTRUE in case of error.
if (!IsOpen() || !fWritable) return kTRUE;
if (fCache) {
Int_t st;
Seek_t off = fOffset;
if ((st = fCache->WriteBuffer(fOffset, buf, len)) < 0) {
Error("WriteBuffer", "error writing to cache");
return kTRUE;
}
if (st > 0) {
// fOffset might have been changed via TCache::WriteBuffer(), reset it
fOffset = off + len;
return kFALSE;
}
}
return TFile::WriteBuffer(buf, len);
}
//______________________________________________________________________________
Bool_t TDCacheFile::Stage(const char *path, UInt_t after, const char *location)
{
// Stage() returns kTRUE on success and kFALSE on failure.
if (!strncmp(path, DCACHE_PREFIX, DCACHE_PREFIX_LEN))
path += 7;
dc_errno = 0;
if (dc_stage(path, after, location) == 0)
return kTRUE;
if (dc_errno != 0)
gSystem->SetErrorStr(dc_strerror(dc_errno));
else
gSystem->SetErrorStr(strerror(errno));
return kFALSE;
}
//______________________________________________________________________________
Bool_t TDCacheFile::CheckFile(const char *path, const char *location)
{
// Note: Name of the method was changed to avoid collision with Check
// macro #defined in ROOT.
// CheckFile() returns kTRUE on success and kFALSE on failure. In
// case the file exists but is not cached, CheckFile() returns
// kFALSE and errno is set to EAGAIN.
if (!strncmp(path, DCACHE_PREFIX, DCACHE_PREFIX_LEN))
path += 7;
dc_errno = 0;
if (dc_check(path, location) == 0)
return kTRUE;
if (dc_errno != 0)
gSystem->SetErrorStr(dc_strerror(dc_errno));
else
gSystem->SetErrorStr(strerror(errno));
return kFALSE;
}
//______________________________________________________________________________
void TDCacheFile::SetOpenTimeout(UInt_t n)
{
dc_setOpenTimeout(n);
}
//______________________________________________________________________________
void TDCacheFile::SetOnError(OnErrorAction a)
{
dc_setOnError(a);
}
//______________________________________________________________________________
void TDCacheFile::SetReplyHostName(const char *host_name)
{
dc_setReplyHostName((char*)host_name);
}
//______________________________________________________________________________
const char *TDCacheFile::GetDcapVersion()
{
return getDcapVersion();
}
//______________________________________________________________________________
Bool_t TDCacheFile::EnableSSL()
{
#ifdef DCAP_USE_SSL
dc_enableSSL();
return kTRUE;
#else
return kFALSE;
#endif
}
//______________________________________________________________________________
Int_t TDCacheFile::SysOpen(const char *pathname, Int_t flags, UInt_t mode)
{
dc_errno = 0;
Int_t rc = dc_open(pathname, flags, (Int_t) mode);
if (rc < 0) {
if (dc_errno != 0)
gSystem->SetErrorStr(dc_strerror(dc_errno));
else
gSystem->SetErrorStr(strerror(errno));
}
return rc;
}
//______________________________________________________________________________
Int_t TDCacheFile::SysClose(Int_t fd)
{
dc_errno = 0;
Int_t rc = dc_close(fd);
if (rc < 0) {
if (dc_errno != 0)
gSystem->SetErrorStr(dc_strerror(dc_errno));
else
gSystem->SetErrorStr(strerror(errno));
}
return rc;
}
//______________________________________________________________________________
Int_t TDCacheFile::SysRead(Int_t fd, void *buf, Int_t len)
{
fOffset += len;
dc_errno = 0;
Int_t rc = dc_read(fd, buf, len);
if (rc < 0) {
if (dc_errno != 0)
gSystem->SetErrorStr(dc_strerror(dc_errno));
else
gSystem->SetErrorStr(strerror(errno));
}
return rc;
}
//______________________________________________________________________________
Int_t TDCacheFile::SysWrite(Int_t fd, const void *buf, Int_t len)
{
fOffset += len;
dc_errno = 0;
Int_t rc = dc_write(fd, (char *)buf, len);
if (rc < 0) {
if (dc_errno != 0)
gSystem->SetErrorStr(dc_strerror(dc_errno));
else
gSystem->SetErrorStr(strerror(errno));
}
return rc;
}
//______________________________________________________________________________
Seek_t TDCacheFile::SysSeek(Int_t fd, Seek_t offset, Int_t whence)
{
switch (whence) {
case SEEK_SET:
if (offset == fOffset)
return offset;
else
fOffset = offset;
break;
case SEEK_CUR:
fOffset += offset;
break;
case SEEK_END:
fOffset = fEND + offset;
break;
}
dc_errno = 0;
Int_t rc = dc_lseek(fd, offset, whence);
if (rc < 0) {
if (dc_errno != 0)
gSystem->SetErrorStr(dc_strerror(dc_errno));
else
gSystem->SetErrorStr(strerror(errno));
}
return rc;
}
//______________________________________________________________________________
Int_t TDCacheFile::SysSync(Int_t fd)
{
// dCache always keep it's files sync'ed, so there's no need to
// sync() them manually.
return 0;
}
//______________________________________________________________________________
Int_t TDCacheFile::SysStat(Int_t fd, Long_t *id, Long_t *size,
Long_t *flags, Long_t *modtime)
{
// FIXME: dcap library doesn't (yet) provide any stat()
// capabilities, relying on PNFS to provide all meta-level data. In
// spite of this, it is possible to open a file which is not
// accessible via PNFS. In such case we do some dirty tricks to
// provide as much information as possible, but not everything can
// really be done correctly.
if (!strncmp(GetName(), DCAP_PREFIX, DCAP_PREFIX_LEN)) {
// Ugh, no PNFS support.
// Try to provide a unique id
*id = ::Hash(GetName());
// Funny way of checking the file size, isn't it?
Seek_t offset = fOffset;
*size = SysSeek(fd, 0, SEEK_END);
SysSeek(fd, offset, SEEK_SET);
*flags = 0; // This one is easy, only ordinary files are allowed here
*modtime = 0; // FIXME: no way to get it right without dc_stat()
return 0;
} else {
return TFile::SysStat(fd, id, size, flags, modtime);
}
}
//______________________________________________________________________________
void TDCacheFile::ResetErrno() const
{
// Method resetting the dc_errno and errno.
dc_errno = 0;
TSystem::ResetErrno();
}
<|endoftext|> |
<commit_before>
#include "microsoftpush.hh"
#include "log/logmanager.hh"
#include "sofia-sip/base64.h"
#include <string.h>
#include <iostream>
#include <vector>
using namespace std;
WindowsPhonePushNotificationRequest::WindowsPhonePushNotificationRequest(const PushInfo &pinfo)
: PushNotificationRequest(pinfo.mAppId, pinfo.mType), mPushInfo(pinfo) {
if(pinfo.mType == "wp"){
createHTTPRequest("");
}
}
void WindowsPhonePushNotificationRequest::createHTTPRequest(const std::string &access_token) {
const string &host = mPushInfo.mAppId;
char decodeUri[512] = {0};
bool is_message = mPushInfo.mEvent == PushInfo::Message;
const std::string &message = mPushInfo.mText;
const std::string &sender_name = mPushInfo.mFromName;
const std::string &sender_uri = mPushInfo.mFromUri;
ostringstream httpBody;
ostringstream httpHeader;
if(mPushInfo.mType == "w10") {
char unescapedUrl[512];
url_unescape(unescapedUrl, mPushInfo.mDeviceToken.c_str());
base64_d(decodeUri, sizeof(decodeUri), unescapedUrl);
string query(decodeUri);
if (is_message) {
// We have to send the content of the message and the name of the sender.
// We also need the sender address to be able to display the full chat view in case the receiver click the
// toast.
httpBody << "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
<< "<toast launch=\"" << "chat?sip=" << sender_uri << "\">"
<< "<visual>"
<< "<binding template =\"ToastGeneric\">"
<< "<text>" << sender_uri << "</text>"
<< "<text>" << message << "</text>"
<< "</binding>"
<< "</visual>"
<< "</toast>";
} else {
// No need to specify name or number, this PN will only wake up linphone.
httpBody << "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
<< "<toast launch=\"" << sender_uri << "\" >"
<< "<visual>"
<< "<binding template=\"ToastGeneric\" >"
<< "<text>Incoming Call</text>"
<< "<text>" << sender_uri << "</text>"
<< "</binding>"
<< "</visual>"
<< "</toast>";
}
httpHeader << "POST " << query << " HTTP/1.1\r\n"
<< "Authorization: Bearer " << access_token << "\r\n"
<< "X-WNS-RequestForStatus: true\r\n"
<< "X-WNS-Type: wns/toast\r\n"
<< "Content-Type: text/xml\r\n"
<< "Host: " << host << "\r\n"
<< "Content-Length: " << httpBody.str().size() << "\r\n\r\n";
} else if(mPushInfo.mType == "wp"){
if(is_message){
httpBody << "<?xml version=\"1.0\" encoding=\"utf-8\"?><wp:Notification "
"xmlns:wp=\"WPNotification\"><wp:Toast><wp:Text1>"
<< sender_name << "</wp:Text1><wp:Text2>" << message << "</wp:Text2><wp:Param>"
<< "/Views/Chat.xaml?sip=" << sender_uri << "</wp:Param></wp:Toast></wp:Notification>";
// Notification class 2 is the type for toast notifitcation.
httpHeader
<< "POST " << mPushInfo.mDeviceToken << " HTTP/1.1\r\nHost:" << host
<< "\r\nX-WindowsPhone-Target:toast\r\nX-NotificationClass:2\r\nContent-Type:text/xml\r\nContent-Length:"
<< httpBody.str().size() << "\r\n\r\n";
} else {
httpBody << "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
<< "<IncomingCall><Name></Name><Number></Number></IncomingCall>";
// Notification class 4 is the type for VoIP incoming call.
httpHeader << "POST " << mPushInfo.mDeviceToken << " HTTP/1.1\r\nHost:" << host
<< "\r\nX-NotificationClass:4\r\nContent-Type:text/xml\r\nContent-Length:" << httpBody.str().size()
<< "\r\n\r\n";
}
}
mHttpHeader = httpHeader.str();
mHttpBody = httpBody.str();
SLOGD << "PNR " << this << " POST header is " << mHttpHeader;
SLOGD << "PNR " << this << " POST body is " << mHttpBody;
}
void WindowsPhonePushNotificationRequest::createPushNotification() {
int headerLength = mHttpHeader.length();
int bodyLength = mHttpBody.length();
mBuffer.clear();
mBuffer.resize(headerLength + bodyLength);
char *binaryMessageBuff = &mBuffer[0];
char *binaryMessagePt = binaryMessageBuff;
memcpy(binaryMessagePt, &mHttpHeader[0], headerLength);
binaryMessagePt += headerLength;
memcpy(binaryMessagePt, &mHttpBody[0], bodyLength);
binaryMessagePt += bodyLength;
}
const vector<char> &WindowsPhonePushNotificationRequest::getData() {
createPushNotification();
return mBuffer;
}
std::string WindowsPhonePushNotificationRequest::isValidResponse(const string &str) {
string line;
istringstream iss(str);
bool valid = false, connect = false, notif = false;
while (getline(iss, line)) {
if(mPushInfo.mType == "w10"){
valid |= (line.find("HTTP/1.1 200 OK") != string::npos);
connect |= (line.find("X-WNS-DEVICECONNECTIONSTATUS: connected") != string::npos);
notif |= (line.find("X-WNS-STATUS: received") != string::npos);
} else {
connect |= (line.find("X-DeviceConnectionStatus: connected") != string::npos);
notif |= (line.find("X-NotificationStatus: Received") != string::npos);
valid |= (line.find("X-SubscriptionStatus: Active") != string::npos);
}
auto it = line.find("X-WNS-ERROR-DESCRIPTION");
if (it != string::npos) {
return line.substr(line.find(' '));
}
}
if (!valid) return "Unexpected HTTP response value (not 200 OK)";
if (!connect) return "Device connection status not set to connected";
if (!notif) return "Notification not received by server";
return "";
}
<commit_msg>fix potential buffer overflow and reformat source code<commit_after>/*
Flexisip, a flexible SIP proxy server with media capabilities.
Copyright (C) 2010-2015 Belledonne Communications SARL, All rights reserved.
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 "microsoftpush.hh"
#include "log/logmanager.hh"
#include "sofia-sip/base64.h"
#include <string.h>
#include <iostream>
#include <vector>
using namespace std;
WindowsPhonePushNotificationRequest::WindowsPhonePushNotificationRequest ( const PushInfo &pinfo )
: PushNotificationRequest ( pinfo.mAppId, pinfo.mType ), mPushInfo ( pinfo ) {
if ( pinfo.mType == "wp" ) {
createHTTPRequest ( "" );
}
}
void WindowsPhonePushNotificationRequest::createHTTPRequest ( const std::string &access_token ) {
const string &host = mPushInfo.mAppId;
char decodeUri[512] = {0};
bool is_message = mPushInfo.mEvent == PushInfo::Message;
const std::string &message = mPushInfo.mText;
const std::string &sender_name = mPushInfo.mFromName;
const std::string &sender_uri = mPushInfo.mFromUri;
ostringstream httpBody;
ostringstream httpHeader;
if ( mPushInfo.mType == "w10" ) {
string unescapedUrl;
unescapedUrl.resize ( mPushInfo.mDeviceToken.size() );
url_unescape ( &unescapedUrl[0], mPushInfo.mDeviceToken.c_str() );
base64_d ( decodeUri, sizeof ( decodeUri ), unescapedUrl.c_str() );
string query ( decodeUri );
if ( is_message ) {
// We have to send the content of the message and the name of the sender.
// We also need the sender address to be able to display the full chat view in case the receiver click the
// toast.
httpBody << "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
<< "<toast launch=\"" << "chat?sip=" << sender_uri << "\">"
<< "<visual>"
<< "<binding template =\"ToastGeneric\">"
<< "<text>" << sender_uri << "</text>"
<< "<text>" << message << "</text>"
<< "</binding>"
<< "</visual>"
<< "</toast>";
} else {
// No need to specify name or number, this PN will only wake up linphone.
httpBody << "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
<< "<toast launch=\"" << sender_uri << "\" >"
<< "<visual>"
<< "<binding template=\"ToastGeneric\" >"
<< "<text>Incoming Call</text>"
<< "<text>" << sender_uri << "</text>"
<< "</binding>"
<< "</visual>"
<< "</toast>";
}
httpHeader << "POST " << query << " HTTP/1.1\r\n"
<< "Authorization: Bearer " << access_token << "\r\n"
<< "X-WNS-RequestForStatus: true\r\n"
<< "X-WNS-Type: wns/toast\r\n"
<< "Content-Type: text/xml\r\n"
<< "Host: " << host << "\r\n"
<< "Content-Length: " << httpBody.str().size() << "\r\n\r\n";
} else if ( mPushInfo.mType == "wp" ) {
if ( is_message ) {
httpBody << "<?xml version=\"1.0\" encoding=\"utf-8\"?><wp:Notification "
"xmlns:wp=\"WPNotification\"><wp:Toast><wp:Text1>"
<< sender_name << "</wp:Text1><wp:Text2>" << message << "</wp:Text2><wp:Param>"
<< "/Views/Chat.xaml?sip=" << sender_uri << "</wp:Param></wp:Toast></wp:Notification>";
// Notification class 2 is the type for toast notifitcation.
httpHeader
<< "POST " << mPushInfo.mDeviceToken << " HTTP/1.1\r\nHost:" << host
<< "\r\nX-WindowsPhone-Target:toast\r\nX-NotificationClass:2\r\nContent-Type:text/xml\r\nContent-Length:"
<< httpBody.str().size() << "\r\n\r\n";
} else {
httpBody << "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
<< "<IncomingCall><Name></Name><Number></Number></IncomingCall>";
// Notification class 4 is the type for VoIP incoming call.
httpHeader << "POST " << mPushInfo.mDeviceToken << " HTTP/1.1\r\nHost:" << host
<< "\r\nX-NotificationClass:4\r\nContent-Type:text/xml\r\nContent-Length:" << httpBody.str().size()
<< "\r\n\r\n";
}
}
mHttpHeader = httpHeader.str();
mHttpBody = httpBody.str();
SLOGD << "PNR " << this << " POST header is " << mHttpHeader;
SLOGD << "PNR " << this << " POST body is " << mHttpBody;
}
void WindowsPhonePushNotificationRequest::createPushNotification() {
int headerLength = mHttpHeader.length();
int bodyLength = mHttpBody.length();
mBuffer.clear();
mBuffer.resize ( headerLength + bodyLength );
char *binaryMessageBuff = &mBuffer[0];
char *binaryMessagePt = binaryMessageBuff;
memcpy ( binaryMessagePt, &mHttpHeader[0], headerLength );
binaryMessagePt += headerLength;
memcpy ( binaryMessagePt, &mHttpBody[0], bodyLength );
binaryMessagePt += bodyLength;
}
const vector<char> &WindowsPhonePushNotificationRequest::getData() {
createPushNotification();
return mBuffer;
}
std::string WindowsPhonePushNotificationRequest::isValidResponse ( const string &str ) {
string line;
istringstream iss ( str );
bool valid = false, connect = false, notif = false;
while ( getline ( iss, line ) ) {
if ( mPushInfo.mType == "w10" ) {
valid |= ( line.find ( "HTTP/1.1 200 OK" ) != string::npos );
connect |= ( line.find ( "X-WNS-DEVICECONNECTIONSTATUS: connected" ) != string::npos );
notif |= ( line.find ( "X-WNS-STATUS: received" ) != string::npos );
} else {
connect |= ( line.find ( "X-DeviceConnectionStatus: connected" ) != string::npos );
notif |= ( line.find ( "X-NotificationStatus: Received" ) != string::npos );
valid |= ( line.find ( "X-SubscriptionStatus: Active" ) != string::npos );
}
auto it = line.find ( "X-WNS-ERROR-DESCRIPTION" );
if ( it != string::npos ) {
return line.substr ( line.find ( ' ' ) );
}
}
if ( !valid ) return "Unexpected HTTP response value (not 200 OK)";
if ( !connect ) return "Device connection status not set to connected";
if ( !notif ) return "Notification not received by server";
return "";
}
<|endoftext|> |
<commit_before>/*
* PrimeSieveGUI_menu.cpp -- This file is part of primesieve
*
* Copyright (C) 2012 Kim Walisch, <kim.walisch@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* 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, see <http://www.gnu.org/licenses/>
*/
#include "PrimeSieveGUI.h"
#include "ui_PrimeSieveGUI.h"
#include "../soe/ParallelPrimeSieve.h"
#include <QMessageBox>
#include <QDir>
#include <QFile>
#include <QTextStream>
#include <QFileDialog>
/**
* Initialize the menu items.
*/
void PrimeSieveGUI::createMenuActions(QVector<QString>& primeText) {
// file actions
saveAct_ = new QAction("&Save", this);
saveAct_->setShortcut(tr("Ctrl+S"));
quitAct_ = new QAction("&Quit", this);
quitAct_->setShortcut(tr("Ctrl+Q"));
// count actions
countAct_.push_back(new QAction(primeText[0], this));
countAct_.back()->setCheckable(true);
countAct_.push_back(new QAction("Prime k-tuplets", this));
countAct_.back()->setCheckable(true);
// default count prime numbers
countAct_.front()->setChecked(true);
// radio button like behaviour for print actions
alignmentGroup_ = new QActionGroup(this);
alignmentGroup_->setExclusive(false);
// print actions
for (int i = 0; i < primeText.size(); i++) {
printAct_.push_back(new QAction(primeText[i], this));
printAct_.back()->setCheckable(true);
alignmentGroup_->addAction(printAct_.back());
}
// about action
aboutAct_ = new QAction("About", this);
}
/**
* Create the menu bar with 'File', 'Count', 'Print' and 'Help'
* menu options.
*/
void PrimeSieveGUI::createMenu(QVector<QString>& primeText) {
this->createMenuActions(primeText);
fileMenu_ = menuBar()->addMenu("&File");
fileMenu_->addAction(saveAct_);
fileMenu_->addAction(quitAct_);
countMenu_ = menuBar()->addMenu("&Count");
for (int i = 0; i < countAct_.size(); i++)
countMenu_->addAction(countAct_[i]);
printMenu_ = menuBar()->addMenu("&Print");
for (int i = 0; i < printAct_.size(); i++)
printMenu_->addAction(printAct_[i]);
helpMenu_ = menuBar()->addMenu("&Help");
helpMenu_->addAction(aboutAct_);
}
/**
* Return the count and print menu settings as bit flags.
*/
int PrimeSieveGUI::getMenuSettings() {
int flags = 0;
// get count settings
if (countAct_[0]->isChecked())
flags |= COUNT_PRIMES;
if (countAct_[1]->isChecked())
flags |= COUNT_KTUPLETS;
// get print settings
for (int i = 0; i < printAct_.size(); i++)
if (printAct_[i]->isChecked())
flags |= PRINT_PRIMES << i;
return flags;
}
/**
* Disable the "Threads" ComboBox and the "Auto set" CheckBox and
* set to 1 Threads for printing (else invert).
*/
void PrimeSieveGUI::printMenuClicked(QAction* qAct) {
// disable other print options
for (int i = 0; i < printAct_.size(); i++) {
if (printAct_[i] != qAct)
printAct_[i]->setChecked(false);
}
ui->autoSetCheckBox->setDisabled(qAct->isChecked());
if (qAct->isChecked()) {
ui->autoSetCheckBox->setChecked(true);
ui->threadsComboBox->setCurrentIndex(0);
}
ui->threadsComboBox->setDisabled(qAct->isChecked());
this->autoSetThreads();
}
/**
* Save the content of the textEdit to a file.
*/
void PrimeSieveGUI::saveToFile() {
// Qt uses '/' internally, also for Windows
QString currentPath = QDir::currentPath() + "/Unsaved Document 1";
QString fileName = QFileDialog::getSaveFileName(this, "Save As...", currentPath, "All Files (*)");
QFile file(fileName);
if (file.open(QFile::WriteOnly | QFile::Text)) {
QTextStream textStream(&file);
textStream << ui->textEdit->toPlainText();
}
}
void PrimeSieveGUI::showAboutDialog() {
QString title = "About " + APPLICATION_NAME;
QString message = "<h2>" + APPLICATION_NAME + " " + PRIMESIEVE_VERSION + "</h2>"
+ "<p>Copyright © " + PRIMESIEVE_YEAR + " Kim Walisch</p>"
+ "<p>" + APPLICATION_ABOUT + "</p>"
+ "<a href=\"" + APPLICATION_HOMEPAGE + "\">" + APPLICATION_HOMEPAGE + "</a>";
QMessageBox::about(this, title, message);
}
<commit_msg>fixed typing error<commit_after>/*
* PrimeSieveGUI_menu.cpp -- This file is part of primesieve
*
* Copyright (C) 2012 Kim Walisch, <kim.walisch@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* 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, see <http://www.gnu.org/licenses/>
*/
#include "PrimeSieveGUI.h"
#include "ui_PrimeSieveGUI.h"
#include "../soe/ParallelPrimeSieve.h"
#include <QMessageBox>
#include <QDir>
#include <QFile>
#include <QTextStream>
#include <QFileDialog>
/**
* Initialize the menu items.
*/
void PrimeSieveGUI::createMenuActions(QVector<QString>& primeText) {
// file actions
saveAct_ = new QAction("&Save", this);
saveAct_->setShortcut(tr("Ctrl+S"));
quitAct_ = new QAction("&Quit", this);
quitAct_->setShortcut(tr("Ctrl+Q"));
// count actions
countAct_.push_back(new QAction(primeText[0], this));
countAct_.back()->setCheckable(true);
countAct_.push_back(new QAction("Prime k-tuplets", this));
countAct_.back()->setCheckable(true);
// default count prime numbers
countAct_.front()->setChecked(true);
// radio button like behaviour for print actions
alignmentGroup_ = new QActionGroup(this);
alignmentGroup_->setExclusive(false);
// print actions
for (int i = 0; i < primeText.size(); i++) {
printAct_.push_back(new QAction(primeText[i], this));
printAct_.back()->setCheckable(true);
alignmentGroup_->addAction(printAct_.back());
}
// about action
aboutAct_ = new QAction("About", this);
}
/**
* Create the menu bar with 'File', 'Count', 'Print' and 'Help'
* menu options.
*/
void PrimeSieveGUI::createMenu(QVector<QString>& primeText) {
this->createMenuActions(primeText);
fileMenu_ = menuBar()->addMenu("&File");
fileMenu_->addAction(saveAct_);
fileMenu_->addAction(quitAct_);
countMenu_ = menuBar()->addMenu("&Count");
for (int i = 0; i < countAct_.size(); i++)
countMenu_->addAction(countAct_[i]);
printMenu_ = menuBar()->addMenu("&Print");
for (int i = 0; i < printAct_.size(); i++)
printMenu_->addAction(printAct_[i]);
helpMenu_ = menuBar()->addMenu("&Help");
helpMenu_->addAction(aboutAct_);
}
/**
* Return the count and print menu settings as bit flags.
*/
int PrimeSieveGUI::getMenuSettings() {
int flags = 0;
// get count settings
if (countAct_[0]->isChecked())
flags |= COUNT_PRIMES;
if (countAct_[1]->isChecked())
flags |= COUNT_KTUPLETS;
// get print settings
for (int i = 0; i < printAct_.size(); i++)
if (printAct_[i]->isChecked())
flags |= PRINT_PRIMES << i;
return flags;
}
/**
* Disable the "Threads" ComboBox and the "Auto set" CheckBox and
* set to 1 Threads for printing (else invert).
*/
void PrimeSieveGUI::printMenuClicked(QAction* qAct) {
// disable other print options
for (int i = 0; i < printAct_.size(); i++) {
if (printAct_[i] != qAct)
printAct_[i]->setChecked(false);
}
ui->autoSetCheckBox->setDisabled(qAct->isChecked());
if (qAct->isChecked()) {
ui->autoSetCheckBox->setChecked(true);
ui->threadsComboBox->setCurrentIndex(0);
}
ui->threadsComboBox->setDisabled(qAct->isChecked());
this->autoSetThreads();
}
/**
* Save the content of the textEdit to a file.
*/
void PrimeSieveGUI::saveToFile() {
// Qt uses '/' internally, also for Windows
QString currentPath = QDir::currentPath() + "/Unsaved Document 1";
QString fileName = QFileDialog::getSaveFileName(this, "Save As...", currentPath, "All Files (*)");
QFile file(fileName);
if (file.open(QFile::WriteOnly | QFile::Text)) {
QTextStream textStream(&file);
textStream << ui->textEdit->toPlainText();
}
}
void PrimeSieveGUI::showAboutDialog() {
QString year = QString::number(PRIMESIEVE_YEAR);
QString title = "About " + APPLICATION_NAME;
QString message = "<h2>" + APPLICATION_NAME + " " + PRIMESIEVE_VERSION + "</h2>"
+ "<p>Copyright © " + year + " Kim Walisch</p>"
+ "<p>" + APPLICATION_ABOUT + "</p>"
+ "<a href=\"" + APPLICATION_HOMEPAGE + "\">" + APPLICATION_HOMEPAGE + "</a>";
QMessageBox::about(this, title, message);
}
<|endoftext|> |
<commit_before>#include "offerwhitelisttablemodel.h"
#include "guiutil.h"
#include "walletmodel.h"
#include "wallet/wallet.h"
#include "base58.h"
#include <QFont>
using namespace std;
struct MyOfferWhitelistTableEntry
{
QString offer;
QString alias;
QString expires;
QString discount;
MyOfferWhitelistTableEntry() {}
MyOfferWhitelistTableEntry(const QString &offer, const QString &alias, const QString &expires,const QString &discount):
offer(offer), alias(alias), expires(expires),discount(discount) {}
};
// Private implementation
class MyOfferWhitelistTablePriv
{
public:
QList<MyOfferWhitelistTableEntry> cachedEntryTable;
MyOfferWhitelistTableModel *parent;
OfferWhitelistTablePriv(MyOfferWhitelistTableModel *parent):
parent(parent) {}
void updateEntry(const QString &offer, const QString &alias, const QString &expires,const QString &discount, int status)
{
if(!parent)
{
return;
}
switch(status)
{
case CT_NEW:
parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex);
cachedEntryTable.insert(lowerIndex, MyOfferWhitelistTableEntry(offer, alias, expires, discount));
parent->endInsertRows();
break;
case CT_UPDATED:
lower->offer = offer;
lower->alias = alias;
lower->expires = expires;
lower->discount = discount;
parent->emitDataChanged(lowerIndex);
break;
case CT_DELETED:
parent->beginRemoveRows(QModelIndex(), lowerIndex, upperIndex-1);
cachedEntryTable.erase(lower, upper);
parent->endRemoveRows();
break;
}
}
int size()
{
return cachedEntryTable.size();
}
OfferWhitelistTableEntry *index(int idx)
{
if(idx >= 0 && idx < cachedEntryTable.size())
{
return &cachedEntryTable[idx];
}
else
{
return 0;
}
}
};
MyOfferWhitelistTableModel::MyOfferWhitelistTableModel(WalletModel *parent) :
QAbstractTableModel(parent)
{
columns << tr("Offer") << tr("Alias") << tr("Discount") << tr("Expires In");
priv = new OfferWhitelistTablePriv(this);
}
MyOfferWhitelistTableModel::~MyOfferWhitelistTableModel()
{
delete priv;
}
int MyOfferWhitelistTableModel::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return priv->size();
}
int MyOfferWhitelistTableModel::columnCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return columns.length();
}
QVariant MyOfferWhitelistTableModel::data(const QModelIndex &index, int role) const
{
if(!index.isValid())
return QVariant();
OfferWhitelistTableEntry *rec = static_cast<OfferWhitelistTableEntry*>(index.internalPointer());
if(role == Qt::DisplayRole || role == Qt::EditRole)
{
switch(index.column())
{
case Offer:
return rec->offer;
case Alias:
return rec->alias;
case Discount:
return rec->discount;
case Expires:
return rec->expires;
}
}
else if (role == AliasRole)
{
return rec->alias;
}
return QVariant();
}
bool MyOfferWhitelistTableModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
if(!index.isValid())
return false;
OfferWhitelistTableEntry *rec = static_cast<OfferWhitelistTableEntry*>(index.internalPointer());
editStatus = OK;
if(role == Qt::EditRole)
{
switch(index.column())
{
case Offer:
// Do nothing, if old value == new value
if(rec->offer == value.toString())
{
editStatus = NO_CHANGES;
return false;
}
break;
case Alias:
// Do nothing, if old value == new value
if(rec->alias == value.toString())
{
editStatus = NO_CHANGES;
return false;
}
break;
case Discount:
// Do nothing, if old value == new value
if(rec->discount == value.toString())
{
editStatus = NO_CHANGES;
return false;
}
break;
case Expires:
// Do nothing, if old value == new value
if(rec->expires == value.toString())
{
editStatus = NO_CHANGES;
return false;
}
break;
return true;
}
}
return false;
}
QVariant MyOfferWhitelistTableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if(orientation == Qt::Horizontal)
{
if(role == Qt::DisplayRole)
{
return columns[section];
}
}
return QVariant();
}
Qt::ItemFlags MyOfferWhitelistTableModel::flags(const QModelIndex &index) const
{
if(!index.isValid())
return 0;
Qt::ItemFlags retval = Qt::ItemIsSelectable | Qt::ItemIsEnabled;
return retval;
}
QModelIndex MyOfferWhitelistTableModel::index(int row, int column, const QModelIndex &parent) const
{
Q_UNUSED(parent);
OfferWhitelistTableEntry *data = priv->index(row);
if(data)
{
return createIndex(row, column, priv->index(row));
}
else
{
return QModelIndex();
}
}
void MyOfferWhitelistTableModel::updateEntry(const QString &offer, const QString &alias, const QString &expires,const QString &discount, int status)
{
priv->updateEntry(offer, alias, expires, discount, status);
}
QString MyOfferWhitelistTableModel::addRow(const QString &offer, const QString &alias, const QString &expires,const QString &discount)
{
std::string strAlias = alias.toStdString();
editStatus = OK;
return QString::fromStdString(strAlias);
}
void MyOfferWhitelistTableModel::clear()
{
beginResetModel();
priv->cachedEntryTable.clear();
endResetModel();
}
void MyOfferWhitelistTableModel::emitDataChanged(int idx)
{
Q_EMIT dataChanged(index(idx, 0, QModelIndex()), index(idx, columns.length()-1, QModelIndex()));
}
<commit_msg>typo<commit_after>#include "myofferwhitelisttablemodel.h"
#include "guiutil.h"
#include "walletmodel.h"
#include "wallet/wallet.h"
#include "base58.h"
#include <QFont>
using namespace std;
struct MyOfferWhitelistTableEntry
{
QString offer;
QString alias;
QString expires;
QString discount;
MyOfferWhitelistTableEntry() {}
MyOfferWhitelistTableEntry(const QString &offer, const QString &alias, const QString &expires,const QString &discount):
offer(offer), alias(alias), expires(expires),discount(discount) {}
};
// Private implementation
class MyOfferWhitelistTablePriv
{
public:
QList<MyOfferWhitelistTableEntry> cachedEntryTable;
MyOfferWhitelistTableModel *parent;
OfferWhitelistTablePriv(MyOfferWhitelistTableModel *parent):
parent(parent) {}
void updateEntry(const QString &offer, const QString &alias, const QString &expires,const QString &discount, int status)
{
if(!parent)
{
return;
}
switch(status)
{
case CT_NEW:
parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex);
cachedEntryTable.insert(lowerIndex, MyOfferWhitelistTableEntry(offer, alias, expires, discount));
parent->endInsertRows();
break;
case CT_UPDATED:
lower->offer = offer;
lower->alias = alias;
lower->expires = expires;
lower->discount = discount;
parent->emitDataChanged(lowerIndex);
break;
case CT_DELETED:
parent->beginRemoveRows(QModelIndex(), lowerIndex, upperIndex-1);
cachedEntryTable.erase(lower, upper);
parent->endRemoveRows();
break;
}
}
int size()
{
return cachedEntryTable.size();
}
OfferWhitelistTableEntry *index(int idx)
{
if(idx >= 0 && idx < cachedEntryTable.size())
{
return &cachedEntryTable[idx];
}
else
{
return 0;
}
}
};
MyOfferWhitelistTableModel::MyOfferWhitelistTableModel(WalletModel *parent) :
QAbstractTableModel(parent)
{
columns << tr("Offer") << tr("Alias") << tr("Discount") << tr("Expires In");
priv = new OfferWhitelistTablePriv(this);
}
MyOfferWhitelistTableModel::~MyOfferWhitelistTableModel()
{
delete priv;
}
int MyOfferWhitelistTableModel::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return priv->size();
}
int MyOfferWhitelistTableModel::columnCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return columns.length();
}
QVariant MyOfferWhitelistTableModel::data(const QModelIndex &index, int role) const
{
if(!index.isValid())
return QVariant();
OfferWhitelistTableEntry *rec = static_cast<OfferWhitelistTableEntry*>(index.internalPointer());
if(role == Qt::DisplayRole || role == Qt::EditRole)
{
switch(index.column())
{
case Offer:
return rec->offer;
case Alias:
return rec->alias;
case Discount:
return rec->discount;
case Expires:
return rec->expires;
}
}
else if (role == AliasRole)
{
return rec->alias;
}
return QVariant();
}
bool MyOfferWhitelistTableModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
if(!index.isValid())
return false;
OfferWhitelistTableEntry *rec = static_cast<OfferWhitelistTableEntry*>(index.internalPointer());
editStatus = OK;
if(role == Qt::EditRole)
{
switch(index.column())
{
case Offer:
// Do nothing, if old value == new value
if(rec->offer == value.toString())
{
editStatus = NO_CHANGES;
return false;
}
break;
case Alias:
// Do nothing, if old value == new value
if(rec->alias == value.toString())
{
editStatus = NO_CHANGES;
return false;
}
break;
case Discount:
// Do nothing, if old value == new value
if(rec->discount == value.toString())
{
editStatus = NO_CHANGES;
return false;
}
break;
case Expires:
// Do nothing, if old value == new value
if(rec->expires == value.toString())
{
editStatus = NO_CHANGES;
return false;
}
break;
return true;
}
}
return false;
}
QVariant MyOfferWhitelistTableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if(orientation == Qt::Horizontal)
{
if(role == Qt::DisplayRole)
{
return columns[section];
}
}
return QVariant();
}
Qt::ItemFlags MyOfferWhitelistTableModel::flags(const QModelIndex &index) const
{
if(!index.isValid())
return 0;
Qt::ItemFlags retval = Qt::ItemIsSelectable | Qt::ItemIsEnabled;
return retval;
}
QModelIndex MyOfferWhitelistTableModel::index(int row, int column, const QModelIndex &parent) const
{
Q_UNUSED(parent);
OfferWhitelistTableEntry *data = priv->index(row);
if(data)
{
return createIndex(row, column, priv->index(row));
}
else
{
return QModelIndex();
}
}
void MyOfferWhitelistTableModel::updateEntry(const QString &offer, const QString &alias, const QString &expires,const QString &discount, int status)
{
priv->updateEntry(offer, alias, expires, discount, status);
}
QString MyOfferWhitelistTableModel::addRow(const QString &offer, const QString &alias, const QString &expires,const QString &discount)
{
std::string strAlias = alias.toStdString();
editStatus = OK;
return QString::fromStdString(strAlias);
}
void MyOfferWhitelistTableModel::clear()
{
beginResetModel();
priv->cachedEntryTable.clear();
endResetModel();
}
void MyOfferWhitelistTableModel::emitDataChanged(int idx)
{
Q_EMIT dataChanged(index(idx, 0, QModelIndex()), index(idx, columns.length()-1, QModelIndex()));
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2014 Jolla Ltd.
** Contact: Raine Makelainen <raine.makelainen@jollamobile.com>
**
****************************************************************************/
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "declarativewebpage.h"
#include "declarativewebcontainer.h"
#include "dbmanager.h"
#include <QtConcurrent>
#include <QStandardPaths>
static const QString gFullScreenMessage("embed:fullscreenchanged");
static const QString gDomContentLoadedMessage("embed:domcontentloaded");
static const QString gLinkAddedMessage("chrome:linkadded");
static const QString gAlertMessage("embed:alert");
static const QString gConfirmMessage("embed:confirm");
static const QString gPromptMessage("embed:prompt");
static const QString gAuthMessage("embed:auth");
static const QString gLoginMessage("embed:login");
static const QString gFindMessage("embed:find");
static const QString gPermissionsMessage("embed:permissions");
static const QString gContextMenuMessage("Content:ContextMenu");
static const QString gSelectionRangeMessage("Content:SelectionRange");
static const QString gSelectionCopiedMessage("Content:SelectionCopied");
static const QString gSelectAsyncMessage("embed:selectasync");
static const QString gFilePickerMessage("embed:filepicker");
bool isBlack(QRgb rgb)
{
return qRed(rgb) == 0 && qGreen(rgb) == 0 && qBlue(rgb) == 0;
}
bool allBlack(const QImage &image)
{
int h = image.height();
int w = image.width();
for (int j = 0; j < h; ++j) {
const QRgb *b = (const QRgb *)image.constScanLine(j);
for (int i = 0; i < w; ++i) {
if (!isBlack(b[i]))
return false;
}
}
return true;
}
DeclarativeWebPage::DeclarativeWebPage(QObject *parent)
: QOpenGLWebPage(parent)
, m_container(0)
, m_userHasDraggedWhileLoading(false)
, m_fullscreen(false)
, m_forcedChrome(false)
, m_domContentLoaded(false)
, m_initialLoadHasHappened(false)
, m_tabHistoryReady(false)
, m_urlReady(false)
{
addMessageListener(gFullScreenMessage);
addMessageListener(gDomContentLoadedMessage);
addMessageListener(gLinkAddedMessage);
addMessageListener(gAlertMessage);
addMessageListener(gConfirmMessage);
addMessageListener(gPromptMessage);
addMessageListener(gAuthMessage);
addMessageListener(gLoginMessage);
addMessageListener(gFindMessage);
addMessageListener(gPermissionsMessage);
addMessageListener(gContextMenuMessage);
addMessageListener(gSelectionRangeMessage);
addMessageListener(gSelectionCopiedMessage);
addMessageListener(gSelectAsyncMessage);
addMessageListener(gFilePickerMessage);
loadFrameScript("chrome://embedlite/content/SelectAsyncHelper.js");
loadFrameScript("chrome://embedlite/content/embedhelper.js");
connect(this, SIGNAL(recvAsyncMessage(const QString, const QVariant)),
this, SLOT(onRecvAsyncMessage(const QString&, const QVariant&)));
connect(&m_grabWritter, SIGNAL(finished()), this, SLOT(grabWritten()));
connect(this, SIGNAL(contentHeightChanged()), this, SLOT(resetHeight()));
connect(this, SIGNAL(scrollableOffsetChanged()), this, SLOT(resetHeight()));
connect(this, SIGNAL(urlChanged()), this, SLOT(onUrlChanged()));
}
DeclarativeWebPage::~DeclarativeWebPage()
{
m_grabWritter.cancel();
m_grabWritter.waitForFinished();
m_grabResult.clear();
m_thumbnailResult.clear();
}
DeclarativeWebContainer *DeclarativeWebPage::container() const
{
return m_container;
}
void DeclarativeWebPage::setContainer(DeclarativeWebContainer *container)
{
if (m_container != container) {
m_container = container;
emit containerChanged();
}
}
int DeclarativeWebPage::tabId() const
{
return m_initialTab.tabId();
}
void DeclarativeWebPage::setInitialTab(const Tab& tab)
{
Q_ASSERT(m_initialTab.tabId() == 0);
m_initialTab = tab;
emit tabIdChanged();
connect(DBManager::instance(), SIGNAL(tabHistoryAvailable(int, QList<Link>)),
this, SLOT(onTabHistoryAvailable(int, QList<Link>)));
DBManager::instance()->getTabHistory(tabId());
}
void DeclarativeWebPage::onUrlChanged()
{
disconnect(this, SIGNAL(urlChanged()), this, SLOT(onUrlChanged()));
m_urlReady = true;
restoreHistory();
}
void DeclarativeWebPage::onTabHistoryAvailable(const int& historyTabId, const QList<Link>& links)
{
if (historyTabId == tabId()) {
m_restoredTabHistory = links;
std::reverse(m_restoredTabHistory.begin(), m_restoredTabHistory.end());
DBManager::instance()->disconnect(this);
m_tabHistoryReady = true;
restoreHistory();
}
}
void DeclarativeWebPage::restoreHistory() {
if (!m_urlReady || !m_tabHistoryReady || m_restoredTabHistory.count() == 0) {
return;
}
QList<QString> urls;
int index(-1);
int i(0);
foreach (Link link, m_restoredTabHistory) {
urls << link.url();
if (link.linkId() == m_initialTab.currentLink()) {
index = i;
if (link.url() != m_initialTab.url()) {
// The browser was started with an initial URL as a cmdline parameter -> reset tab history
urls << m_initialTab.url();
index++;
DBManager::instance()->navigateTo(tabId(), m_initialTab.url(), "", "");
break;
}
}
i++;
}
if (index < 0) {
urls << url().toString();
index = urls.count() - 1;
}
QVariantMap data;
data.insert(QString("links"), QVariant(urls));
data.insert(QString("index"), QVariant(index));
sendAsyncMessage("embedui:addhistory", QVariant(data));
}
bool DeclarativeWebPage::domContentLoaded() const
{
return m_domContentLoaded;
}
bool DeclarativeWebPage::initialLoadHasHappened() const
{
return m_initialLoadHasHappened;
}
void DeclarativeWebPage::setInitialLoadHasHappened()
{
m_initialLoadHasHappened = true;
}
QVariant DeclarativeWebPage::resurrectedContentRect() const
{
return m_resurrectedContentRect;
}
void DeclarativeWebPage::setResurrectedContentRect(QVariant resurrectedContentRect)
{
if (m_resurrectedContentRect != resurrectedContentRect) {
m_resurrectedContentRect = resurrectedContentRect;
emit resurrectedContentRectChanged();
}
}
void DeclarativeWebPage::loadTab(QString newUrl, bool force)
{
// Always enable chrome when load is called.
setChrome(true);
QString oldUrl = url().toString();
if ((!newUrl.isEmpty() && oldUrl != newUrl) || force) {
m_domContentLoaded = false;
emit domContentLoadedChanged();
load(newUrl);
}
}
void DeclarativeWebPage::grabToFile(const QSize &size)
{
emit clearGrabResult();
// grabToImage handles invalid geometry.
m_grabResult = grabToImage(size);
if (m_grabResult) {
if (!m_grabResult->isReady()) {
connect(m_grabResult.data(), SIGNAL(ready()), this, SLOT(grabResultReady()));
} else {
grabResultReady();
}
}
}
void DeclarativeWebPage::grabThumbnail(const QSize &size)
{
m_thumbnailResult = grabToImage(size);
if (m_thumbnailResult) {
connect(m_thumbnailResult.data(), SIGNAL(ready()), this, SLOT(thumbnailReady()));
}
}
/**
* Use this to lock to chrome mode. This disables the gesture
* that normally enables fullscreen mode. The chromeGestureEnabled property
* is bound to this so that contentHeight changes do not re-enable the
* gesture.
*
* When gesture is allowed to be used again, unlock call by forceChrome(false).
*
* Used for instance when find-in-page view is active that is part of
* the new browser user interface.
*/
void DeclarativeWebPage::forceChrome(bool forcedChrome)
{
// This way we don't break chromeGestureEnabled and chrome bindings.
setChromeGestureEnabled(!forcedChrome);
if (forcedChrome) {
setChrome(forcedChrome);
}
// Without chrome respect content height.
resetHeight(!forcedChrome);
if (m_forcedChrome != forcedChrome) {
m_forcedChrome = forcedChrome;
emit forcedChromeChanged();
}
}
void DeclarativeWebPage::resetHeight(bool respectContentHeight)
{
// Input panel is fully open.
if (m_container->imOpened()) {
return;
}
// fullscreen() below in the fullscreen request coming from the web content.
if (respectContentHeight && (!m_forcedChrome || fullscreen())) {
// Handle webPage height over here, BrowserPage.qml loading
// reset might be redundant as we have also loaded trigger
// reset. However, I'd leave it there for safety reasons.
// We need to reset height always back to short height when loading starts
// so that after tab change there is always initial short composited height.
// Height may expand when content is moved.
if (contentHeight() > (m_fullScreenHeight + m_toolbarHeight) || fullscreen()) {
setHeight(m_fullScreenHeight);
} else {
setHeight(m_fullScreenHeight - m_toolbarHeight);
}
} else {
setHeight(m_fullScreenHeight - m_toolbarHeight);
}
}
void DeclarativeWebPage::grabResultReady()
{
QImage image = m_grabResult->image();
m_grabResult.clear();
m_grabWritter.setFuture(QtConcurrent::run(this, &DeclarativeWebPage::saveToFile, image));
}
void DeclarativeWebPage::grabWritten()
{
QString path = m_grabWritter.result();
emit grabResult(path);
}
void DeclarativeWebPage::thumbnailReady()
{
QImage image = m_thumbnailResult->image();
m_thumbnailResult.clear();
QByteArray iconData;
QBuffer buffer(&iconData);
buffer.open(QIODevice::WriteOnly);
if (image.save(&buffer, "jpg", 75)) {
buffer.close();
emit thumbnailResult(QString(BASE64_IMAGE).arg(QString(iconData.toBase64())));
} else {
emit thumbnailResult(DEFAULT_DESKTOP_BOOKMARK_ICON);
}
}
QString DeclarativeWebPage::saveToFile(QImage image)
{
if (image.isNull()) {
return "";
}
// 75% quality jpg produces small and good enough capture.
QString path = QString("%1/tab-%2-thumb.jpg").arg(QStandardPaths::writableLocation(QStandardPaths::CacheLocation)).arg(tabId());
return !allBlack(image) && image.save(path, "jpg", 75) ? path : "";
}
void DeclarativeWebPage::onRecvAsyncMessage(const QString& message, const QVariant& data)
{
if (message == gFullScreenMessage) {
setFullscreen(data.toMap().value(QString("fullscreen")).toBool());
} else if (message == gDomContentLoadedMessage && data.toMap().value("rootFrame").toBool()) {
m_domContentLoaded = true;
emit domContentLoadedChanged();
}
}
bool DeclarativeWebPage::fullscreen() const
{
return m_fullscreen;
}
bool DeclarativeWebPage::forcedChrome() const
{
return m_forcedChrome;
}
void DeclarativeWebPage::setFullscreen(const bool fullscreen)
{
if (m_fullscreen != fullscreen) {
m_fullscreen = fullscreen;
resetHeight();
emit fullscreenChanged();
}
}
QDebug operator<<(QDebug dbg, const DeclarativeWebPage *page)
{
if (!page) {
return dbg << "DeclarativeWebPage (this = 0x0)";
}
dbg.nospace() << "DeclarativeWebPage(url = " << page->url() << ", title = " << page->title() << ", width = " << page->width()
<< ", height = " << page->height() << ", completed = " << page->completed()
<< ", active = " << page->active() << ", enabled = " << page->enabled() << ")";
return dbg.space();
}
<commit_msg>[history] Use actual current URL when modifying session history.<commit_after>/****************************************************************************
**
** Copyright (C) 2014 Jolla Ltd.
** Contact: Raine Makelainen <raine.makelainen@jollamobile.com>
**
****************************************************************************/
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "declarativewebpage.h"
#include "declarativewebcontainer.h"
#include "dbmanager.h"
#include <QtConcurrent>
#include <QStandardPaths>
static const QString gFullScreenMessage("embed:fullscreenchanged");
static const QString gDomContentLoadedMessage("embed:domcontentloaded");
static const QString gLinkAddedMessage("chrome:linkadded");
static const QString gAlertMessage("embed:alert");
static const QString gConfirmMessage("embed:confirm");
static const QString gPromptMessage("embed:prompt");
static const QString gAuthMessage("embed:auth");
static const QString gLoginMessage("embed:login");
static const QString gFindMessage("embed:find");
static const QString gPermissionsMessage("embed:permissions");
static const QString gContextMenuMessage("Content:ContextMenu");
static const QString gSelectionRangeMessage("Content:SelectionRange");
static const QString gSelectionCopiedMessage("Content:SelectionCopied");
static const QString gSelectAsyncMessage("embed:selectasync");
static const QString gFilePickerMessage("embed:filepicker");
bool isBlack(QRgb rgb)
{
return qRed(rgb) == 0 && qGreen(rgb) == 0 && qBlue(rgb) == 0;
}
bool allBlack(const QImage &image)
{
int h = image.height();
int w = image.width();
for (int j = 0; j < h; ++j) {
const QRgb *b = (const QRgb *)image.constScanLine(j);
for (int i = 0; i < w; ++i) {
if (!isBlack(b[i]))
return false;
}
}
return true;
}
DeclarativeWebPage::DeclarativeWebPage(QObject *parent)
: QOpenGLWebPage(parent)
, m_container(0)
, m_userHasDraggedWhileLoading(false)
, m_fullscreen(false)
, m_forcedChrome(false)
, m_domContentLoaded(false)
, m_initialLoadHasHappened(false)
, m_tabHistoryReady(false)
, m_urlReady(false)
{
addMessageListener(gFullScreenMessage);
addMessageListener(gDomContentLoadedMessage);
addMessageListener(gLinkAddedMessage);
addMessageListener(gAlertMessage);
addMessageListener(gConfirmMessage);
addMessageListener(gPromptMessage);
addMessageListener(gAuthMessage);
addMessageListener(gLoginMessage);
addMessageListener(gFindMessage);
addMessageListener(gPermissionsMessage);
addMessageListener(gContextMenuMessage);
addMessageListener(gSelectionRangeMessage);
addMessageListener(gSelectionCopiedMessage);
addMessageListener(gSelectAsyncMessage);
addMessageListener(gFilePickerMessage);
loadFrameScript("chrome://embedlite/content/SelectAsyncHelper.js");
loadFrameScript("chrome://embedlite/content/embedhelper.js");
connect(this, SIGNAL(recvAsyncMessage(const QString, const QVariant)),
this, SLOT(onRecvAsyncMessage(const QString&, const QVariant&)));
connect(&m_grabWritter, SIGNAL(finished()), this, SLOT(grabWritten()));
connect(this, SIGNAL(contentHeightChanged()), this, SLOT(resetHeight()));
connect(this, SIGNAL(scrollableOffsetChanged()), this, SLOT(resetHeight()));
connect(this, SIGNAL(urlChanged()), this, SLOT(onUrlChanged()));
}
DeclarativeWebPage::~DeclarativeWebPage()
{
m_grabWritter.cancel();
m_grabWritter.waitForFinished();
m_grabResult.clear();
m_thumbnailResult.clear();
}
DeclarativeWebContainer *DeclarativeWebPage::container() const
{
return m_container;
}
void DeclarativeWebPage::setContainer(DeclarativeWebContainer *container)
{
if (m_container != container) {
m_container = container;
emit containerChanged();
}
}
int DeclarativeWebPage::tabId() const
{
return m_initialTab.tabId();
}
void DeclarativeWebPage::setInitialTab(const Tab& tab)
{
Q_ASSERT(m_initialTab.tabId() == 0);
m_initialTab = tab;
emit tabIdChanged();
connect(DBManager::instance(), SIGNAL(tabHistoryAvailable(int, QList<Link>)),
this, SLOT(onTabHistoryAvailable(int, QList<Link>)));
DBManager::instance()->getTabHistory(tabId());
}
void DeclarativeWebPage::onUrlChanged()
{
disconnect(this, SIGNAL(urlChanged()), this, SLOT(onUrlChanged()));
m_urlReady = true;
restoreHistory();
}
void DeclarativeWebPage::onTabHistoryAvailable(const int& historyTabId, const QList<Link>& links)
{
if (historyTabId == tabId()) {
m_restoredTabHistory = links;
std::reverse(m_restoredTabHistory.begin(), m_restoredTabHistory.end());
DBManager::instance()->disconnect(this);
m_tabHistoryReady = true;
restoreHistory();
}
}
void DeclarativeWebPage::restoreHistory() {
if (!m_urlReady || !m_tabHistoryReady || m_restoredTabHistory.count() == 0) {
return;
}
QList<QString> urls;
int index(-1);
int i(0);
foreach (Link link, m_restoredTabHistory) {
urls << link.url();
if (link.linkId() == m_initialTab.currentLink()) {
index = i;
QString currentUrl(url().toString());
if (link.url() != currentUrl) {
// The browser was started with an initial URL as a cmdline parameter -> reset tab history
urls << currentUrl;
index++;
DBManager::instance()->navigateTo(tabId(), currentUrl, "", "");
break;
}
}
i++;
}
if (index < 0) {
urls << url().toString();
index = urls.count() - 1;
}
QVariantMap data;
data.insert(QString("links"), QVariant(urls));
data.insert(QString("index"), QVariant(index));
sendAsyncMessage("embedui:addhistory", QVariant(data));
}
bool DeclarativeWebPage::domContentLoaded() const
{
return m_domContentLoaded;
}
bool DeclarativeWebPage::initialLoadHasHappened() const
{
return m_initialLoadHasHappened;
}
void DeclarativeWebPage::setInitialLoadHasHappened()
{
m_initialLoadHasHappened = true;
}
QVariant DeclarativeWebPage::resurrectedContentRect() const
{
return m_resurrectedContentRect;
}
void DeclarativeWebPage::setResurrectedContentRect(QVariant resurrectedContentRect)
{
if (m_resurrectedContentRect != resurrectedContentRect) {
m_resurrectedContentRect = resurrectedContentRect;
emit resurrectedContentRectChanged();
}
}
void DeclarativeWebPage::loadTab(QString newUrl, bool force)
{
// Always enable chrome when load is called.
setChrome(true);
QString oldUrl = url().toString();
if ((!newUrl.isEmpty() && oldUrl != newUrl) || force) {
m_domContentLoaded = false;
emit domContentLoadedChanged();
load(newUrl);
}
}
void DeclarativeWebPage::grabToFile(const QSize &size)
{
emit clearGrabResult();
// grabToImage handles invalid geometry.
m_grabResult = grabToImage(size);
if (m_grabResult) {
if (!m_grabResult->isReady()) {
connect(m_grabResult.data(), SIGNAL(ready()), this, SLOT(grabResultReady()));
} else {
grabResultReady();
}
}
}
void DeclarativeWebPage::grabThumbnail(const QSize &size)
{
m_thumbnailResult = grabToImage(size);
if (m_thumbnailResult) {
connect(m_thumbnailResult.data(), SIGNAL(ready()), this, SLOT(thumbnailReady()));
}
}
/**
* Use this to lock to chrome mode. This disables the gesture
* that normally enables fullscreen mode. The chromeGestureEnabled property
* is bound to this so that contentHeight changes do not re-enable the
* gesture.
*
* When gesture is allowed to be used again, unlock call by forceChrome(false).
*
* Used for instance when find-in-page view is active that is part of
* the new browser user interface.
*/
void DeclarativeWebPage::forceChrome(bool forcedChrome)
{
// This way we don't break chromeGestureEnabled and chrome bindings.
setChromeGestureEnabled(!forcedChrome);
if (forcedChrome) {
setChrome(forcedChrome);
}
// Without chrome respect content height.
resetHeight(!forcedChrome);
if (m_forcedChrome != forcedChrome) {
m_forcedChrome = forcedChrome;
emit forcedChromeChanged();
}
}
void DeclarativeWebPage::resetHeight(bool respectContentHeight)
{
// Input panel is fully open.
if (m_container->imOpened()) {
return;
}
// fullscreen() below in the fullscreen request coming from the web content.
if (respectContentHeight && (!m_forcedChrome || fullscreen())) {
// Handle webPage height over here, BrowserPage.qml loading
// reset might be redundant as we have also loaded trigger
// reset. However, I'd leave it there for safety reasons.
// We need to reset height always back to short height when loading starts
// so that after tab change there is always initial short composited height.
// Height may expand when content is moved.
if (contentHeight() > (m_fullScreenHeight + m_toolbarHeight) || fullscreen()) {
setHeight(m_fullScreenHeight);
} else {
setHeight(m_fullScreenHeight - m_toolbarHeight);
}
} else {
setHeight(m_fullScreenHeight - m_toolbarHeight);
}
}
void DeclarativeWebPage::grabResultReady()
{
QImage image = m_grabResult->image();
m_grabResult.clear();
m_grabWritter.setFuture(QtConcurrent::run(this, &DeclarativeWebPage::saveToFile, image));
}
void DeclarativeWebPage::grabWritten()
{
QString path = m_grabWritter.result();
emit grabResult(path);
}
void DeclarativeWebPage::thumbnailReady()
{
QImage image = m_thumbnailResult->image();
m_thumbnailResult.clear();
QByteArray iconData;
QBuffer buffer(&iconData);
buffer.open(QIODevice::WriteOnly);
if (image.save(&buffer, "jpg", 75)) {
buffer.close();
emit thumbnailResult(QString(BASE64_IMAGE).arg(QString(iconData.toBase64())));
} else {
emit thumbnailResult(DEFAULT_DESKTOP_BOOKMARK_ICON);
}
}
QString DeclarativeWebPage::saveToFile(QImage image)
{
if (image.isNull()) {
return "";
}
// 75% quality jpg produces small and good enough capture.
QString path = QString("%1/tab-%2-thumb.jpg").arg(QStandardPaths::writableLocation(QStandardPaths::CacheLocation)).arg(tabId());
return !allBlack(image) && image.save(path, "jpg", 75) ? path : "";
}
void DeclarativeWebPage::onRecvAsyncMessage(const QString& message, const QVariant& data)
{
if (message == gFullScreenMessage) {
setFullscreen(data.toMap().value(QString("fullscreen")).toBool());
} else if (message == gDomContentLoadedMessage && data.toMap().value("rootFrame").toBool()) {
m_domContentLoaded = true;
emit domContentLoadedChanged();
}
}
bool DeclarativeWebPage::fullscreen() const
{
return m_fullscreen;
}
bool DeclarativeWebPage::forcedChrome() const
{
return m_forcedChrome;
}
void DeclarativeWebPage::setFullscreen(const bool fullscreen)
{
if (m_fullscreen != fullscreen) {
m_fullscreen = fullscreen;
resetHeight();
emit fullscreenChanged();
}
}
QDebug operator<<(QDebug dbg, const DeclarativeWebPage *page)
{
if (!page) {
return dbg << "DeclarativeWebPage (this = 0x0)";
}
dbg.nospace() << "DeclarativeWebPage(url = " << page->url() << ", title = " << page->title() << ", width = " << page->width()
<< ", height = " << page->height() << ", completed = " << page->completed()
<< ", active = " << page->active() << ", enabled = " << page->enabled() << ")";
return dbg.space();
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* Copyright 2016 Realm Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**************************************************************************/
#ifndef REALM_UTIL_INTERPROCESS_MUTEX
#define REALM_UTIL_INTERPROCESS_MUTEX
#include <realm/util/features.h>
#include <realm/util/thread.hpp>
#include <realm/util/file.hpp>
#include <realm/utilities.hpp>
#include <mutex>
#include <map>
// Enable this only on platforms where it might be needed
#if REALM_PLATFORM_APPLE || REALM_ANDROID
#define REALM_ROBUST_MUTEX_EMULATION
#endif
namespace realm {
namespace util {
// fwd decl to support friend decl below
class InterprocessCondVar;
/// Emulation of a Robust Mutex.
/// A Robust Mutex is an interprocess mutex which will automatically
/// release any locks held by a process when it crashes. Contrary to
/// Posix robust mutexes, this robust mutex is not capable of informing
/// participants that they have been granted a lock after a crash of
/// the process holding it (though it could be added if needed).
class InterprocessMutex {
public:
InterprocessMutex();
~InterprocessMutex() noexcept;
// Disable copying. Copying a locked Mutex will create a scenario
// where the same file descriptor will be locked once but unlocked twice.
InterprocessMutex(const InterprocessMutex&) = delete;
InterprocessMutex& operator=(const InterprocessMutex&) = delete;
#ifdef REALM_ROBUST_MUTEX_EMULATION
struct SharedPart {
};
#else
using SharedPart = RobustMutex;
#endif
/// You need to bind the emulation to a SharedPart in shared/mmapped memory.
/// The SharedPart is assumed to have been initialized (possibly by another process)
/// elsewhere.
void set_shared_part(SharedPart& shared_part, const std::string& path, const std::string& mutex_name);
void set_shared_part(SharedPart& shared_part, File&& lock_file);
/// Destroy shared object. Potentially release system resources. Caller must
/// ensure that the shared_part is not in use at the point of call.
void release_shared_part();
/// Lock the mutex. If the mutex is already locked, wait for it to be unlocked.
void lock();
/// Unlock the mutex
void unlock();
/// Attempt to check if the mutex is valid (only relevant if not emulating)
bool is_valid() noexcept;
static bool is_robust_on_this_platform()
{
#ifdef REALM_ROBUST_MUTEX_EMULATION
return true; // we're faking it!
#else
return RobustMutex::is_robust_on_this_platform();
#endif
}
private:
#ifdef REALM_ROBUST_MUTEX_EMULATION
struct LockInfo {
File m_file;
Mutex m_local_mutex;
LockInfo() {}
~LockInfo() noexcept;
// Disable copying.
LockInfo(const LockInfo&) = delete;
LockInfo& operator=(const LockInfo&) = delete;
};
/// InterprocessMutex created on the same file (same inode on POSIX) share the same LockInfo.
/// LockInfo will be saved in a static map as a weak ptr and use the UniqueID as the key.
/// Operations on the map need to be protected by s_mutex
static std::map<File::UniqueID, std::weak_ptr<LockInfo>>* s_info_map;
static Mutex* s_mutex;
/// We manually initialize these static variables when first needed,
/// creating them on the heap so that they last for the entire lifetime
/// of the process. The destructor of these is never called; the
/// process will clean up their memory when exiting. It is not enough
/// to count instances of InterprocessMutex and clean up these statics when
/// the count reaches zero because the program can create more
/// InterprocessMutex instances before the process ends, so we really need
/// these variables for the entire lifetime of the process.
static std::once_flag s_init_flag;
static void initialize_statics();
/// Only used for release_shared_part
std::string m_filename;
File::UniqueID m_fileuid;
std::shared_ptr<LockInfo> m_lock_info;
/// Free the lock info hold by this instance.
/// If it is the last reference, underly resources will be freed as well.
void free_lock_info();
#else
SharedPart* m_shared_part = nullptr;
#endif
friend class InterprocessCondVar;
};
inline InterprocessMutex::InterprocessMutex()
{
#ifdef REALM_ROBUST_MUTEX_EMULATION
std::call_once(s_init_flag, initialize_statics);
#endif
}
inline InterprocessMutex::~InterprocessMutex() noexcept
{
#ifdef REALM_ROBUST_MUTEX_EMULATION
free_lock_info();
#endif
}
#ifdef REALM_ROBUST_MUTEX_EMULATION
inline InterprocessMutex::LockInfo::~LockInfo() noexcept
{
if (m_file.is_attached()) {
m_file.close();
}
}
inline void InterprocessMutex::free_lock_info()
{
// It has not been initiated yet.
if (!m_lock_info)
return;
std::lock_guard<Mutex> guard(*s_mutex);
m_lock_info.reset();
if ((*s_info_map)[m_fileuid].expired()) {
s_info_map->erase(m_fileuid);
}
m_filename.clear();
}
inline void InterprocessMutex::initialize_statics()
{
s_mutex = new Mutex();
s_info_map = new std::map<File::UniqueID, std::weak_ptr<LockInfo>>();
}
#endif
inline void InterprocessMutex::set_shared_part(SharedPart& shared_part, const std::string& path,
const std::string& mutex_name)
{
#ifdef REALM_ROBUST_MUTEX_EMULATION
static_cast<void>(shared_part);
free_lock_info();
m_filename = path + "." + mutex_name + ".mx";
std::lock_guard<Mutex> guard(*s_mutex);
// Try to get the file uid if the file exists
if (File::get_unique_id(m_filename, m_fileuid)) {
auto result = s_info_map->find(m_fileuid);
if (result != s_info_map->end()) {
// File exists and the lock info has been created in the map.
m_lock_info = result->second.lock();
return;
}
}
// LockInfo has not been created yet.
m_lock_info = std::make_shared<LockInfo>();
// Always use mod_Write to open file and retreive the uid in case other process
// deletes the file.
m_lock_info->m_file.open(m_filename, File::mode_Write);
m_fileuid = m_lock_info->m_file.get_unique_id();
(*s_info_map)[m_fileuid] = m_lock_info;
#else
m_shared_part = &shared_part;
static_cast<void>(path);
static_cast<void>(mutex_name);
#endif
}
inline void InterprocessMutex::set_shared_part(SharedPart& shared_part, File&& lock_file)
{
#ifdef REALM_ROBUST_MUTEX_EMULATION
static_cast<void>(shared_part);
free_lock_info();
std::lock_guard<Mutex> guard(*s_mutex);
m_fileuid = lock_file.get_unique_id();
auto result = s_info_map->find(m_fileuid);
if (result == s_info_map->end()) {
m_lock_info = std::make_shared<LockInfo>();
m_lock_info->m_file = std::move(lock_file);
(*s_info_map)[m_fileuid] = m_lock_info;
}
else {
// File exists and the lock info has been created in the map.
m_lock_info = result->second.lock();
lock_file.close();
}
#else
m_shared_part = &shared_part;
static_cast<void>(lock_file);
#endif
}
inline void InterprocessMutex::release_shared_part()
{
#ifdef REALM_ROBUST_MUTEX_EMULATION
if (!m_filename.empty())
File::try_remove(m_filename);
free_lock_info();
#else
m_shared_part = nullptr;
#endif
}
inline void InterprocessMutex::lock()
{
#ifdef REALM_ROBUST_MUTEX_EMULATION
std::unique_lock<Mutex> mutex_lock(m_lock_info->m_local_mutex);
m_lock_info->m_file.lock_exclusive();
mutex_lock.release();
#else
REALM_ASSERT(m_shared_part);
m_shared_part->lock([]() {});
#endif
}
inline void InterprocessMutex::unlock()
{
#ifdef REALM_ROBUST_MUTEX_EMULATION
m_lock_info->m_file.unlock();
m_lock_info->m_local_mutex.unlock();
#else
REALM_ASSERT(m_shared_part);
m_shared_part->unlock();
#endif
}
inline bool InterprocessMutex::is_valid() noexcept
{
#ifdef REALM_ROBUST_MUTEX_EMULATION
return true;
#else
REALM_ASSERT(m_shared_part);
return m_shared_part->is_valid();
#endif
}
} // namespace util
} // namespace realm
#endif // #ifndef REALM_UTIL_INTERPROCESS_MUTEX
<commit_msg>Spelling error in comment.<commit_after>/*************************************************************************
*
* Copyright 2016 Realm Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**************************************************************************/
#ifndef REALM_UTIL_INTERPROCESS_MUTEX
#define REALM_UTIL_INTERPROCESS_MUTEX
#include <realm/util/features.h>
#include <realm/util/thread.hpp>
#include <realm/util/file.hpp>
#include <realm/utilities.hpp>
#include <mutex>
#include <map>
// Enable this only on platforms where it might be needed
#if REALM_PLATFORM_APPLE || REALM_ANDROID
#define REALM_ROBUST_MUTEX_EMULATION
#endif
namespace realm {
namespace util {
// fwd decl to support friend decl below
class InterprocessCondVar;
/// Emulation of a Robust Mutex.
/// A Robust Mutex is an interprocess mutex which will automatically
/// release any locks held by a process when it crashes. Contrary to
/// Posix robust mutexes, this robust mutex is not capable of informing
/// participants that they have been granted a lock after a crash of
/// the process holding it (though it could be added if needed).
class InterprocessMutex {
public:
InterprocessMutex();
~InterprocessMutex() noexcept;
// Disable copying. Copying a locked Mutex will create a scenario
// where the same file descriptor will be locked once but unlocked twice.
InterprocessMutex(const InterprocessMutex&) = delete;
InterprocessMutex& operator=(const InterprocessMutex&) = delete;
#ifdef REALM_ROBUST_MUTEX_EMULATION
struct SharedPart {
};
#else
using SharedPart = RobustMutex;
#endif
/// You need to bind the emulation to a SharedPart in shared/mmapped memory.
/// The SharedPart is assumed to have been initialized (possibly by another process)
/// elsewhere.
void set_shared_part(SharedPart& shared_part, const std::string& path, const std::string& mutex_name);
void set_shared_part(SharedPart& shared_part, File&& lock_file);
/// Destroy shared object. Potentially release system resources. Caller must
/// ensure that the shared_part is not in use at the point of call.
void release_shared_part();
/// Lock the mutex. If the mutex is already locked, wait for it to be unlocked.
void lock();
/// Unlock the mutex
void unlock();
/// Attempt to check if the mutex is valid (only relevant if not emulating)
bool is_valid() noexcept;
static bool is_robust_on_this_platform()
{
#ifdef REALM_ROBUST_MUTEX_EMULATION
return true; // we're faking it!
#else
return RobustMutex::is_robust_on_this_platform();
#endif
}
private:
#ifdef REALM_ROBUST_MUTEX_EMULATION
struct LockInfo {
File m_file;
Mutex m_local_mutex;
LockInfo() {}
~LockInfo() noexcept;
// Disable copying.
LockInfo(const LockInfo&) = delete;
LockInfo& operator=(const LockInfo&) = delete;
};
/// InterprocessMutex created on the same file (same inode on POSIX) share the same LockInfo.
/// LockInfo will be saved in a static map as a weak ptr and use the UniqueID as the key.
/// Operations on the map need to be protected by s_mutex
static std::map<File::UniqueID, std::weak_ptr<LockInfo>>* s_info_map;
static Mutex* s_mutex;
/// We manually initialize these static variables when first needed,
/// creating them on the heap so that they last for the entire lifetime
/// of the process. The destructor of these is never called; the
/// process will clean up their memory when exiting. It is not enough
/// to count instances of InterprocessMutex and clean up these statics when
/// the count reaches zero because the program can create more
/// InterprocessMutex instances before the process ends, so we really need
/// these variables for the entire lifetime of the process.
static std::once_flag s_init_flag;
static void initialize_statics();
/// Only used for release_shared_part
std::string m_filename;
File::UniqueID m_fileuid;
std::shared_ptr<LockInfo> m_lock_info;
/// Free the lock info hold by this instance.
/// If it is the last reference, underly resources will be freed as well.
void free_lock_info();
#else
SharedPart* m_shared_part = nullptr;
#endif
friend class InterprocessCondVar;
};
inline InterprocessMutex::InterprocessMutex()
{
#ifdef REALM_ROBUST_MUTEX_EMULATION
std::call_once(s_init_flag, initialize_statics);
#endif
}
inline InterprocessMutex::~InterprocessMutex() noexcept
{
#ifdef REALM_ROBUST_MUTEX_EMULATION
free_lock_info();
#endif
}
#ifdef REALM_ROBUST_MUTEX_EMULATION
inline InterprocessMutex::LockInfo::~LockInfo() noexcept
{
if (m_file.is_attached()) {
m_file.close();
}
}
inline void InterprocessMutex::free_lock_info()
{
// It has not been initialized yet.
if (!m_lock_info)
return;
std::lock_guard<Mutex> guard(*s_mutex);
m_lock_info.reset();
if ((*s_info_map)[m_fileuid].expired()) {
s_info_map->erase(m_fileuid);
}
m_filename.clear();
}
inline void InterprocessMutex::initialize_statics()
{
s_mutex = new Mutex();
s_info_map = new std::map<File::UniqueID, std::weak_ptr<LockInfo>>();
}
#endif
inline void InterprocessMutex::set_shared_part(SharedPart& shared_part, const std::string& path,
const std::string& mutex_name)
{
#ifdef REALM_ROBUST_MUTEX_EMULATION
static_cast<void>(shared_part);
free_lock_info();
m_filename = path + "." + mutex_name + ".mx";
std::lock_guard<Mutex> guard(*s_mutex);
// Try to get the file uid if the file exists
if (File::get_unique_id(m_filename, m_fileuid)) {
auto result = s_info_map->find(m_fileuid);
if (result != s_info_map->end()) {
// File exists and the lock info has been created in the map.
m_lock_info = result->second.lock();
return;
}
}
// LockInfo has not been created yet.
m_lock_info = std::make_shared<LockInfo>();
// Always use mod_Write to open file and retreive the uid in case other process
// deletes the file.
m_lock_info->m_file.open(m_filename, File::mode_Write);
m_fileuid = m_lock_info->m_file.get_unique_id();
(*s_info_map)[m_fileuid] = m_lock_info;
#else
m_shared_part = &shared_part;
static_cast<void>(path);
static_cast<void>(mutex_name);
#endif
}
inline void InterprocessMutex::set_shared_part(SharedPart& shared_part, File&& lock_file)
{
#ifdef REALM_ROBUST_MUTEX_EMULATION
static_cast<void>(shared_part);
free_lock_info();
std::lock_guard<Mutex> guard(*s_mutex);
m_fileuid = lock_file.get_unique_id();
auto result = s_info_map->find(m_fileuid);
if (result == s_info_map->end()) {
m_lock_info = std::make_shared<LockInfo>();
m_lock_info->m_file = std::move(lock_file);
(*s_info_map)[m_fileuid] = m_lock_info;
}
else {
// File exists and the lock info has been created in the map.
m_lock_info = result->second.lock();
lock_file.close();
}
#else
m_shared_part = &shared_part;
static_cast<void>(lock_file);
#endif
}
inline void InterprocessMutex::release_shared_part()
{
#ifdef REALM_ROBUST_MUTEX_EMULATION
if (!m_filename.empty())
File::try_remove(m_filename);
free_lock_info();
#else
m_shared_part = nullptr;
#endif
}
inline void InterprocessMutex::lock()
{
#ifdef REALM_ROBUST_MUTEX_EMULATION
std::unique_lock<Mutex> mutex_lock(m_lock_info->m_local_mutex);
m_lock_info->m_file.lock_exclusive();
mutex_lock.release();
#else
REALM_ASSERT(m_shared_part);
m_shared_part->lock([]() {});
#endif
}
inline void InterprocessMutex::unlock()
{
#ifdef REALM_ROBUST_MUTEX_EMULATION
m_lock_info->m_file.unlock();
m_lock_info->m_local_mutex.unlock();
#else
REALM_ASSERT(m_shared_part);
m_shared_part->unlock();
#endif
}
inline bool InterprocessMutex::is_valid() noexcept
{
#ifdef REALM_ROBUST_MUTEX_EMULATION
return true;
#else
REALM_ASSERT(m_shared_part);
return m_shared_part->is_valid();
#endif
}
} // namespace util
} // namespace realm
#endif // #ifndef REALM_UTIL_INTERPROCESS_MUTEX
<|endoftext|> |
<commit_before>#include <gtest/gtest.h>
#include "utList.h"
int main( int argc , char **argv )
{
testing :: InitGoogleTest( &argc , argv ) ;
return RUN_ALL_TESTS( ) ;
}
<commit_msg>Delete mainStructure.cpp<commit_after><|endoftext|> |
<commit_before>/** Copyright (C) 2017 Ultimaker - Released under terms of the AGPLv3 License */
#include <iterator>
#include <algorithm>
#include <math.h>
#include "AdaptiveLayerHeights.h"
namespace cura
{
AdaptiveLayer::AdaptiveLayer(int layer_height)
{
this->layer_height = layer_height;
}
AdaptiveLayerHeights::AdaptiveLayerHeights(Mesh* mesh, int layer_thickness, int initial_layer_thickness, coord_t variation, coord_t step_size, double threshold)
{
// store the required parameters
this->mesh = mesh;
this->layer_height = layer_thickness;
this->initial_layer_height = initial_layer_thickness;
this->max_variation = static_cast<int>(variation);
this->step_size = static_cast<int>(step_size);
this->threshold = threshold;
// calculate the allowed layer heights from variation and step size
// note: the order is from thickest to thinnest height!
for (int allowed_layer_height = this->layer_height + this->max_variation; allowed_layer_height >= this->layer_height - this->max_variation; allowed_layer_height -= this->step_size)
{
this->allowed_layer_heights.push_back(allowed_layer_height);
}
this->calculateMeshTriangleSlopes();
this->calculateLayers();
}
int AdaptiveLayerHeights::getLayerCount()
{
return this->layers.size();
}
std::vector<AdaptiveLayer>* AdaptiveLayerHeights::getLayers()
{
return &this->layers;
}
void AdaptiveLayerHeights::calculateLayers()
{
const int minimum_layer_height = *std::min_element(this->allowed_layer_heights.begin(), this->allowed_layer_heights.end());
SlicingTolerance slicing_tolerance = this->mesh->getSettingAsSlicingTolerance("slicing_tolerance");
std::vector<int> triangles_of_interest;
int z_level = 0;
int previous_layer_height = 0;
// the first layer has it's own independent height set, so we always add that
z_level += this->initial_layer_height;
// compensate first layer thickness depending on slicing mode
if (slicing_tolerance == SlicingTolerance::MIDDLE)
{
z_level += this->initial_layer_height / 2;
this->initial_layer_height += this->initial_layer_height / 2;
}
auto * adaptive_layer = new AdaptiveLayer(this->initial_layer_height);
adaptive_layer->z_position = z_level;
previous_layer_height = adaptive_layer->layer_height;
this->layers.push_back(*adaptive_layer);
// loop while triangles are found
while (!triangles_of_interest.empty() || this->layers.size() < 2)
{
// loop over all allowed layer heights starting with the largest
for (auto & layer_height : this->allowed_layer_heights)
{
int lower_bound = z_level;
int upper_bound = z_level + layer_height;
std::vector<int> min_bounds;
std::vector<int> max_bounds;
// calculate all intersecting lower bounds
for (auto it_lower = this->face_min_z_values.begin(); it_lower != this->face_min_z_values.end(); ++it_lower)
{
if (*it_lower <= upper_bound)
{
min_bounds.emplace_back(std::distance(this->face_min_z_values.begin(), it_lower));
}
}
// calculate all intersecting upper bounds
for (auto it_upper = this->face_max_z_values.begin(); it_upper != this->face_max_z_values.end(); ++it_upper)
{
if (*it_upper >= lower_bound)
{
max_bounds.emplace_back(std::distance(this->face_max_z_values.begin(), it_upper));
}
}
// use lower and upper bounds to filter on triangles that are interesting for this potential layer
triangles_of_interest.clear();
std::set_intersection(min_bounds.begin(), min_bounds.end(), max_bounds.begin(), max_bounds.end(), std::back_inserter(triangles_of_interest));
// when there not interesting triangles in this potential layer go to the next one
if (triangles_of_interest.empty())
{
break;
}
std::vector<double> slopes;
// find all slopes for interesting triangles
for (auto & triangle_index : triangles_of_interest)
{
double slope = this->face_slopes.at(triangle_index);
slopes.push_back(slope);
}
double minimum_slope = *std::min_element(slopes.begin(), slopes.end());
double minimum_slope_tan = std::tan(minimum_slope);
// check if the maximum step size has been exceeded depending on layer height direction
bool has_exceeded_step_size = false;
if (previous_layer_height > layer_height && previous_layer_height - layer_height > this->step_size)
{
has_exceeded_step_size = true;
}
else if (layer_height - previous_layer_height > this->step_size && layer_height > minimum_layer_height)
{
continue;
}
// we add the layer in the following cases:
// 1) the layer angle is below the threshold and the layer height difference with the previous layer is the maximum allowed step size
// 2) the layer height is the smallest it is allowed
// 3) the layer is a flat surface (we can't divide by 0)
if (minimum_slope_tan == 0.0
|| (layer_height / minimum_slope_tan) <= this->threshold
|| layer_height == minimum_layer_height
|| has_exceeded_step_size)
{
z_level += layer_height;
auto * adaptive_layer = new AdaptiveLayer(layer_height);
adaptive_layer->z_position = z_level;
previous_layer_height = adaptive_layer->layer_height;
this->layers.push_back(*adaptive_layer);
break;
}
}
// stop calculating when we're out of triangles (e.g. above the mesh)
if (triangles_of_interest.empty())
{
break;
}
}
}
void AdaptiveLayerHeights::calculateMeshTriangleSlopes()
{
// loop over all mesh faces (triangles) and find their slopes
for (const auto &face : this->mesh->faces)
{
const MeshVertex& v0 = this->mesh->vertices[face.vertex_index[0]];
const MeshVertex& v1 = this->mesh->vertices[face.vertex_index[1]];
const MeshVertex& v2 = this->mesh->vertices[face.vertex_index[2]];
FPoint3 p0 = v0.p;
FPoint3 p1 = v1.p;
FPoint3 p2 = v2.p;
float minZ = p0.z;
float maxZ = p0.z;
if (p1.z < minZ) minZ = p1.z;
if (p2.z < minZ) minZ = p2.z;
if (p1.z > maxZ) maxZ = p1.z;
if (p2.z > maxZ) maxZ = p2.z;
// calculate the angle of this triangle in the z direction
FPoint3 n = FPoint3(p1 - p0).cross(p2 - p0);
FPoint3 normal = n.normalized();
double z_angle = std::acos(std::abs(normal.z));
// prevent flat surfaces from influencing the algorithm
if (z_angle == 0)
{
z_angle = M_PI;
}
this->face_min_z_values.push_back(minZ * 1000);
this->face_max_z_values.push_back(maxZ * 1000);
this->face_slopes.push_back(z_angle);
}
}
}<commit_msg>Make search for interesting triangles more efficient.<commit_after>/** Copyright (C) 2017 Ultimaker - Released under terms of the AGPLv3 License */
#include <iterator>
#include <algorithm>
#include <math.h>
#include "AdaptiveLayerHeights.h"
namespace cura
{
AdaptiveLayer::AdaptiveLayer(int layer_height)
{
this->layer_height = layer_height;
}
AdaptiveLayerHeights::AdaptiveLayerHeights(Mesh* mesh, int layer_thickness, int initial_layer_thickness, coord_t variation, coord_t step_size, double threshold)
{
// store the required parameters
this->mesh = mesh;
this->layer_height = layer_thickness;
this->initial_layer_height = initial_layer_thickness;
this->max_variation = static_cast<int>(variation);
this->step_size = static_cast<int>(step_size);
this->threshold = threshold;
// calculate the allowed layer heights from variation and step size
// note: the order is from thickest to thinnest height!
for (int allowed_layer_height = this->layer_height + this->max_variation; allowed_layer_height >= this->layer_height - this->max_variation; allowed_layer_height -= this->step_size)
{
this->allowed_layer_heights.push_back(allowed_layer_height);
}
this->calculateMeshTriangleSlopes();
this->calculateLayers();
}
int AdaptiveLayerHeights::getLayerCount()
{
return this->layers.size();
}
std::vector<AdaptiveLayer>* AdaptiveLayerHeights::getLayers()
{
return &this->layers;
}
void AdaptiveLayerHeights::calculateLayers()
{
const int minimum_layer_height = *std::min_element(this->allowed_layer_heights.begin(), this->allowed_layer_heights.end());
SlicingTolerance slicing_tolerance = this->mesh->getSettingAsSlicingTolerance("slicing_tolerance");
std::vector<int> triangles_of_interest;
int z_level = 0;
int previous_layer_height = 0;
// the first layer has it's own independent height set, so we always add that
z_level += this->initial_layer_height;
// compensate first layer thickness depending on slicing mode
if (slicing_tolerance == SlicingTolerance::MIDDLE)
{
z_level += this->initial_layer_height / 2;
this->initial_layer_height += this->initial_layer_height / 2;
}
auto * adaptive_layer = new AdaptiveLayer(this->initial_layer_height);
adaptive_layer->z_position = z_level;
previous_layer_height = adaptive_layer->layer_height;
this->layers.push_back(*adaptive_layer);
// loop while triangles are found
while (!triangles_of_interest.empty() || this->layers.size() < 2)
{
// loop over all allowed layer heights starting with the largest
for (auto & layer_height : this->allowed_layer_heights)
{
// use lower and upper bounds to filter on triangles that are interesting for this potential layer
const int lower_bound = z_level;
const int upper_bound = z_level + layer_height;
triangles_of_interest.clear();
for (unsigned int i = 0; i < this->face_min_z_values.size(); ++i)
{
if (this->face_min_z_values[i] <= upper_bound && this->face_max_z_values[i] >= lower_bound)
{
triangles_of_interest.push_back(i);
}
}
// when there not interesting triangles in this potential layer go to the next one
if (triangles_of_interest.empty())
{
break;
}
std::vector<double> slopes;
// find all slopes for interesting triangles
for (auto & triangle_index : triangles_of_interest)
{
double slope = this->face_slopes.at(triangle_index);
slopes.push_back(slope);
}
double minimum_slope = *std::min_element(slopes.begin(), slopes.end());
double minimum_slope_tan = std::tan(minimum_slope);
// check if the maximum step size has been exceeded depending on layer height direction
bool has_exceeded_step_size = false;
if (previous_layer_height > layer_height && previous_layer_height - layer_height > this->step_size)
{
has_exceeded_step_size = true;
}
else if (layer_height - previous_layer_height > this->step_size && layer_height > minimum_layer_height)
{
continue;
}
// we add the layer in the following cases:
// 1) the layer angle is below the threshold and the layer height difference with the previous layer is the maximum allowed step size
// 2) the layer height is the smallest it is allowed
// 3) the layer is a flat surface (we can't divide by 0)
if (minimum_slope_tan == 0.0
|| (layer_height / minimum_slope_tan) <= this->threshold
|| layer_height == minimum_layer_height
|| has_exceeded_step_size)
{
z_level += layer_height;
auto * adaptive_layer = new AdaptiveLayer(layer_height);
adaptive_layer->z_position = z_level;
previous_layer_height = adaptive_layer->layer_height;
this->layers.push_back(*adaptive_layer);
break;
}
}
// stop calculating when we're out of triangles (e.g. above the mesh)
if (triangles_of_interest.empty())
{
break;
}
}
}
void AdaptiveLayerHeights::calculateMeshTriangleSlopes()
{
// loop over all mesh faces (triangles) and find their slopes
for (const auto &face : this->mesh->faces)
{
const MeshVertex& v0 = this->mesh->vertices[face.vertex_index[0]];
const MeshVertex& v1 = this->mesh->vertices[face.vertex_index[1]];
const MeshVertex& v2 = this->mesh->vertices[face.vertex_index[2]];
FPoint3 p0 = v0.p;
FPoint3 p1 = v1.p;
FPoint3 p2 = v2.p;
float minZ = p0.z;
float maxZ = p0.z;
if (p1.z < minZ) minZ = p1.z;
if (p2.z < minZ) minZ = p2.z;
if (p1.z > maxZ) maxZ = p1.z;
if (p2.z > maxZ) maxZ = p2.z;
// calculate the angle of this triangle in the z direction
FPoint3 n = FPoint3(p1 - p0).cross(p2 - p0);
FPoint3 normal = n.normalized();
double z_angle = std::acos(std::abs(normal.z));
// prevent flat surfaces from influencing the algorithm
if (z_angle == 0)
{
z_angle = M_PI;
}
this->face_min_z_values.push_back(minZ * 1000);
this->face_max_z_values.push_back(maxZ * 1000);
this->face_slopes.push_back(z_angle);
}
}
}<|endoftext|> |
<commit_before>#include <systems/OpenGLTextureRenderer.h>
OpenGLTextureRenderer::OpenGLTextureRenderer() : Base(anax::ComponentFilter().requires<Texcoords, PhysicsComponent>()) {
}
OpenGLTextureRenderer::~OpenGLTextureRenderer() {
}
void OpenGLTextureRenderer::render() {
auto entities = getEntities();
const float M2P = 30;
int s = entities.size();
for (auto entity : entities) {
auto& texCoordsComp = entity.getComponent<Texcoords>();
auto& physicsComp = entity.getComponent<PhysicsComponent>();
auto& image = texCoordsComp.image;
auto& texCoordsVec = texCoordsComp.textCoords;
b2Body* body = physicsComp.physicsBody;
GLuint texture = 0;
{
// if (!image.loadFromFile("1.png"))
// return;
// image.flipVertically();
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, image.getSize().x,
image.getSize().y, GL_RGBA, GL_UNSIGNED_BYTE,
image.getPixelsPtr());
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
GL_LINEAR_MIPMAP_LINEAR);
}
glBindTexture(GL_TEXTURE_2D, texture);
glDisableClientState(GL_NORMAL_ARRAY);
glDisableClientState(GL_COLOR_ARRAY);
b2PolygonShape* shape =
((b2PolygonShape*) body->GetFixtureList()->GetShape());
std::vector<b2Vec2> points(shape->GetVertexCount());
for (int i = 0; i < shape->GetVertexCount(); i++) {
points[i] = (shape)->GetVertex(i);
}
glPushMatrix();
b2Vec2 center = physicsComp.smoothedPosition;
float angle = body->GetAngle();
glTranslatef(static_cast<float>(floor(center.x * M2P)), static_cast<float>(floor(center.y * M2P)), 0.0f);
glRotatef(angle * 180.0 / M_PI, 0, 0, 1);
glBegin(GL_POLYGON); //begin drawing of polygon
for (int i = 0; i < shape->GetVertexCount(); i++) {
glTexCoord2d(texCoordsVec[i].x, texCoordsVec[i].y);
glVertex2f(floor(points[i].x * M2P), floor(points[i].y * M2P));
}
glEnd(); //end drawing of polygon
glPopMatrix();
}
}
<commit_msg>Updated code to use simple opengl calls for textures<commit_after>#include <systems/OpenGLTextureRenderer.h>
OpenGLTextureRenderer::OpenGLTextureRenderer() : Base(anax::ComponentFilter().requires<Texcoords, PhysicsComponent>()) {
}
OpenGLTextureRenderer::~OpenGLTextureRenderer() {
}
void OpenGLTextureRenderer::render() {
auto entities = getEntities();
const float M2P = 30.0f;
for (auto entity : entities) {
auto& texCoordsComp = entity.getComponent<Texcoords>();
auto& physicsComp = entity.getComponent<PhysicsComponent>();
auto& image = texCoordsComp.image;
auto& texCoordsVec = texCoordsComp.textCoords;
b2Body* body = physicsComp.physicsBody;
GLuint texture = 0;
{
// if (!image.loadFromFile("1.png"))
// return;
// image.flipVertically();
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, image.getSize().x,
image.getSize().y, GL_RGBA, GL_UNSIGNED_BYTE,
image.getPixelsPtr());
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
GL_LINEAR_MIPMAP_LINEAR);
}
glBindTexture(GL_TEXTURE_2D, texture);
glDisableClientState(GL_NORMAL_ARRAY);
glDisableClientState(GL_COLOR_ARRAY);
b2PolygonShape* shape =
((b2PolygonShape*) body->GetFixtureList()->GetShape());
std::vector<b2Vec2> points(shape->GetVertexCount());
for (int i = 0; i < shape->GetVertexCount(); i++) {
points[i] = (shape)->GetVertex(i);
}
glPushMatrix();
// b2Vec2 center = physicsComp.smoothedPosition;
b2Vec2 center = physicsComp.physicsBody->GetPosition();
float angle = body->GetAngle();
glTranslatef(static_cast<float>(floor(center.x * M2P)), static_cast<float>(floor(center.y * M2P)), 0.0f);
glRotatef(angle * 180.0 / M_PI, 0, 0, 1);
glBegin(GL_POLYGON); //begin drawing of polygon
for (int i = 0; i < shape->GetVertexCount(); i++) {
glTexCoord2d(texCoordsVec[i].x, texCoordsVec[i].y);
glVertex2f(floor(points[i].x * M2P), floor(points[i].y * M2P));
}
glEnd(); //end drawing of polygon
glPopMatrix();
}
}
<|endoftext|> |
<commit_before>#include <blackhole/sink/elasticsearch.hpp>
#include <blackhole/utils/atomic.hpp>
#include "../global.hpp"
using namespace blackhole;
TEST(elasticsearch_t, Class) {
using blackhole::sink::elasticsearch_t;
elasticsearch_t sink;
UNUSED(sink);
}
TEST(elasticsearch_t, Manual) {
using blackhole::sink::elasticsearch_t;
elasticsearch_t sink;
std::string msg = "{}";
boost::algorithm::replace_all(msg, "'", "\"");
for (int i = 0; i < 200; ++i) {
sink.consume(msg);
}
}
using namespace elasticsearch;
namespace mock {
class logger_t {
public:
template<typename... Args>
log::record_t open_record(Args&&...) const {
return log::record_t();
}
void push(log::record_t&&) const {}
};
class response_t {
};
class action_t {
public:
typedef response_t response_type;
typedef result_t<response_type>::type result_type;
static const request::method_t method_value = request::method_t::get;
static const char* name() {
return "mock.action";
}
std::string path() const {
return "/";
}
};
class connection_t {
public:
typedef boost::asio::ip::tcp protocol_type;
typedef protocol_type::endpoint endpoint_type;
template<class... Args>
connection_t(Args&&...) {}
MOCK_CONST_METHOD0(endpoint, endpoint_type());
MOCK_METHOD3(perform, void(
actions::nodes_info_t,
callback<actions::nodes_info_t>::type,
long
));
MOCK_METHOD3(perform, void(
action_t,
callback<action_t>::type,
long
));
};
class pool_t {
public:
typedef connection_t connection_type;
typedef connection_type::endpoint_type endpoint_type;
typedef std::unordered_map<
endpoint_type,
std::shared_ptr<connection_type>
> pool_type;
typedef pool_type::size_type size_type;
typedef pool_type::iterator iterator;
typedef std::mutex mutex_type;
typedef pool_lock_t<pool_t> pool_lock_type;
mutable std::mutex mutex;
typedef std::pair<iterator, bool> pair_type;
MOCK_METHOD2(insert, pair_type(
const endpoint_type&,
const std::shared_ptr<connection_type>&
));
MOCK_METHOD1(remove, void(const endpoint_type&));
//!@note: These methods are pure stubs, they shouldn't be called ever.
MOCK_CONST_METHOD1(size, size_type(pool_lock_type&));
MOCK_CONST_METHOD1(empty, bool(pool_lock_type&));
MOCK_METHOD1(begin, iterator(pool_lock_type&));
MOCK_METHOD1(end, iterator(pool_lock_type&));
};
class balancer : public balancing::strategy<pool_t> {
public:
typedef pool_t pool_type;
typedef pool_type::connection_type connection_type;
MOCK_METHOD1(next, std::shared_ptr<connection_type>(pool_type& pool));
};
} // namespace mock
namespace elasticsearch {
template<>
struct extractor_t<mock::response_t> {
static mock::response_t extract(const rapidjson::Value&) {
return mock::response_t();
}
};
} // namespace elasticsearch
class transport_t_SuccessfullyHandleMessage_Test;
namespace inspector {
//!@note: Helper class to easy ancestor's mock fields inspection.
template<class Connection, class Pool>
class http_transport_t : public elasticsearch::http_transport_t<Connection, Pool> {
friend class ::transport_t_SuccessfullyHandleMessage_Test;
public:
template<typename... Args>
http_transport_t(Args&&... args) :
elasticsearch::http_transport_t<Connection, Pool>(std::forward<Args>(args)...)
{}
};
} // namespace inspector
template<class Action>
struct event_t {
std::atomic<int>& counter;
void operator()(typename Action::result_type) {
counter++;
}
};
void post(boost::asio::io_service& loop,
callback<mock::action_t>::type callback,
result_t<mock::response_t>::type result) {
loop.post(std::bind(callback, result));
}
namespace stub {
synchronized<logger_base_t> log(logger_factory_t::create());
} // namespace stub
TEST(transport_t, SuccessfullyHandleMessage) {
boost::asio::io_service loop;
std::unique_ptr<mock::balancer> balancer(new mock::balancer);
std::shared_ptr<mock::connection_t> connection(new mock::connection_t);
settings_t settings;
inspector::http_transport_t<
mock::connection_t,
mock::pool_t
> transport(settings, loop, stub::log);
EXPECT_CALL(*balancer, next(_))
.Times(1)
.WillOnce(Return(connection));
EXPECT_CALL(*connection, endpoint())
.WillOnce(Return(mock::connection_t::endpoint_type()));
EXPECT_CALL(*connection, perform(An<mock::action_t>(), _, _))
.Times(1)
.WillOnce(
WithArg<1>(
Invoke(
std::bind(
&post,
std::ref(loop),
std::placeholders::_1,
mock::response_t()
)
)
)
);
transport.balancer = std::move(balancer);
std::atomic<int> counter(0);
transport.perform(mock::action_t(), event_t<mock::action_t> { counter });
loop.run_one();
EXPECT_EQ(1, counter);
}
<commit_msg>[Unit Testing] Added test that checks code sequence after some generic elasticsearch error occurs.<commit_after>#include <blackhole/sink/elasticsearch.hpp>
#include <blackhole/utils/atomic.hpp>
#include "../global.hpp"
using namespace blackhole;
TEST(elasticsearch_t, Class) {
using blackhole::sink::elasticsearch_t;
elasticsearch_t sink;
UNUSED(sink);
}
TEST(elasticsearch_t, Manual) {
using blackhole::sink::elasticsearch_t;
elasticsearch_t sink;
std::string msg = "{}";
boost::algorithm::replace_all(msg, "'", "\"");
for (int i = 0; i < 200; ++i) {
sink.consume(msg);
}
}
using namespace elasticsearch;
namespace mock {
class logger_t {
public:
template<typename... Args>
log::record_t open_record(Args&&...) const {
return log::record_t();
}
void push(log::record_t&&) const {}
};
class response_t {
};
class action_t {
public:
typedef response_t response_type;
typedef result_t<response_type>::type result_type;
static const request::method_t method_value = request::method_t::get;
static const char* name() {
return "mock.action";
}
std::string path() const {
return "/";
}
};
class connection_t {
public:
typedef boost::asio::ip::tcp protocol_type;
typedef protocol_type::endpoint endpoint_type;
template<class... Args>
connection_t(Args&&...) {}
MOCK_CONST_METHOD0(endpoint, endpoint_type());
MOCK_METHOD3(perform, void(
actions::nodes_info_t,
callback<actions::nodes_info_t>::type,
long
));
MOCK_METHOD3(perform, void(
action_t,
callback<action_t>::type,
long
));
};
class pool_t {
public:
typedef connection_t connection_type;
typedef connection_type::endpoint_type endpoint_type;
typedef std::unordered_map<
endpoint_type,
std::shared_ptr<connection_type>
> pool_type;
typedef pool_type::size_type size_type;
typedef pool_type::iterator iterator;
typedef std::mutex mutex_type;
typedef pool_lock_t<pool_t> pool_lock_type;
mutable std::mutex mutex;
typedef std::pair<iterator, bool> pair_type;
MOCK_METHOD2(insert, pair_type(
const endpoint_type&,
const std::shared_ptr<connection_type>&
));
MOCK_METHOD1(remove, void(const endpoint_type&));
//!@note: These methods are pure stubs, they shouldn't be called ever.
MOCK_CONST_METHOD1(size, size_type(pool_lock_type&));
MOCK_CONST_METHOD1(empty, bool(pool_lock_type&));
MOCK_METHOD1(begin, iterator(pool_lock_type&));
MOCK_METHOD1(end, iterator(pool_lock_type&));
};
class balancer : public balancing::strategy<pool_t> {
public:
typedef pool_t pool_type;
typedef pool_type::connection_type connection_type;
MOCK_METHOD1(next, std::shared_ptr<connection_type>(pool_type& pool));
};
} // namespace mock
namespace elasticsearch {
template<>
struct extractor_t<mock::response_t> {
static mock::response_t extract(const rapidjson::Value&) {
return mock::response_t();
}
};
} // namespace elasticsearch
class transport_t_SuccessfullyHandleMessage_Test;
class transport_t_HandleGenericError_Test;
namespace inspector {
//!@note: Helper class to easy ancestor's mock fields inspection.
template<class Connection, class Pool>
class http_transport_t : public elasticsearch::http_transport_t<Connection, Pool> {
friend class ::transport_t_SuccessfullyHandleMessage_Test;
friend class ::transport_t_HandleGenericError_Test;
public:
template<typename... Args>
http_transport_t(Args&&... args) :
elasticsearch::http_transport_t<Connection, Pool>(std::forward<Args>(args)...)
{}
};
} // namespace inspector
template<class Action>
struct event_t {
std::atomic<int>& counter;
void operator()(typename Action::result_type) {
counter++;
}
};
void post(boost::asio::io_service& loop,
callback<mock::action_t>::type callback,
result_t<mock::response_t>::type result) {
loop.post(std::bind(callback, result));
}
namespace stub {
synchronized<logger_base_t> log(logger_factory_t::create());
} // namespace stub
TEST(transport_t, SuccessfullyHandleMessage) {
boost::asio::io_service loop;
std::unique_ptr<mock::balancer> balancer(new mock::balancer);
std::shared_ptr<mock::connection_t> connection(new mock::connection_t);
settings_t settings;
inspector::http_transport_t<
mock::connection_t,
mock::pool_t
> transport(settings, loop, stub::log);
EXPECT_CALL(*balancer, next(_))
.Times(1)
.WillOnce(Return(connection));
EXPECT_CALL(*connection, endpoint())
.WillOnce(Return(mock::connection_t::endpoint_type()));
EXPECT_CALL(*connection, perform(An<mock::action_t>(), _, _))
.Times(1)
.WillOnce(
WithArg<1>(
Invoke(
std::bind(
&post,
std::ref(loop),
std::placeholders::_1,
mock::response_t()
)
)
)
);
transport.balancer = std::move(balancer);
std::atomic<int> counter(0);
transport.perform(mock::action_t(), event_t<mock::action_t> { counter });
loop.run_one();
EXPECT_EQ(1, counter);
}
TEST(transport_t, HandleGenericError) {
//! After receiving the response with some elasticsearch error,
//! a caller's callback must be called during next event loop tick.
boost::asio::io_service loop;
std::unique_ptr<mock::balancer> balancer(new mock::balancer);
std::shared_ptr<mock::connection_t> connection(new mock::connection_t);
settings_t settings;
inspector::http_transport_t<
mock::connection_t,
mock::pool_t
> transport(settings, loop, stub::log);
EXPECT_CALL(*balancer, next(_))
.Times(1)
.WillOnce(Return(connection));
EXPECT_CALL(*connection, endpoint())
.WillOnce(Return(mock::connection_t::endpoint_type()));
EXPECT_CALL(*connection, perform(An<mock::action_t>(), _, _))
.Times(1)
.WillOnce(
WithArg<1>(
Invoke(
std::bind(
&post,
std::ref(loop),
std::placeholders::_1,
elasticsearch::error_t(generic_error_t("mock"))
)
)
)
);
transport.balancer = std::move(balancer);
std::atomic<int> counter(0);
transport.perform(mock::action_t(), event_t<mock::action_t> { counter });
loop.run_one();
EXPECT_EQ(1, counter);
}
<|endoftext|> |
<commit_before>/*
QWebSockets implements the WebSocket protocol as defined in RFC 6455.
Copyright (C) 2013 Kurt Pattyn (pattyn.kurt@gmail.com)
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "handshakerequest_p.h"
#include <QString>
#include <QMap>
#include <QTextStream>
#include <QUrl>
#include <QList>
#include <QStringList>
#include "qwebsocketprotocol.h"
QT_BEGIN_NAMESPACE
/*!
\internal
*/
HandshakeRequest::HandshakeRequest(int port, bool isSecure) :
m_port(port),
m_isSecure(isSecure),
m_isValid(false),
m_headers(),
m_versions(),
m_key(),
m_origin(),
m_protocols(),
m_extensions(),
m_requestUrl()
{
}
/*!
\internal
*/
HandshakeRequest::~HandshakeRequest()
{
}
/*!
\internal
*/
void HandshakeRequest::clear()
{
m_port = -1;
m_isSecure = false;
m_isValid = false;
m_headers.clear();
m_versions.clear();
m_key.clear();
m_origin.clear();
m_protocols.clear();
m_extensions.clear();
m_requestUrl.clear();
}
/*!
\internal
*/
int HandshakeRequest::getPort() const
{
return m_requestUrl.port(m_port);
}
/*!
\internal
*/
bool HandshakeRequest::isSecure() const
{
return m_isSecure;
}
/*!
\internal
*/
bool HandshakeRequest::isValid() const
{
return m_isValid;
}
/*!
\internal
*/
QMap<QString, QString> HandshakeRequest::getHeaders() const
{
return m_headers;
}
/*!
\internal
*/
QList<QWebSocketProtocol::Version> HandshakeRequest::getVersions() const
{
return m_versions;
}
/*!
\internal
*/
QString HandshakeRequest::getResourceName() const
{
return m_requestUrl.path();
}
/*!
\internal
*/
QString HandshakeRequest::getKey() const
{
return m_key;
}
/*!
\internal
*/
QString HandshakeRequest::getHost() const
{
return m_requestUrl.host();
}
/*!
\internal
*/
QString HandshakeRequest::getOrigin() const
{
return m_origin;
}
/*!
\internal
*/
QList<QString> HandshakeRequest::getProtocols() const
{
return m_protocols;
}
/*!
\internal
*/
QList<QString> HandshakeRequest::getExtensions() const
{
return m_extensions;
}
/*!
\internal
*/
QUrl HandshakeRequest::getRequestUrl() const
{
return m_requestUrl;
}
/*!
\internal
*/
QTextStream &HandshakeRequest::readFromStream(QTextStream &textStream)
{
m_isValid = false;
clear();
if (textStream.status() == QTextStream::Ok)
{
QString requestLine = textStream.readLine();
QStringList tokens = requestLine.split(' ', QString::SkipEmptyParts);
QString verb = tokens[0];
QString resourceName = tokens[1];
QString httpProtocol = tokens[2];
bool conversionOk = false;
float httpVersion = httpProtocol.midRef(5).toFloat(&conversionOk);
QString headerLine = textStream.readLine();
m_headers.clear();
while (!headerLine.isEmpty())
{
QStringList headerField = headerLine.split(QString(": "), QString::SkipEmptyParts);
m_headers.insertMulti(headerField[0], headerField[1]);
headerLine = textStream.readLine();
}
QString host = m_headers.value("Host", "");
m_requestUrl = QUrl::fromEncoded(resourceName.toLatin1());
if (m_requestUrl.isRelative())
{
m_requestUrl.setHost(host);
}
if (m_requestUrl.scheme().isEmpty())
{
QString scheme = isSecure() ? "wss://" : "ws://";
m_requestUrl.setScheme(scheme);
}
QStringList versionLines = m_headers.values("Sec-WebSocket-Version");
Q_FOREACH(QString versionLine, versionLines)
{
QStringList versions = versionLine.split(",", QString::SkipEmptyParts);
Q_FOREACH(QString version, versions)
{
QWebSocketProtocol::Version ver = QWebSocketProtocol::versionFromString(version.trimmed());
m_versions << ver;
}
}
qStableSort(m_versions.begin(), m_versions.end(), qGreater<QWebSocketProtocol::Version>()); //sort in descending order
m_key = m_headers.value("Sec-WebSocket-Key", "");
QString upgrade = m_headers.value("Upgrade", ""); //must be equal to "websocket", case-insensitive
QString connection = m_headers.value("Connection", ""); //must contain "Upgrade", case-insensitive
QStringList connectionLine = connection.split(",", QString::SkipEmptyParts);
QStringList connectionValues;
Q_FOREACH(QString connection, connectionLine)
{
connectionValues << connection.trimmed();
}
//optional headers
m_origin = m_headers.value("Sec-WebSocket-Origin", "");
QStringList protocolLines = m_headers.values("Sec-WebSocket-Protocol");
Q_FOREACH(QString protocolLine, protocolLines)
{
QStringList protocols = protocolLine.split(",", QString::SkipEmptyParts);
Q_FOREACH(QString protocol, protocols)
{
m_protocols << protocol.trimmed();
}
}
QStringList extensionLines = m_headers.values("Sec-WebSocket-Extensions");
Q_FOREACH(QString extensionLine, extensionLines)
{
QStringList extensions = extensionLine.split(",", QString::SkipEmptyParts);
Q_FOREACH(QString extension, extensions)
{
m_extensions << extension.trimmed();
}
}
//TODO: authentication field
m_isValid = !(host.isEmpty() ||
resourceName.isEmpty() ||
m_versions.isEmpty() ||
m_key.isEmpty() ||
(verb != "GET") ||
(!conversionOk || (httpVersion < 1.1f)) ||
(upgrade.toLower() != "websocket") ||
(!connectionValues.contains("upgrade", Qt::CaseInsensitive)));
}
return textStream;
}
/*!
\internal
*/
QTextStream &operator >>(QTextStream &stream, HandshakeRequest &request)
{
return request.readFromStream(stream);
}
QT_END_NAMESPACE
<commit_msg>Replace string literals with QString::fromLatin1() expression, to avoid deprecated warning (since Qt 5.1.1)<commit_after>/*
QWebSockets implements the WebSocket protocol as defined in RFC 6455.
Copyright (C) 2013 Kurt Pattyn (pattyn.kurt@gmail.com)
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "handshakerequest_p.h"
#include <QString>
#include <QMap>
#include <QTextStream>
#include <QUrl>
#include <QList>
#include <QStringList>
#include "qwebsocketprotocol.h"
QT_BEGIN_NAMESPACE
/*!
\internal
*/
HandshakeRequest::HandshakeRequest(int port, bool isSecure) :
m_port(port),
m_isSecure(isSecure),
m_isValid(false),
m_headers(),
m_versions(),
m_key(),
m_origin(),
m_protocols(),
m_extensions(),
m_requestUrl()
{
}
/*!
\internal
*/
HandshakeRequest::~HandshakeRequest()
{
}
/*!
\internal
*/
void HandshakeRequest::clear()
{
m_port = -1;
m_isSecure = false;
m_isValid = false;
m_headers.clear();
m_versions.clear();
m_key.clear();
m_origin.clear();
m_protocols.clear();
m_extensions.clear();
m_requestUrl.clear();
}
/*!
\internal
*/
int HandshakeRequest::getPort() const
{
return m_requestUrl.port(m_port);
}
/*!
\internal
*/
bool HandshakeRequest::isSecure() const
{
return m_isSecure;
}
/*!
\internal
*/
bool HandshakeRequest::isValid() const
{
return m_isValid;
}
/*!
\internal
*/
QMap<QString, QString> HandshakeRequest::getHeaders() const
{
return m_headers;
}
/*!
\internal
*/
QList<QWebSocketProtocol::Version> HandshakeRequest::getVersions() const
{
return m_versions;
}
/*!
\internal
*/
QString HandshakeRequest::getResourceName() const
{
return m_requestUrl.path();
}
/*!
\internal
*/
QString HandshakeRequest::getKey() const
{
return m_key;
}
/*!
\internal
*/
QString HandshakeRequest::getHost() const
{
return m_requestUrl.host();
}
/*!
\internal
*/
QString HandshakeRequest::getOrigin() const
{
return m_origin;
}
/*!
\internal
*/
QList<QString> HandshakeRequest::getProtocols() const
{
return m_protocols;
}
/*!
\internal
*/
QList<QString> HandshakeRequest::getExtensions() const
{
return m_extensions;
}
/*!
\internal
*/
QUrl HandshakeRequest::getRequestUrl() const
{
return m_requestUrl;
}
/*!
\internal
*/
QTextStream &HandshakeRequest::readFromStream(QTextStream &textStream)
{
m_isValid = false;
clear();
if (textStream.status() == QTextStream::Ok)
{
QString requestLine = textStream.readLine();
QStringList tokens = requestLine.split(' ', QString::SkipEmptyParts);
QString verb = tokens[0];
QString resourceName = tokens[1];
QString httpProtocol = tokens[2];
bool conversionOk = false;
float httpVersion = httpProtocol.midRef(5).toFloat(&conversionOk);
QString headerLine = textStream.readLine();
m_headers.clear();
while (!headerLine.isEmpty())
{
QStringList headerField = headerLine.split(QString::fromLatin1(": "), QString::SkipEmptyParts);
m_headers.insertMulti(headerField[0], headerField[1]);
headerLine = textStream.readLine();
}
QString host = m_headers.value("Host", "");
m_requestUrl = QUrl::fromEncoded(resourceName.toLatin1());
if (m_requestUrl.isRelative())
{
m_requestUrl.setHost(host);
}
if (m_requestUrl.scheme().isEmpty())
{
QString scheme = QString::fromLatin1(isSecure() ? "wss://" : "ws://");
m_requestUrl.setScheme(scheme);
}
QStringList versionLines = m_headers.values("Sec-WebSocket-Version");
Q_FOREACH(QString versionLine, versionLines)
{
QStringList versions = versionLine.split(",", QString::SkipEmptyParts);
Q_FOREACH(QString version, versions)
{
QWebSocketProtocol::Version ver = QWebSocketProtocol::versionFromString(version.trimmed());
m_versions << ver;
}
}
qStableSort(m_versions.begin(), m_versions.end(), qGreater<QWebSocketProtocol::Version>()); //sort in descending order
m_key = m_headers.value("Sec-WebSocket-Key", "");
QString upgrade = m_headers.value("Upgrade", ""); //must be equal to "websocket", case-insensitive
QString connection = m_headers.value("Connection", ""); //must contain "Upgrade", case-insensitive
QStringList connectionLine = connection.split(",", QString::SkipEmptyParts);
QStringList connectionValues;
Q_FOREACH(QString connection, connectionLine)
{
connectionValues << connection.trimmed();
}
//optional headers
m_origin = m_headers.value("Sec-WebSocket-Origin", "");
QStringList protocolLines = m_headers.values("Sec-WebSocket-Protocol");
Q_FOREACH(QString protocolLine, protocolLines)
{
QStringList protocols = protocolLine.split(",", QString::SkipEmptyParts);
Q_FOREACH(QString protocol, protocols)
{
m_protocols << protocol.trimmed();
}
}
QStringList extensionLines = m_headers.values("Sec-WebSocket-Extensions");
Q_FOREACH(QString extensionLine, extensionLines)
{
QStringList extensions = extensionLine.split(",", QString::SkipEmptyParts);
Q_FOREACH(QString extension, extensions)
{
m_extensions << extension.trimmed();
}
}
//TODO: authentication field
m_isValid = !(host.isEmpty() ||
resourceName.isEmpty() ||
m_versions.isEmpty() ||
m_key.isEmpty() ||
(verb != QString::fromLatin1("GET")) ||
(!conversionOk || (httpVersion < 1.1f)) ||
(upgrade.toLower() != QString::fromLatin1("websocket")) ||
(!connectionValues.contains("upgrade", Qt::CaseInsensitive)));
}
return textStream;
}
/*!
\internal
*/
QTextStream &operator >>(QTextStream &stream, HandshakeRequest &request)
{
return request.readFromStream(stream);
}
QT_END_NAMESPACE
<|endoftext|> |
<commit_before>/**
******************************************************************************
* Xenia : Xbox 360 Emulator Research Project *
******************************************************************************
* Copyright 2015 Ben Vanik. All rights reserved. *
* Released under the BSD license - see LICENSE in the root for more details. *
******************************************************************************
*/
#include <gflags/gflags.h>
#include <cinttypes>
#include <cstring>
#include <string>
#include <vector>
#include "xenia/base/logging.h"
#include "xenia/base/main.h"
#include "xenia/base/platform.h"
#include "xenia/base/string.h"
#include "xenia/gpu/dxbc_shader_translator.h"
#include "xenia/gpu/glsl_shader_translator.h"
#include "xenia/gpu/shader_translator.h"
#include "xenia/gpu/spirv_shader_translator.h"
#include "xenia/ui/spirv/spirv_disassembler.h"
// For D3DDisassemble:
#if XE_PLATFORM_WIN32
#include "xenia/ui/d3d12/d3d12_api.h"
#endif // XE_PLATFORM_WIN32
DEFINE_string(shader_input, "", "Input shader binary file path.");
DEFINE_string(shader_input_type, "",
"'vs', 'ps', or unspecified to infer from the given filename.");
DEFINE_string(shader_output, "", "Output shader file path.");
DEFINE_string(shader_output_type, "ucode",
"Translator to use: [ucode, glsl45, spirv, spirvtext, dxbc].");
DEFINE_string(shader_output_patch, "",
"Tessellation patch type in the generated tessellation "
"evaluation (domain) shader, or unspecified to produce a vertex "
"shader: [line, triangle, quad].");
DEFINE_bool(shader_output_dxbc_rov, false,
"Output ROV-based output-merger code in DXBC pixel shaders.");
namespace xe {
namespace gpu {
int shader_compiler_main(const std::vector<std::wstring>& args) {
ShaderType shader_type;
if (!FLAGS_shader_input_type.empty()) {
if (FLAGS_shader_input_type == "vs") {
shader_type = ShaderType::kVertex;
} else if (FLAGS_shader_input_type == "ps") {
shader_type = ShaderType::kPixel;
} else {
XELOGE("Invalid --shader_input_type; must be 'vs' or 'ps'.");
return 1;
}
} else {
auto last_dot = FLAGS_shader_input.find_last_of('.');
bool valid_type = false;
if (last_dot != std::string::npos) {
if (FLAGS_shader_input.substr(last_dot) == ".vs") {
shader_type = ShaderType::kVertex;
valid_type = true;
} else if (FLAGS_shader_input.substr(last_dot) == ".ps") {
shader_type = ShaderType::kPixel;
valid_type = true;
}
}
if (!valid_type) {
XELOGE(
"File type not recognized (use .vs, .ps or "
"--shader_input_type=vs|ps).");
return 1;
}
}
auto input_file = fopen(FLAGS_shader_input.c_str(), "rb");
if (!input_file) {
XELOGE("Unable to open input file: %s", FLAGS_shader_input.c_str());
return 1;
}
fseek(input_file, 0, SEEK_END);
size_t input_file_size = ftell(input_file);
fseek(input_file, 0, SEEK_SET);
std::vector<uint32_t> ucode_dwords(input_file_size / 4);
fread(ucode_dwords.data(), 4, ucode_dwords.size(), input_file);
fclose(input_file);
XELOGI("Opened %s as a %s shader, %" PRId64 " words (%" PRId64 " bytes).",
FLAGS_shader_input.c_str(),
shader_type == ShaderType::kVertex ? "vertex" : "pixel",
ucode_dwords.size(), ucode_dwords.size() * 4);
// TODO(benvanik): hash? need to return the data to big-endian format first.
uint64_t ucode_data_hash = 0;
auto shader = std::make_unique<Shader>(
shader_type, ucode_data_hash, ucode_dwords.data(), ucode_dwords.size());
std::unique_ptr<ShaderTranslator> translator;
if (FLAGS_shader_output_type == "spirv" ||
FLAGS_shader_output_type == "spirvtext") {
translator = std::make_unique<SpirvShaderTranslator>();
} else if (FLAGS_shader_output_type == "glsl45") {
translator = std::make_unique<GlslShaderTranslator>(
GlslShaderTranslator::Dialect::kGL45);
} else if (FLAGS_shader_output_type == "dxbc") {
translator =
std::make_unique<DxbcShaderTranslator>(0, FLAGS_shader_output_dxbc_rov);
} else {
translator = std::make_unique<UcodeShaderTranslator>();
}
PrimitiveType patch_primitive_type = PrimitiveType::kNone;
if (shader_type == ShaderType::kVertex) {
if (FLAGS_shader_output_patch == "line") {
patch_primitive_type == PrimitiveType::kLinePatch;
} else if (FLAGS_shader_output_patch == "triangle") {
patch_primitive_type == PrimitiveType::kTrianglePatch;
} else if (FLAGS_shader_output_patch == "quad") {
patch_primitive_type == PrimitiveType::kQuadPatch;
}
}
translator->Translate(shader.get(), patch_primitive_type);
const void* source_data = shader->translated_binary().data();
size_t source_data_size = shader->translated_binary().size();
std::unique_ptr<xe::ui::spirv::SpirvDisassembler::Result> spirv_disasm_result;
if (FLAGS_shader_output_type == "spirvtext") {
// Disassemble SPIRV.
spirv_disasm_result = xe::ui::spirv::SpirvDisassembler().Disassemble(
reinterpret_cast<const uint32_t*>(source_data), source_data_size / 4);
source_data = spirv_disasm_result->text();
source_data_size = std::strlen(spirv_disasm_result->text()) + 1;
}
#if XE_PLATFORM_WIN32
ID3DBlob* dxbc_disasm_blob = nullptr;
if (FLAGS_shader_output_type == "dxbc") {
HMODULE d3d_compiler = LoadLibrary(L"D3DCompiler_47.dll");
if (d3d_compiler != nullptr) {
pD3DDisassemble d3d_disassemble =
pD3DDisassemble(GetProcAddress(d3d_compiler, "D3DDisassemble"));
if (d3d_disassemble != nullptr) {
// Disassemble DXBC.
if (SUCCEEDED(d3d_disassemble(source_data, source_data_size,
D3D_DISASM_ENABLE_INSTRUCTION_NUMBERING |
D3D_DISASM_ENABLE_INSTRUCTION_OFFSET,
nullptr, &dxbc_disasm_blob))) {
source_data = dxbc_disasm_blob->GetBufferPointer();
source_data_size = dxbc_disasm_blob->GetBufferSize();
}
}
FreeLibrary(d3d_compiler);
}
}
#endif // XE_PLATFORM_WIN32
if (!FLAGS_shader_output.empty()) {
auto output_file = fopen(FLAGS_shader_output.c_str(), "wb");
fwrite(source_data, 1, source_data_size, output_file);
fclose(output_file);
}
#if XE_PLATFORM_WIN32
if (dxbc_disasm_blob != nullptr) {
dxbc_disasm_blob->Release();
}
#endif // XE_PLATFORM_WIN32
return 0;
}
} // namespace gpu
} // namespace xe
DEFINE_ENTRY_POINT(L"xenia-gpu-shader-compiler",
L"xenia-gpu-shader-compiler shader.bin",
xe::gpu::shader_compiler_main);
<commit_msg>[D3D12] Fix typos in shader_compiler_main<commit_after>/**
******************************************************************************
* Xenia : Xbox 360 Emulator Research Project *
******************************************************************************
* Copyright 2015 Ben Vanik. All rights reserved. *
* Released under the BSD license - see LICENSE in the root for more details. *
******************************************************************************
*/
#include <gflags/gflags.h>
#include <cinttypes>
#include <cstring>
#include <string>
#include <vector>
#include "xenia/base/logging.h"
#include "xenia/base/main.h"
#include "xenia/base/platform.h"
#include "xenia/base/string.h"
#include "xenia/gpu/dxbc_shader_translator.h"
#include "xenia/gpu/glsl_shader_translator.h"
#include "xenia/gpu/shader_translator.h"
#include "xenia/gpu/spirv_shader_translator.h"
#include "xenia/ui/spirv/spirv_disassembler.h"
// For D3DDisassemble:
#if XE_PLATFORM_WIN32
#include "xenia/ui/d3d12/d3d12_api.h"
#endif // XE_PLATFORM_WIN32
DEFINE_string(shader_input, "", "Input shader binary file path.");
DEFINE_string(shader_input_type, "",
"'vs', 'ps', or unspecified to infer from the given filename.");
DEFINE_string(shader_output, "", "Output shader file path.");
DEFINE_string(shader_output_type, "ucode",
"Translator to use: [ucode, glsl45, spirv, spirvtext, dxbc].");
DEFINE_string(shader_output_patch, "",
"Tessellation patch type in the generated tessellation "
"evaluation (domain) shader, or unspecified to produce a vertex "
"shader: [line, triangle, quad].");
DEFINE_bool(shader_output_dxbc_rov, false,
"Output ROV-based output-merger code in DXBC pixel shaders.");
namespace xe {
namespace gpu {
int shader_compiler_main(const std::vector<std::wstring>& args) {
ShaderType shader_type;
if (!FLAGS_shader_input_type.empty()) {
if (FLAGS_shader_input_type == "vs") {
shader_type = ShaderType::kVertex;
} else if (FLAGS_shader_input_type == "ps") {
shader_type = ShaderType::kPixel;
} else {
XELOGE("Invalid --shader_input_type; must be 'vs' or 'ps'.");
return 1;
}
} else {
auto last_dot = FLAGS_shader_input.find_last_of('.');
bool valid_type = false;
if (last_dot != std::string::npos) {
if (FLAGS_shader_input.substr(last_dot) == ".vs") {
shader_type = ShaderType::kVertex;
valid_type = true;
} else if (FLAGS_shader_input.substr(last_dot) == ".ps") {
shader_type = ShaderType::kPixel;
valid_type = true;
}
}
if (!valid_type) {
XELOGE(
"File type not recognized (use .vs, .ps or "
"--shader_input_type=vs|ps).");
return 1;
}
}
auto input_file = fopen(FLAGS_shader_input.c_str(), "rb");
if (!input_file) {
XELOGE("Unable to open input file: %s", FLAGS_shader_input.c_str());
return 1;
}
fseek(input_file, 0, SEEK_END);
size_t input_file_size = ftell(input_file);
fseek(input_file, 0, SEEK_SET);
std::vector<uint32_t> ucode_dwords(input_file_size / 4);
fread(ucode_dwords.data(), 4, ucode_dwords.size(), input_file);
fclose(input_file);
XELOGI("Opened %s as a %s shader, %" PRId64 " words (%" PRId64 " bytes).",
FLAGS_shader_input.c_str(),
shader_type == ShaderType::kVertex ? "vertex" : "pixel",
ucode_dwords.size(), ucode_dwords.size() * 4);
// TODO(benvanik): hash? need to return the data to big-endian format first.
uint64_t ucode_data_hash = 0;
auto shader = std::make_unique<Shader>(
shader_type, ucode_data_hash, ucode_dwords.data(), ucode_dwords.size());
std::unique_ptr<ShaderTranslator> translator;
if (FLAGS_shader_output_type == "spirv" ||
FLAGS_shader_output_type == "spirvtext") {
translator = std::make_unique<SpirvShaderTranslator>();
} else if (FLAGS_shader_output_type == "glsl45") {
translator = std::make_unique<GlslShaderTranslator>(
GlslShaderTranslator::Dialect::kGL45);
} else if (FLAGS_shader_output_type == "dxbc") {
translator =
std::make_unique<DxbcShaderTranslator>(0, FLAGS_shader_output_dxbc_rov);
} else {
translator = std::make_unique<UcodeShaderTranslator>();
}
PrimitiveType patch_primitive_type = PrimitiveType::kNone;
if (shader_type == ShaderType::kVertex) {
if (FLAGS_shader_output_patch == "line") {
patch_primitive_type = PrimitiveType::kLinePatch;
} else if (FLAGS_shader_output_patch == "triangle") {
patch_primitive_type = PrimitiveType::kTrianglePatch;
} else if (FLAGS_shader_output_patch == "quad") {
patch_primitive_type = PrimitiveType::kQuadPatch;
}
}
translator->Translate(shader.get(), patch_primitive_type);
const void* source_data = shader->translated_binary().data();
size_t source_data_size = shader->translated_binary().size();
std::unique_ptr<xe::ui::spirv::SpirvDisassembler::Result> spirv_disasm_result;
if (FLAGS_shader_output_type == "spirvtext") {
// Disassemble SPIRV.
spirv_disasm_result = xe::ui::spirv::SpirvDisassembler().Disassemble(
reinterpret_cast<const uint32_t*>(source_data), source_data_size / 4);
source_data = spirv_disasm_result->text();
source_data_size = std::strlen(spirv_disasm_result->text()) + 1;
}
#if XE_PLATFORM_WIN32
ID3DBlob* dxbc_disasm_blob = nullptr;
if (FLAGS_shader_output_type == "dxbc") {
HMODULE d3d_compiler = LoadLibrary(L"D3DCompiler_47.dll");
if (d3d_compiler != nullptr) {
pD3DDisassemble d3d_disassemble =
pD3DDisassemble(GetProcAddress(d3d_compiler, "D3DDisassemble"));
if (d3d_disassemble != nullptr) {
// Disassemble DXBC.
if (SUCCEEDED(d3d_disassemble(source_data, source_data_size,
D3D_DISASM_ENABLE_INSTRUCTION_NUMBERING |
D3D_DISASM_ENABLE_INSTRUCTION_OFFSET,
nullptr, &dxbc_disasm_blob))) {
source_data = dxbc_disasm_blob->GetBufferPointer();
source_data_size = dxbc_disasm_blob->GetBufferSize();
}
}
FreeLibrary(d3d_compiler);
}
}
#endif // XE_PLATFORM_WIN32
if (!FLAGS_shader_output.empty()) {
auto output_file = fopen(FLAGS_shader_output.c_str(), "wb");
fwrite(source_data, 1, source_data_size, output_file);
fclose(output_file);
}
#if XE_PLATFORM_WIN32
if (dxbc_disasm_blob != nullptr) {
dxbc_disasm_blob->Release();
}
#endif // XE_PLATFORM_WIN32
return 0;
}
} // namespace gpu
} // namespace xe
DEFINE_ENTRY_POINT(L"xenia-gpu-shader-compiler",
L"xenia-gpu-shader-compiler shader.bin",
xe::gpu::shader_compiler_main);
<|endoftext|> |
<commit_before><commit_msg>coverity#1255389 Dereference null return value<commit_after><|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: swstylemanager.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2006-12-05 16:38:21 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"
#pragma hdrstop
#include "swstylemanager.hxx"
#include <hash_map>
#include <svtools/stylepool.hxx>
#ifndef _DOC_HXX
#include <doc.hxx>
#endif
#ifndef _CHARFMT_HXX
#include <charfmt.hxx>
#endif
#ifndef _DOCARY_HXX
#include <docary.hxx>
#endif
#ifndef _SWTYPES_HXX
#include <swtypes.hxx>
#endif
#ifndef _ISTYLEACCESS_HXX
#include <istyleaccess.hxx>
#endif
typedef ::std::hash_map< const ::rtl::OUString,
StylePool::SfxItemSet_Pointer_t,
::rtl::OUStringHash,
::std::equal_to< ::rtl::OUString > > SwStyleNameCache;
class SwStyleCache
{
SwStyleNameCache mMap;
public:
SwStyleCache() {}
void addStyleName( StylePool::SfxItemSet_Pointer_t pStyle )
{ mMap[ StylePool::nameOf(pStyle) ] = pStyle; }
void addCompletePool( StylePool& rPool );
StylePool::SfxItemSet_Pointer_t getByName( const rtl::OUString& rName ) { return mMap[rName]; }
};
void SwStyleCache::addCompletePool( StylePool& rPool )
{
IStylePoolIteratorAccess *pIter = rPool.createIterator();
StylePool::SfxItemSet_Pointer_t pStyle = pIter->getNext();
while( pStyle.get() )
{
rtl::OUString aName( StylePool::nameOf(pStyle) );
mMap[ aName ] = pStyle;
pStyle = pIter->getNext();
}
delete pIter;
}
class SwStyleManager : public IStyleAccess
{
StylePool aAutoCharPool;
StylePool aAutoParaPool;
SwStyleCache *mpCharCache;
SwStyleCache *mpParaCache;
public:
SwStyleManager() : mpCharCache(0), mpParaCache(0) {}
virtual ~SwStyleManager();
virtual StylePool::SfxItemSet_Pointer_t getAutomaticStyle( const SfxItemSet& rSet,
IStyleAccess::SwAutoStyleFamily eFamily );
virtual StylePool::SfxItemSet_Pointer_t getByName( const rtl::OUString& rName,
IStyleAccess::SwAutoStyleFamily eFamily );
virtual void getAllStyles( std::vector<StylePool::SfxItemSet_Pointer_t> &rStyles,
IStyleAccess::SwAutoStyleFamily eFamily );
virtual StylePool::SfxItemSet_Pointer_t cacheAutomaticStyle( const SfxItemSet& rSet,
SwAutoStyleFamily eFamily );
virtual void clearCaches();
};
IStyleAccess *createStyleManager()
{
return new SwStyleManager();
}
SwStyleManager::~SwStyleManager()
{
delete mpCharCache;
delete mpParaCache;
}
void SwStyleManager::clearCaches()
{
delete mpCharCache;
mpCharCache = 0;
delete mpParaCache;
mpParaCache = 0;
}
StylePool::SfxItemSet_Pointer_t SwStyleManager::getAutomaticStyle( const SfxItemSet& rSet,
IStyleAccess::SwAutoStyleFamily eFamily )
{
StylePool& rAutoPool = eFamily == IStyleAccess::AUTO_STYLE_CHAR ? aAutoCharPool : aAutoParaPool;
return rAutoPool.insertItemSet( rSet );
}
StylePool::SfxItemSet_Pointer_t SwStyleManager::cacheAutomaticStyle( const SfxItemSet& rSet,
IStyleAccess::SwAutoStyleFamily eFamily )
{
StylePool& rAutoPool = eFamily == IStyleAccess::AUTO_STYLE_CHAR ? aAutoCharPool : aAutoParaPool;
StylePool::SfxItemSet_Pointer_t pStyle = rAutoPool.insertItemSet( rSet );
SwStyleCache* &rpCache = eFamily == IStyleAccess::AUTO_STYLE_CHAR ?
mpCharCache : mpParaCache;
if( !rpCache )
rpCache = new SwStyleCache();
rpCache->addStyleName( pStyle );
return pStyle;
}
StylePool::SfxItemSet_Pointer_t SwStyleManager::getByName( const rtl::OUString& rName,
IStyleAccess::SwAutoStyleFamily eFamily )
{
StylePool& rAutoPool = eFamily == IStyleAccess::AUTO_STYLE_CHAR ? aAutoCharPool : aAutoParaPool;
SwStyleCache* &rpCache = eFamily == IStyleAccess::AUTO_STYLE_CHAR ? mpCharCache : mpParaCache;
if( !rpCache )
rpCache = new SwStyleCache();
StylePool::SfxItemSet_Pointer_t pStyle = rpCache->getByName( rName );
if( !pStyle.get() )
{
// Ok, ok, it's allowed to ask for uncached styles (from UNO) but it should not be done
// during loading a document
ASSERT( false, "Don't ask for uncached styles" );
rpCache->addCompletePool( rAutoPool );
pStyle = rpCache->getByName( rName );
}
return pStyle;
}
void SwStyleManager::getAllStyles( std::vector<StylePool::SfxItemSet_Pointer_t> &rStyles,
IStyleAccess::SwAutoStyleFamily eFamily )
{
StylePool& rAutoPool = eFamily == IStyleAccess::AUTO_STYLE_CHAR ? aAutoCharPool : aAutoParaPool;
IStylePoolIteratorAccess *pIter = rAutoPool.createIterator();
StylePool::SfxItemSet_Pointer_t pStyle = pIter->getNext();
while( pStyle.get() )
{
// Do not consider styles which aren't used.
if ( pStyle.use_count() > 2 )
rStyles.push_back( pStyle );
pStyle = pIter->getNext();
}
delete pIter;
}
<commit_msg>INTEGRATION: CWS mingwport06 (1.3.358); FILE MERGED 2007/08/24 13:25:59 vg 1.3.358.1: #i75499# pragma is for MSVC<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: swstylemanager.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: kz $ $Date: 2007-09-06 14:00:34 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"
#ifdef _MSC_VER
#pragma hdrstop
#endif
#include "swstylemanager.hxx"
#include <hash_map>
#include <svtools/stylepool.hxx>
#ifndef _DOC_HXX
#include <doc.hxx>
#endif
#ifndef _CHARFMT_HXX
#include <charfmt.hxx>
#endif
#ifndef _DOCARY_HXX
#include <docary.hxx>
#endif
#ifndef _SWTYPES_HXX
#include <swtypes.hxx>
#endif
#ifndef _ISTYLEACCESS_HXX
#include <istyleaccess.hxx>
#endif
typedef ::std::hash_map< const ::rtl::OUString,
StylePool::SfxItemSet_Pointer_t,
::rtl::OUStringHash,
::std::equal_to< ::rtl::OUString > > SwStyleNameCache;
class SwStyleCache
{
SwStyleNameCache mMap;
public:
SwStyleCache() {}
void addStyleName( StylePool::SfxItemSet_Pointer_t pStyle )
{ mMap[ StylePool::nameOf(pStyle) ] = pStyle; }
void addCompletePool( StylePool& rPool );
StylePool::SfxItemSet_Pointer_t getByName( const rtl::OUString& rName ) { return mMap[rName]; }
};
void SwStyleCache::addCompletePool( StylePool& rPool )
{
IStylePoolIteratorAccess *pIter = rPool.createIterator();
StylePool::SfxItemSet_Pointer_t pStyle = pIter->getNext();
while( pStyle.get() )
{
rtl::OUString aName( StylePool::nameOf(pStyle) );
mMap[ aName ] = pStyle;
pStyle = pIter->getNext();
}
delete pIter;
}
class SwStyleManager : public IStyleAccess
{
StylePool aAutoCharPool;
StylePool aAutoParaPool;
SwStyleCache *mpCharCache;
SwStyleCache *mpParaCache;
public:
SwStyleManager() : mpCharCache(0), mpParaCache(0) {}
virtual ~SwStyleManager();
virtual StylePool::SfxItemSet_Pointer_t getAutomaticStyle( const SfxItemSet& rSet,
IStyleAccess::SwAutoStyleFamily eFamily );
virtual StylePool::SfxItemSet_Pointer_t getByName( const rtl::OUString& rName,
IStyleAccess::SwAutoStyleFamily eFamily );
virtual void getAllStyles( std::vector<StylePool::SfxItemSet_Pointer_t> &rStyles,
IStyleAccess::SwAutoStyleFamily eFamily );
virtual StylePool::SfxItemSet_Pointer_t cacheAutomaticStyle( const SfxItemSet& rSet,
SwAutoStyleFamily eFamily );
virtual void clearCaches();
};
IStyleAccess *createStyleManager()
{
return new SwStyleManager();
}
SwStyleManager::~SwStyleManager()
{
delete mpCharCache;
delete mpParaCache;
}
void SwStyleManager::clearCaches()
{
delete mpCharCache;
mpCharCache = 0;
delete mpParaCache;
mpParaCache = 0;
}
StylePool::SfxItemSet_Pointer_t SwStyleManager::getAutomaticStyle( const SfxItemSet& rSet,
IStyleAccess::SwAutoStyleFamily eFamily )
{
StylePool& rAutoPool = eFamily == IStyleAccess::AUTO_STYLE_CHAR ? aAutoCharPool : aAutoParaPool;
return rAutoPool.insertItemSet( rSet );
}
StylePool::SfxItemSet_Pointer_t SwStyleManager::cacheAutomaticStyle( const SfxItemSet& rSet,
IStyleAccess::SwAutoStyleFamily eFamily )
{
StylePool& rAutoPool = eFamily == IStyleAccess::AUTO_STYLE_CHAR ? aAutoCharPool : aAutoParaPool;
StylePool::SfxItemSet_Pointer_t pStyle = rAutoPool.insertItemSet( rSet );
SwStyleCache* &rpCache = eFamily == IStyleAccess::AUTO_STYLE_CHAR ?
mpCharCache : mpParaCache;
if( !rpCache )
rpCache = new SwStyleCache();
rpCache->addStyleName( pStyle );
return pStyle;
}
StylePool::SfxItemSet_Pointer_t SwStyleManager::getByName( const rtl::OUString& rName,
IStyleAccess::SwAutoStyleFamily eFamily )
{
StylePool& rAutoPool = eFamily == IStyleAccess::AUTO_STYLE_CHAR ? aAutoCharPool : aAutoParaPool;
SwStyleCache* &rpCache = eFamily == IStyleAccess::AUTO_STYLE_CHAR ? mpCharCache : mpParaCache;
if( !rpCache )
rpCache = new SwStyleCache();
StylePool::SfxItemSet_Pointer_t pStyle = rpCache->getByName( rName );
if( !pStyle.get() )
{
// Ok, ok, it's allowed to ask for uncached styles (from UNO) but it should not be done
// during loading a document
ASSERT( false, "Don't ask for uncached styles" );
rpCache->addCompletePool( rAutoPool );
pStyle = rpCache->getByName( rName );
}
return pStyle;
}
void SwStyleManager::getAllStyles( std::vector<StylePool::SfxItemSet_Pointer_t> &rStyles,
IStyleAccess::SwAutoStyleFamily eFamily )
{
StylePool& rAutoPool = eFamily == IStyleAccess::AUTO_STYLE_CHAR ? aAutoCharPool : aAutoParaPool;
IStylePoolIteratorAccess *pIter = rAutoPool.createIterator();
StylePool::SfxItemSet_Pointer_t pStyle = pIter->getNext();
while( pStyle.get() )
{
// Do not consider styles which aren't used.
if ( pStyle.use_count() > 2 )
rStyles.push_back( pStyle );
pStyle = pIter->getNext();
}
delete pIter;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: staticassert.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2005-09-09 06:05:02 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil -*- */
#ifndef WW_STATICASSERT_HXX
#define WW_STATICASSERT_HXX
/*
Lifted direct from:
Modern C++ Design: Generic Programming and Design Patterns Applied
Section 2.1
by Andrei Alexandrescu
*/
namespace ww
{
template<bool> class compile_time_check
{
public:
compile_time_check(...) {}
};
template<> class compile_time_check<false>
{
};
}
/*
Similiar to assert, StaticAssert is only in operation when NDEBUG is not
defined. It will test its first argument at compile time and on failure
report the error message of the second argument, which must be a valid c++
classname. i.e. no spaces, punctuation or reserved keywords.
*/
#ifndef NDEBUG
# define StaticAssert(test, errormsg) \
do { \
struct ERROR_##errormsg {}; \
typedef ww::compile_time_check< (test) != 0 > tmplimpl; \
tmplimpl aTemp = tmplimpl(ERROR_##errormsg()); \
sizeof(aTemp); \
} while (0)
#else
# define StaticAssert(test, errormsg) \
do {} while (0)
#endif
#endif
/* vi:set tabstop=4 shiftwidth=4 expandtab: */
<commit_msg>INTEGRATION: CWS thaiissues (1.4.888); FILE MERGED<commit_after>/*************************************************************************
*
* $RCSfile: staticassert.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: obo $ $Date: 2005-11-16 09:33:33 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil -*- */
#ifndef WW_STATICASSERT_HXX
#define WW_STATICASSERT_HXX
/*
Lifted direct from:
Modern C++ Design: Generic Programming and Design Patterns Applied
Section 2.1
by Andrei Alexandrescu
*/
namespace ww
{
template<bool> class compile_time_check
{
public:
compile_time_check(...) {}
};
template<> class compile_time_check<false>
{
};
}
/*
Similiar to assert, StaticAssert is only in operation when NDEBUG is not
defined. It will test its first argument at compile time and on failure
report the error message of the second argument, which must be a valid c++
classname. i.e. no spaces, punctuation or reserved keywords.
*/
#ifndef NDEBUG
# define StaticAssert(test, errormsg) \
do { \
struct ERROR_##errormsg {}; \
typedef ww::compile_time_check< (test) != 0 > tmplimpl; \
tmplimpl aTemp = tmplimpl(ERROR_##errormsg()); \
sizeof(aTemp); \
} while (0)
#else
# define StaticAssert(test, errormsg) \
do {} while (0)
#endif
#endif
/* vi:set tabstop=4 shiftwidth=4 expandtab: */
<|endoftext|> |
<commit_before>// RUN: %clang_cc1 -triple %itanium_abi_triple -verify -fsyntax-only -Wsign-conversion %s
// NOTE: When a 'enumeral mismatch' warning is implemented then expect several
// of the following cases to be impacted.
// namespace for anonymous enums tests
namespace test1 {
enum { A };
enum { B = -1 };
template <typename T> struct Foo {
enum { C };
enum { D = ~0U };
};
enum { E = ~0U };
void doit_anonymous( int i ) {
int a1 = 1 ? i : A;
int a2 = 1 ? A : i;
int b1 = 1 ? i : B;
int b2 = 1 ? B : i;
int c1 = 1 ? i : Foo<bool>::C;
int c2 = 1 ? Foo<bool>::C : i;
int d1a = 1 ? i : Foo<bool>::D; // expected-warning {{test1::Foo<bool>::(anonymous enum at }}
int d1b = 1 ? i : Foo<bool>::D; // expected-warning {{warn-sign-conversion.cpp:13:5)' to 'int'}}
int d2a = 1 ? Foo<bool>::D : i; // expected-warning {{operand of ? changes signedness: 'test1::Foo<bool>::(anonymous enum at }}
int d2b = 1 ? Foo<bool>::D : i; // expected-warning {{warn-sign-conversion.cpp:13:5)' to 'int'}}
int d3a = 1 ? B : Foo<bool>::D; // expected-warning {{operand of ? changes signedness: 'test1::Foo<bool>::(anonymous enum at }}
int d3b = 1 ? B : Foo<bool>::D; // expected-warning {{warn-sign-conversion.cpp:13:5)' to 'int'}}
int d4a = 1 ? Foo<bool>::D : B; // expected-warning {{operand of ? changes signedness: 'test1::Foo<bool>::(anonymous enum at }}
int d4b = 1 ? Foo<bool>::D : B; // expected-warning {{warn-sign-conversion.cpp:13:5)' to 'int'}}
int e1a = 1 ? i : E; // expected-warning {{operand of ? changes signedness: 'test1::(anonymous enum at }}
int e1b = 1 ? i : E; // expected-warning {{warn-sign-conversion.cpp:16:3)' to 'int'}}
int e2a = 1 ? E : i; // expected-warning {{operand of ? changes signedness: 'test1::(anonymous enum at }}
int e2b = 1 ? E : i; // expected-warning {{warn-sign-conversion.cpp:16:3)' to 'int'}}
int e3a = 1 ? E : B; // expected-warning {{operand of ? changes signedness: 'test1::(anonymous enum at }}
int e3b = 1 ? E : B; // expected-warning {{warn-sign-conversion.cpp:16:3)' to 'int'}}
int e4a = 1 ? B : E; // expected-warning {{operand of ? changes signedness: 'test1::(anonymous enum at }}
int e4b = 1 ? B : E; // expected-warning {{warn-sign-conversion.cpp:16:3)' to 'int'}}
}
}
// namespace for named enums tests
namespace test2 {
enum Named1 { A };
enum Named2 { B = -1 };
template <typename T> struct Foo {
enum Named3 { C };
enum Named4 { D = ~0U };
};
enum Named5 { E = ~0U };
void doit_anonymous( int i ) {
int a1 = 1 ? i : A;
int a2 = 1 ? A : i;
int b1 = 1 ? i : B;
int b2 = 1 ? B : i;
int c1 = 1 ? i : Foo<bool>::C;
int c2 = 1 ? Foo<bool>::C : i;
int d1 = 1 ? i : Foo<bool>::D; // expected-warning {{operand of ? changes signedness: 'test2::Foo<bool>::Named4' to 'int'}}
int d2 = 1 ? Foo<bool>::D : i; // expected-warning {{operand of ? changes signedness: 'test2::Foo<bool>::Named4' to 'int'}}
int d3 = 1 ? B : Foo<bool>::D; // expected-warning {{operand of ? changes signedness: 'test2::Foo<bool>::Named4' to 'int'}}
int d4 = 1 ? Foo<bool>::D : B; // expected-warning {{operand of ? changes signedness: 'test2::Foo<bool>::Named4' to 'int'}}
int e1 = 1 ? i : E; // expected-warning {{operand of ? changes signedness: 'test2::Named5' to 'int'}}
int e2 = 1 ? E : i; // expected-warning {{operand of ? changes signedness: 'test2::Named5' to 'int'}}
int e3 = 1 ? E : B; // expected-warning {{operand of ? changes signedness: 'test2::Named5' to 'int'}}
int e4 = 1 ? B : E; // expected-warning {{operand of ? changes signedness: 'test2::Named5' to 'int'}}
}
}
<commit_msg>[NFCI] Updated broken test<commit_after>// RUN: %clang_cc1 -triple %itanium_abi_triple -verify -fsyntax-only -Wsign-conversion %s
// NOTE: When a 'enumeral mismatch' warning is implemented then expect several
// of the following cases to be impacted.
// namespace for anonymous enums tests
namespace test1 {
enum { A };
enum { B = -1 };
template <typename T> struct Foo {
enum { C };
enum { D = ~0U };
};
enum { E = ~0U };
void doit_anonymous( int i ) {
int a1 = 1 ? i : A;
int a2 = 1 ? A : i;
int b1 = 1 ? i : B;
int b2 = 1 ? B : i;
int c1 = 1 ? i : Foo<bool>::C;
int c2 = 1 ? Foo<bool>::C : i;
int d1a = 1 ? i : Foo<bool>::D; // expected-warning {{test1::Foo<bool>::(anonymous enum at }}
int d1b = 1 ? i : Foo<bool>::D; // expected-warning {{warn-sign-conversion.cpp:13:5)' to 'int'}}
int d2a = 1 ? Foo<bool>::D : i; // expected-warning {{operand of ? changes signedness: 'test1::Foo<bool>::(anonymous enum at }}
int d2b = 1 ? Foo<bool>::D : i; // expected-warning {{warn-sign-conversion.cpp:13:5)' to 'int'}}
int d3a = 1 ? B : Foo<bool>::D; // expected-warning {{operand of ? changes signedness: 'test1::Foo<bool>::(anonymous enum at }}
int d3b = 1 ? B : Foo<bool>::D; // expected-warning {{warn-sign-conversion.cpp:13:5)' to 'int'}}
int d4a = 1 ? Foo<bool>::D : B; // expected-warning {{operand of ? changes signedness: 'test1::Foo<bool>::(anonymous enum at }}
int d4b = 1 ? Foo<bool>::D : B; // expected-warning {{warn-sign-conversion.cpp:13:5)' to 'int'}}
int e1a = 1 ? i : E; // expected-warning {{operand of ? changes signedness: 'test1::(anonymous enum at }}
int e1b = 1 ? i : E; // expected-warning {{warn-sign-conversion.cpp:16:3)' to 'int'}}
int e2a = 1 ? E : i; // expected-warning {{operand of ? changes signedness: 'test1::(anonymous enum at }}
int e2b = 1 ? E : i; // expected-warning {{warn-sign-conversion.cpp:16:3)' to 'int'}}
int e3a = 1 ? E : B; // expected-warning {{operand of ? changes signedness: 'test1::(anonymous enum at }}
int e3b = 1 ? E : B; // expected-warning {{warn-sign-conversion.cpp:16:3)' to 'int'}}
int e4a = 1 ? B : E; // expected-warning {{operand of ? changes signedness: 'test1::(anonymous enum at }}
int e4b = 1 ? B : E; // expected-warning {{warn-sign-conversion.cpp:16:3)' to 'int'}}
}
}
// namespace for named enums tests
namespace test2 {
enum Named1 { A };
enum Named2 { B = -1 };
template <typename T> struct Foo {
enum Named3 { C };
enum Named4 { D = ~0U };
};
enum Named5 { E = ~0U };
void doit_anonymous( int i ) {
int a1 = 1 ? i : A;
int a2 = 1 ? A : i;
int b1 = 1 ? i : B;
int b2 = 1 ? B : i;
int c1 = 1 ? i : Foo<bool>::C;
int c2 = 1 ? Foo<bool>::C : i;
int d1 = 1 ? i : Foo<bool>::D; // expected-warning {{operand of ? changes signedness: 'test2::Foo<bool>::Named4' to 'int'}}
int d2 = 1 ? Foo<bool>::D : i; // expected-warning {{operand of ? changes signedness: 'test2::Foo<bool>::Named4' to 'int'}}
int d3 = 1 ? B : Foo<bool>::D; // expected-warning {{operand of ? changes signedness: 'test2::Foo<bool>::Named4' to 'int'}}
// expected-warning@+1 {{enumeration type mismatch in conditional expression ('test2::Named2' and 'test2::Foo<bool>::Named4')}}
int d4 = 1 ? Foo<bool>::D : B; // expected-warning {{operand of ? changes signedness: 'test2::Foo<bool>::Named4' to 'int'}}
// expected-warning@+1 {{enumeration type mismatch in conditional expression ('test2::Foo<bool>::Named4' and 'test2::Named2')}}
int e1 = 1 ? i : E; // expected-warning {{operand of ? changes signedness: 'test2::Named5' to 'int'}}
int e2 = 1 ? E : i; // expected-warning {{operand of ? changes signedness: 'test2::Named5' to 'int'}}
int e3 = 1 ? E : B; // expected-warning {{operand of ? changes signedness: 'test2::Named5' to 'int'}}
// expected-warning@+1 {{enumeration type mismatch in conditional expression ('test2::Named5' and 'test2::Named2')}}
int e4 = 1 ? B : E; // expected-warning {{operand of ? changes signedness: 'test2::Named5' to 'int'}}
// expected-warning@+1 {{enumeration type mismatch in conditional expression ('test2::Named2' and 'test2::Named5')}}
}
}
<|endoftext|> |
<commit_before>#include <utility>
#include <type_traits>
#if __cpp_deduction_guides
#else
#error "Class Template Argument Deduction is not supported by the compiler"
#endif
template<typename A, typename B>
struct MyPair
{
MyPair(const A &, const B &)
{
}
};
template<int Size>
struct StaticString
{
StaticString(const char (&str)[Size]): c_str(str)
{
}
const char *c_str;
};
template<typename T>
struct Container
{
struct Iterator
{
using value_type = T;
};
template<typename It>
Container( It begin, It end )
{
}
};
// Class Template Argument Deduction guide (must be outside the class, in the same namespace).
template<typename It>
Container(It begin, It end) ->Container<typename It::value_type>;
template<typename A, typename B>
struct MyPerfectPair
{
// perfect forwarding like
template<typename U, typename V>
MyPerfectPair(U &&, V &&)
{
}
};
/**
* // CTAD guide, signature does not need to match.
*
* Use "decay by value" trick.
*
* Takes by value to partially simulate decay. See https://youtu.be/-H-ut6j1BYU?list=PLHTh1InhhwT6V9RVdFRoCG_Pm5udDxG1c&t=1987
*
* CTAD signature does not impact with ctor parameter overload resolution. It will be done as usual, but in the context of type MyPerfectPair<A,B>.
*/
template<typename A, typename B>
MyPerfectPair(A, B) -> MyPerfectPair<A, B>;
void typeTracer(int x)
{
}
int main()
{
// CTAG automatically deduce template argument type based on constructor parameters
MyPair p1{ 1729, 3.14 };
StaticString s1{ "hello" };
// typeTracer(s1);
static_assert( std::is_same_v<decltype(s1), StaticString<6>> );
Container<int>::Iterator it;
Container cont{ it, it }; // using CTAD deduction guide
int i1 = 12;
double d2 = 3.4;
MyPerfectPair p2{ std::move(i1), std::move(d2) };
static_assert(std::is_same_v<decltype(p2), MyPerfectPair<int, double>>);
return 0;
}<commit_msg>More CTAD example.<commit_after>#include <utility>
#include <type_traits>
#if __cpp_deduction_guides
#else
#error "Class Template Argument Deduction is not supported by the compiler"
#endif
template<typename A, typename B>
struct MyPair
{
MyPair(const A &, const B &)
{
}
};
template<int Size>
struct StaticString
{
StaticString(const char (&str)[Size]): c_str(str)
{
}
const char *c_str;
};
template<typename T>
struct Container
{
struct Iterator
{
using value_type = T;
};
template<typename It>
Container( It begin, It end )
{
}
};
// Class Template Argument Deduction guide (must be outside the class, in the same namespace).
template<typename It>
Container(It begin, It end) ->Container<typename It::value_type>;
template<typename A, typename B>
struct MyPerfectPair
{
// perfect forwarding like
template<typename U, typename V>
MyPerfectPair(U &&, V &&)
{
}
};
/**
* // CTAD guide, signature does not need to match.
*
* Use "decay by value" trick.
*
* Takes by value to partially simulate decay. See https://youtu.be/-H-ut6j1BYU?list=PLHTh1InhhwT6V9RVdFRoCG_Pm5udDxG1c&t=1987
*
* CTAD signature does not impact with ctor parameter overload resolution. It will be done as usual, but in the context of type MyPerfectPair<A,B>.
*/
template<typename A, typename B>
MyPerfectPair(A, B) -> MyPerfectPair<A, B>;
void typeTracer(int x)
{
}
int main()
{
// CTAG automatically deduce template argument type based on constructor parameters
MyPair p1{ 1729, 3.14 };
StaticString s1{ "hello" };
// typeTracer(s1);
static_assert( std::is_same_v<decltype(s1), StaticString<6>> );
MyPair p1b{ 1729, "hello" };
static_assert(std::is_same_v<decltype(p1b), MyPair<int, char[6]>>);// watch out, not const char
Container<int>::Iterator it;
Container cont{ it, it }; // using CTAD deduction guide
int i1 = 12;
double d2 = 3.4;
MyPerfectPair p2{ std::move(i1), std::move(d2) };
static_assert(std::is_same_v<decltype(p2), MyPerfectPair<int, double>>);
return 0;
}<|endoftext|> |
<commit_before>#pragma once
#include <cfloat>
#include <cstdint>
#include <string>
#include "gmock/gmock.h"
#include "quantities/quantities.hpp"
namespace principia {
namespace testing_utilities {
template<typename T>
class VanishesBeforeMatcher;
// The matchers below are useful when a computation gives a result whose
// expected value is zero. Because of cancellations it is unlikely that the
// computed value is exactly zero. The matchers take a reference value, which
// represents the order of magnitude of the intermediate results that triggered
// the cancellation, and a tolerance expressed as a number of ulps in the
// error. More precisely the matcher checks that the |reference| is equal to
// to |actual + reference| to within the specified number of ulps.
// The 2-argument version of |VanishesBefore()| should always be preferred as it
// guarantees that the error bound is tight.
template<typename T>
testing::PolymorphicMatcher<VanishesBeforeMatcher<T>> VanishesBefore(
T const& reference,
std::int64_t const max_ulps);
// The 3-argument version of |VanishesBefore()| is exclusively for use when a
// given assertion may have different errors, e.g., because it's in a loop. It
// doesn't guarantee that the error bound is tight.
template<typename T>
testing::PolymorphicMatcher<VanishesBeforeMatcher<T>> VanishesBefore(
T const& reference,
std::int64_t const min_ulps,
std::int64_t const max_ulps);
template<typename T>
class VanishesBeforeMatcher{
public:
explicit VanishesBeforeMatcher(T const& reference,
std::int64_t const min_ulps,
std::int64_t const max_ulps);
~VanishesBeforeMatcher() = default;
template<typename Dimensions>
bool MatchAndExplain(quantities::Quantity<Dimensions> const& actual,
testing::MatchResultListener* listener) const;
bool MatchAndExplain(double const actual,
testing::MatchResultListener* listener) const;
void DescribeTo(std::ostream* out) const;
void DescribeNegationTo(std::ostream* out) const;
private:
T const reference_;
std::int64_t const min_ulps_;
std::int64_t const max_ulps_;
};
} // namespace testing_utilities
} // namespace principia
#include "testing_utilities/vanishes_before_body.hpp"
<commit_msg>Un p'tit blanc sec.<commit_after>#pragma once
#include <cfloat>
#include <cstdint>
#include <string>
#include "gmock/gmock.h"
#include "quantities/quantities.hpp"
namespace principia {
namespace testing_utilities {
template<typename T>
class VanishesBeforeMatcher;
// The matchers below are useful when a computation gives a result whose
// expected value is zero. Because of cancellations it is unlikely that the
// computed value is exactly zero. The matchers take a reference value, which
// represents the order of magnitude of the intermediate results that triggered
// the cancellation, and a tolerance expressed as a number of ulps in the
// error. More precisely the matcher checks that the |reference| is equal to
// to |actual + reference| to within the specified number of ulps.
// The 2-argument version of |VanishesBefore()| should always be preferred as it
// guarantees that the error bound is tight.
template<typename T>
testing::PolymorphicMatcher<VanishesBeforeMatcher<T>> VanishesBefore(
T const& reference,
std::int64_t const max_ulps);
// The 3-argument version of |VanishesBefore()| is exclusively for use when a
// given assertion may have different errors, e.g., because it's in a loop. It
// doesn't guarantee that the error bound is tight.
template<typename T>
testing::PolymorphicMatcher<VanishesBeforeMatcher<T>> VanishesBefore(
T const& reference,
std::int64_t const min_ulps,
std::int64_t const max_ulps);
template<typename T>
class VanishesBeforeMatcher {
public:
explicit VanishesBeforeMatcher(T const& reference,
std::int64_t const min_ulps,
std::int64_t const max_ulps);
~VanishesBeforeMatcher() = default;
template<typename Dimensions>
bool MatchAndExplain(quantities::Quantity<Dimensions> const& actual,
testing::MatchResultListener* listener) const;
bool MatchAndExplain(double const actual,
testing::MatchResultListener* listener) const;
void DescribeTo(std::ostream* out) const;
void DescribeNegationTo(std::ostream* out) const;
private:
T const reference_;
std::int64_t const min_ulps_;
std::int64_t const max_ulps_;
};
} // namespace testing_utilities
} // namespace principia
#include "testing_utilities/vanishes_before_body.hpp"
<|endoftext|> |
<commit_before>#include "../../src/common/problem_definition.h"
#include "../test_utilities.h"
void setup_parameters (dealii::ParameterHandler &prm)
{
// set entry values for those without default input
prm.set ("reflective boundary names", "xmin");
prm.set ("x, y, z max values of boundary locations", "1.0, 2.0");
prm.set ("number of cells for x, y, z directions", "1, 3");
}
void find_errors (dealii::ParameterHandler &prm)
{
// dealii::ExcInternalError() is used to indicate expected
// condition is not satisfied.
AssertThrow (prm.get_integer("problem dimension")==2,
dealii::ExcInternalError());
AssertThrow (prm.get("transport model")=="none", dealii::ExcInternalError());
AssertThrow (prm.get("HO linear solver name")=="cg",
dealii::ExcInternalError());
AssertThrow (prm.get("HO preconditioner name")=="amg",
dealii::ExcInternalError());
AssertThrow (prm.get_double("HO ssor factor")==1.0,
dealii::ExcInternalError());
AssertThrow (prm.get("NDA linear solver name")=="none",
dealii::ExcInternalError());
AssertThrow (prm.get("NDA preconditioner name")=="none",
dealii::ExcInternalError());
AssertThrow (prm.get_double("NDA ssor factor")==1.0,
dealii::ExcInternalError());
AssertThrow (prm.get("angular quadrature name")=="none",
dealii::ExcInternalError());
AssertThrow (prm.get_integer("angular quadrature order")==4,
dealii::ExcInternalError());
AssertThrow (prm.get_integer("number of groups")==1,
dealii::ExcInternalError());
AssertThrow (prm.get_integer("thermal group boundary")==0,
dealii::ExcInternalError());
AssertThrow (prm.get("spatial discretization")=="cfem",
dealii::ExcInternalError());
AssertThrow (prm.get_bool("do eigenvalue calculations")==false,
dealii::ExcInternalError());
AssertThrow (prm.get_bool("do NDA")==false, dealii::ExcInternalError());
AssertThrow (prm.get_bool("have reflective BC")==false,
dealii::ExcInternalError());
AssertThrow (prm.get("reflective boundary names")=="xmin",
dealii::ExcInternalError());
AssertThrow (prm.get_integer("finite element polynomial degree")==1,
dealii::ExcInternalError());
AssertThrow (prm.get_integer("uniform refinements")==0,
dealii::ExcInternalError());
AssertThrow (prm.get("x, y, z max values of boundary locations")=="1.0, 2.0",
dealii::ExcInternalError());
AssertThrow (prm.get("number of cells for x, y, z directions")=="1, 3",
dealii::ExcInternalError());
AssertThrow (prm.get_integer("number of materials")==1,
dealii::ExcInternalError());
AssertThrow (prm.get_bool("do print angular quadrature info")==true,
dealii::ExcInternalError());
AssertThrow (prm.get_bool("is mesh generated by deal.II")==true,
dealii::ExcInternalError());
AssertThrow (prm.get("output file name base")=="solu",
dealii::ExcInternalError());
AssertThrow (prm.get("mesh file name")=="mesh.msh",
dealii::ExcInternalError());
}
void test (dealii::ParameterHandler &prm)
{
// purpose of this test is to see whether parameters
// are parsed correctly
ProblemDefinition::declare_parameters (prm);
setup_parameters (prm);
find_errors (prm);
dealii::deallog << "OK" << std::endl;
}
int main ()
{
dealii::ParameterHandler prm;
testing::init_log ();
test (prm);
return 0;
}
<commit_msg>Modified ProblemDefinition test w/ GGL style #61<commit_after>#include "../../src/common/problem_definition.h"
#include "../test_utilities.h"
void SetupParameters (dealii::ParameterHandler &prm)
{
// set entry values for those without default input
prm.set ("reflective boundary names", "xmin");
prm.set ("x, y, z max values of boundary locations", "1.0, 2.0");
prm.set ("number of cells for x, y, z directions", "1, 3");
}
void FindErrors (dealii::ParameterHandler &prm)
{
// dealii::ExcInternalError() is used to indicate expected
// condition is not satisfied.
AssertThrow (prm.get_integer("problem dimension")==2,
dealii::ExcInternalError());
AssertThrow (prm.get("transport model")=="none", dealii::ExcInternalError());
AssertThrow (prm.get("HO linear solver name")=="cg",
dealii::ExcInternalError());
AssertThrow (prm.get("HO preconditioner name")=="amg",
dealii::ExcInternalError());
AssertThrow (prm.get_double("HO ssor factor")==1.0,
dealii::ExcInternalError());
AssertThrow (prm.get("NDA linear solver name")=="none",
dealii::ExcInternalError());
AssertThrow (prm.get("NDA preconditioner name")=="none",
dealii::ExcInternalError());
AssertThrow (prm.get_double("NDA ssor factor")==1.0,
dealii::ExcInternalError());
AssertThrow (prm.get("angular quadrature name")=="none",
dealii::ExcInternalError());
AssertThrow (prm.get_integer("angular quadrature order")==4,
dealii::ExcInternalError());
AssertThrow (prm.get_integer("number of groups")==1,
dealii::ExcInternalError());
AssertThrow (prm.get_integer("thermal group boundary")==0,
dealii::ExcInternalError());
AssertThrow (prm.get("spatial discretization")=="cfem",
dealii::ExcInternalError());
AssertThrow (prm.get_bool("do eigenvalue calculations")==false,
dealii::ExcInternalError());
AssertThrow (prm.get_bool("do NDA")==false, dealii::ExcInternalError());
AssertThrow (prm.get_bool("have reflective BC")==false,
dealii::ExcInternalError());
AssertThrow (prm.get("reflective boundary names")=="xmin",
dealii::ExcInternalError());
AssertThrow (prm.get_integer("finite element polynomial degree")==1,
dealii::ExcInternalError());
AssertThrow (prm.get_integer("uniform refinements")==0,
dealii::ExcInternalError());
AssertThrow (prm.get("x, y, z max values of boundary locations")=="1.0, 2.0",
dealii::ExcInternalError());
AssertThrow (prm.get("number of cells for x, y, z directions")=="1, 3",
dealii::ExcInternalError());
AssertThrow (prm.get_integer("number of materials")==1,
dealii::ExcInternalError());
AssertThrow (prm.get_bool("do print angular quadrature info")==true,
dealii::ExcInternalError());
AssertThrow (prm.get_bool("is mesh generated by deal.II")==true,
dealii::ExcInternalError());
AssertThrow (prm.get("output file name base")=="solu",
dealii::ExcInternalError());
AssertThrow (prm.get("mesh file name")=="mesh.msh",
dealii::ExcInternalError());
}
void Test (dealii::ParameterHandler &prm)
{
// purpose of this test is to see whether parameters
// are parsed correctly
ProblemDefinition::DeclareParameters (prm);
SetupParameters (prm);
FindErrors (prm);
dealii::deallog << "OK" << std::endl;
}
int main ()
{
dealii::ParameterHandler prm;
testing::init_log ();
Test (prm);
return 0;
}
<|endoftext|> |
<commit_before>/*
This file is part of the kolab resource - the implementation of the
Kolab storage format. See www.kolab.org for documentation on this.
Copyright (c) 2004 Bo Thorsen <bo@klaralvdalens-datakonsult.se>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
In addition, as a special exception, the copyright holders give
permission to link the code of this program with any edition of
the Qt library by Trolltech AS, Norway (or with modified versions
of Qt that use the same license as Qt), and distribute linked
combinations including the two. You must obey the GNU General
Public License in all respects for all of the code used other than
Qt. If you modify this file, you may extend this exception to
your version of the file, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from
your version.
*/
#include "task.h"
#include <libkcal/todo.h>
#include <kdebug.h>
using namespace Kolab;
KCal::Todo* Task::xmlToTask( const QString& xml, const QString& tz )
{
Task task( tz );
task.load( xml );
KCal::Todo* todo = new KCal::Todo();
task.saveTo( todo );
return todo;
}
QString Task::taskToXML( KCal::Todo* todo, const QString& tz )
{
Task task( tz, todo );
return task.saveXML();
}
Task::Task( const QString& tz, KCal::Todo* task )
: Incidence( tz ), mPriority( 3 ), mPercentCompleted( 100 ),
mStatus( KCal::Incidence::StatusNone ),
mHasDueDate( false ), mHasCompletedDate( false )
{
if ( task )
setFields( task );
}
Task::~Task()
{
}
void Task::setPriority( int priority )
{
mPriority = priority;
}
int Task::priority() const
{
return mPriority;
}
void Task::setPercentCompleted( int percent )
{
mPercentCompleted = percent;
}
int Task::percentCompleted() const
{
return mPercentCompleted;
}
void Task::setStatus( KCal::Incidence::Status status )
{
mStatus = status;
}
KCal::Incidence::Status Task::status() const
{
return mStatus;
}
void Task::setParent( const QString& parentUid )
{
mParent = parentUid;
}
QString Task::parent() const
{
return mParent;
}
void Task::setDueDate( const QDateTime& date )
{
mDueDate = date;
mHasDueDate = true;
}
QDateTime Task::dueDate() const
{
return mDueDate;
}
bool Task::hasDueDate() const
{
return mHasDueDate;
}
void Task::setCompletedDate( const QDateTime& date )
{
mCompletedDate = date;
mHasCompletedDate = true;
}
QDateTime Task::completedDate() const
{
return mCompletedDate;
}
bool Task::hasCompletedDate() const
{
return mHasCompletedDate;
}
bool Task::loadAttribute( QDomElement& element )
{
QString tagName = element.tagName();
if ( tagName == "priority" ) {
bool ok;
int priority = element.text().toInt( &ok );
if ( !ok || priority < 0 || priority > 5 )
priority = 3;
setPriority( priority );
} else if ( tagName == "completed" ) {
bool ok;
int percent = element.text().toInt( &ok );
if ( !ok || percent < 0 || percent > 100 )
percent = 0;
setPercentCompleted( percent );
} else if ( tagName == "status" ) {
if ( element.text() == "in-progress" )
setStatus( KCal::Incidence::StatusInProcess );
else if ( element.text() == "completed" )
setStatus( KCal::Incidence::StatusCompleted );
else if ( element.text() == "waiting-on-someone-else" )
setStatus( KCal::Incidence::StatusNeedsAction );
else if ( element.text() == "deferred" )
// Guessing a status here
setStatus( KCal::Incidence::StatusCanceled );
else
// Default
setStatus( KCal::Incidence::StatusNone );
} else if ( tagName == "due-date" )
setDueDate( stringToDateTime( element.text() ) );
else if ( tagName == "parent" )
setParent( element.text() );
else if ( tagName == "x-completed-date" )
setCompletedDate( stringToDateTime( element.text() ) );
else
return Incidence::loadAttribute( element );
// We handled this
return true;
}
bool Task::saveAttributes( QDomElement& element ) const
{
// Save the base class elements
Incidence::saveAttributes( element );
writeString( element, "priority", QString::number( priority() ) );
writeString( element, "completed", QString::number( percentCompleted() ) );
switch( status() ) {
case KCal::Incidence::StatusInProcess:
writeString( element, "status", "in-progress" );
break;
case KCal::Incidence::StatusCompleted:
writeString( element, "status", "completed" );
break;
case KCal::Incidence::StatusNeedsAction:
writeString( element, "status", "waiting-on-someone-else" );
break;
case KCal::Incidence::StatusCanceled:
writeString( element, "status", "deferred" );
break;
case KCal::Incidence::StatusNone:
writeString( element, "status", "not-started" );
break;
case KCal::Incidence::StatusTentative:
case KCal::Incidence::StatusConfirmed:
case KCal::Incidence::StatusDraft:
case KCal::Incidence::StatusFinal:
case KCal::Incidence::StatusX:
// All of these are saved as StatusNone.
writeString( element, "status", "not-started" );
break;
}
if ( hasDueDate() )
writeString( element, "due-date", dateTimeToString( dueDate() ) );
if ( !parent().isNull() )
writeString( element, "parent", parent() );
if ( hasCompletedDate() )
writeString( element, "x-completed-date", dateTimeToString( completedDate() ) );
return true;
}
bool Task::loadXML( const QDomDocument& document )
{
QDomElement top = document.documentElement();
if ( top.tagName() != "task" ) {
qWarning( "XML error: Top tag was %s instead of the expected task",
top.tagName().ascii() );
return false;
}
for ( QDomNode n = top.firstChild(); !n.isNull(); n = n.nextSibling() ) {
if ( n.isComment() )
continue;
if ( n.isElement() ) {
QDomElement e = n.toElement();
if ( !loadAttribute( e ) )
// TODO: Unhandled tag - save for later storage
kdDebug() << "Warning: Unhandled tag " << e.tagName() << endl;
} else
kdDebug() << "Node is not a comment or an element???" << endl;
}
return true;
}
QString Task::saveXML() const
{
QDomDocument document = domTree();
QDomElement element = document.createElement( "task" );
element.setAttribute( "version", "1.0" );
saveAttributes( element );
document.appendChild( element );
return document.toString();
}
void Task::setFields( const KCal::Todo* task )
{
Incidence::setFields( task );
setPriority( task->priority() );
setPercentCompleted( task->percentComplete() );
setStatus( task->status() );
if ( task->hasDueDate() )
setDueDate( localToUTC( task->dtDue() ) );
else
mHasDueDate = false;
setParent( QString::null );
if ( task->hasCompletedDate() )
setCompletedDate( localToUTC( task->completed() ) );
else
mHasCompletedDate = false;
}
void Task::saveTo( KCal::Todo* task )
{
Incidence::saveTo( task );
task->setPriority( priority() );
task->setPercentComplete( percentCompleted() );
task->setStatus( status() );
task->setHasDueDate( hasDueDate() );
if ( hasDueDate() )
task->setDtDue( utcToLocal( dueDate() ) );
if ( parent() != QString::null )
task->setRelatedToUid( parent() );
if ( hasCompletedDate() )
task->setCompleted( utcToLocal( mCompletedDate ) );
}
<commit_msg>Save the parent of todos if they have one.<commit_after>/*
This file is part of the kolab resource - the implementation of the
Kolab storage format. See www.kolab.org for documentation on this.
Copyright (c) 2004 Bo Thorsen <bo@klaralvdalens-datakonsult.se>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
In addition, as a special exception, the copyright holders give
permission to link the code of this program with any edition of
the Qt library by Trolltech AS, Norway (or with modified versions
of Qt that use the same license as Qt), and distribute linked
combinations including the two. You must obey the GNU General
Public License in all respects for all of the code used other than
Qt. If you modify this file, you may extend this exception to
your version of the file, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from
your version.
*/
#include "task.h"
#include <libkcal/todo.h>
#include <kdebug.h>
using namespace Kolab;
KCal::Todo* Task::xmlToTask( const QString& xml, const QString& tz )
{
Task task( tz );
task.load( xml );
KCal::Todo* todo = new KCal::Todo();
task.saveTo( todo );
return todo;
}
QString Task::taskToXML( KCal::Todo* todo, const QString& tz )
{
Task task( tz, todo );
return task.saveXML();
}
Task::Task( const QString& tz, KCal::Todo* task )
: Incidence( tz ), mPriority( 3 ), mPercentCompleted( 100 ),
mStatus( KCal::Incidence::StatusNone ),
mHasDueDate( false ), mHasCompletedDate( false )
{
if ( task )
setFields( task );
}
Task::~Task()
{
}
void Task::setPriority( int priority )
{
mPriority = priority;
}
int Task::priority() const
{
return mPriority;
}
void Task::setPercentCompleted( int percent )
{
mPercentCompleted = percent;
}
int Task::percentCompleted() const
{
return mPercentCompleted;
}
void Task::setStatus( KCal::Incidence::Status status )
{
mStatus = status;
}
KCal::Incidence::Status Task::status() const
{
return mStatus;
}
void Task::setParent( const QString& parentUid )
{
mParent = parentUid;
}
QString Task::parent() const
{
return mParent;
}
void Task::setDueDate( const QDateTime& date )
{
mDueDate = date;
mHasDueDate = true;
}
QDateTime Task::dueDate() const
{
return mDueDate;
}
bool Task::hasDueDate() const
{
return mHasDueDate;
}
void Task::setCompletedDate( const QDateTime& date )
{
mCompletedDate = date;
mHasCompletedDate = true;
}
QDateTime Task::completedDate() const
{
return mCompletedDate;
}
bool Task::hasCompletedDate() const
{
return mHasCompletedDate;
}
bool Task::loadAttribute( QDomElement& element )
{
QString tagName = element.tagName();
if ( tagName == "priority" ) {
bool ok;
int priority = element.text().toInt( &ok );
if ( !ok || priority < 0 || priority > 5 )
priority = 3;
setPriority( priority );
} else if ( tagName == "completed" ) {
bool ok;
int percent = element.text().toInt( &ok );
if ( !ok || percent < 0 || percent > 100 )
percent = 0;
setPercentCompleted( percent );
} else if ( tagName == "status" ) {
if ( element.text() == "in-progress" )
setStatus( KCal::Incidence::StatusInProcess );
else if ( element.text() == "completed" )
setStatus( KCal::Incidence::StatusCompleted );
else if ( element.text() == "waiting-on-someone-else" )
setStatus( KCal::Incidence::StatusNeedsAction );
else if ( element.text() == "deferred" )
// Guessing a status here
setStatus( KCal::Incidence::StatusCanceled );
else
// Default
setStatus( KCal::Incidence::StatusNone );
} else if ( tagName == "due-date" )
setDueDate( stringToDateTime( element.text() ) );
else if ( tagName == "parent" )
setParent( element.text() );
else if ( tagName == "x-completed-date" )
setCompletedDate( stringToDateTime( element.text() ) );
else
return Incidence::loadAttribute( element );
// We handled this
return true;
}
bool Task::saveAttributes( QDomElement& element ) const
{
// Save the base class elements
Incidence::saveAttributes( element );
writeString( element, "priority", QString::number( priority() ) );
writeString( element, "completed", QString::number( percentCompleted() ) );
switch( status() ) {
case KCal::Incidence::StatusInProcess:
writeString( element, "status", "in-progress" );
break;
case KCal::Incidence::StatusCompleted:
writeString( element, "status", "completed" );
break;
case KCal::Incidence::StatusNeedsAction:
writeString( element, "status", "waiting-on-someone-else" );
break;
case KCal::Incidence::StatusCanceled:
writeString( element, "status", "deferred" );
break;
case KCal::Incidence::StatusNone:
writeString( element, "status", "not-started" );
break;
case KCal::Incidence::StatusTentative:
case KCal::Incidence::StatusConfirmed:
case KCal::Incidence::StatusDraft:
case KCal::Incidence::StatusFinal:
case KCal::Incidence::StatusX:
// All of these are saved as StatusNone.
writeString( element, "status", "not-started" );
break;
}
if ( hasDueDate() )
writeString( element, "due-date", dateTimeToString( dueDate() ) );
if ( !parent().isNull() )
writeString( element, "parent", parent() );
if ( hasCompletedDate() )
writeString( element, "x-completed-date", dateTimeToString( completedDate() ) );
return true;
}
bool Task::loadXML( const QDomDocument& document )
{
QDomElement top = document.documentElement();
if ( top.tagName() != "task" ) {
qWarning( "XML error: Top tag was %s instead of the expected task",
top.tagName().ascii() );
return false;
}
for ( QDomNode n = top.firstChild(); !n.isNull(); n = n.nextSibling() ) {
if ( n.isComment() )
continue;
if ( n.isElement() ) {
QDomElement e = n.toElement();
if ( !loadAttribute( e ) )
// TODO: Unhandled tag - save for later storage
kdDebug() << "Warning: Unhandled tag " << e.tagName() << endl;
} else
kdDebug() << "Node is not a comment or an element???" << endl;
}
return true;
}
QString Task::saveXML() const
{
QDomDocument document = domTree();
QDomElement element = document.createElement( "task" );
element.setAttribute( "version", "1.0" );
saveAttributes( element );
document.appendChild( element );
return document.toString();
}
void Task::setFields( const KCal::Todo* task )
{
Incidence::setFields( task );
setPriority( task->priority() );
setPercentCompleted( task->percentComplete() );
setStatus( task->status() );
if ( task->hasDueDate() )
setDueDate( localToUTC( task->dtDue() ) );
else
mHasDueDate = false;
if ( task->relatedTo() )
setParent( task->relatedTo()->uid() );
else
setParent( QString::null );
if ( task->hasCompletedDate() )
setCompletedDate( localToUTC( task->completed() ) );
else
mHasCompletedDate = false;
}
void Task::saveTo( KCal::Todo* task )
{
Incidence::saveTo( task );
task->setPriority( priority() );
task->setPercentComplete( percentCompleted() );
task->setStatus( status() );
task->setHasDueDate( hasDueDate() );
if ( hasDueDate() )
task->setDtDue( utcToLocal( dueDate() ) );
if ( parent() != QString::null )
task->setRelatedToUid( parent() );
if ( hasCompletedDate() )
task->setCompleted( utcToLocal( mCompletedDate ) );
}
<|endoftext|> |
<commit_before>// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at
// the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights
// reserved. See file COPYRIGHT for details.
//
// This file is part of the MFEM library. For more information and source code
// availability see http://mfem.org.
//
// MFEM 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) version 2.1 dated February 1999.
#include "mfem.hpp"
#include "catch.hpp"
#include <iostream>
#include <cmath>
using namespace mfem;
/**
* Utility function to generate IntegerationPoints, based on param ip
* that are outside the unit interval. Results are placed in output
* parameter arr.
*
* Note: this is defined in test_calcshape.cpp
*/
void GetRelatedIntegrationPoints(const IntegrationPoint& ip, int dim,
Array<IntegrationPoint>& arr);
/**
* Utility function to setup IsoparametricTransformations for reference
* elements of various types.
*
* Note: this is defined in test_calcvshape.cpp
*/
void GetReferenceTransformation(const Element::Type ElemType,
IsoparametricTransformation & T);
/**
* Linear test function whose curl is equal to 1 in 2D and (1,1,1) in 3D.
*/
void test_curl_func(const Vector &x, Vector &v)
{
int dim = x.Size();
v.SetSize(dim);
v[0] = 4.0 * x[1];
v[1] = 5.0 * x[0];
if (dim == 3)
{
v[0] += 3.0 * x[2];
v[1] += x[2];
v[2] = 2.0 * (x[0] + x[1]);
}
}
/**
* Tests fe->CalcCurlShape() over a grid of IntegrationPoints
* of resolution res. Also tests at integration points
* that are outside the element.
*/
void TestCalcCurlShape(FiniteElement* fe, ElementTransformation * T, int res)
{
int dof = fe->GetDof();
int dim = fe->GetDim();
int cdim = 2 * dim - 3;
Vector dofs(dof);
Vector v(cdim);
DenseMatrix weights( dof, cdim );
VectorFunctionCoefficient vCoef(dim, test_curl_func);
fe->Project(vCoef, *T, dofs);
// Get a uniform grid or integration points
RefinedGeometry* ref = GlobGeometryRefiner.Refine( fe->GetGeomType(), res);
const IntegrationRule& intRule = ref->RefPts;
int npoints = intRule.GetNPoints();
for (int i=0; i < npoints; ++i)
{
// Get the current integration point from intRule
IntegrationPoint pt = intRule.IntPoint(i);
// Get several variants of this integration point
// some of which are inside the element and some are outside
Array<IntegrationPoint> ipArr;
GetRelatedIntegrationPoints( pt, dim, ipArr );
// For each such integration point check that the weights
// from CalcCurlShape() sum to one
for (int j=0; j < ipArr.Size(); ++j)
{
IntegrationPoint& ip = ipArr[j];
fe->CalcCurlShape(ip, weights);
weights.MultTranspose(dofs, v);
REQUIRE( v[0] == Approx(1.) );
if (dim == 3)
{
REQUIRE( v[1] == Approx(1.) );
REQUIRE( v[2] == Approx(1.) );
}
}
}
}
TEST_CASE("CalcCurlShape for several ND FiniteElement instances",
"[ND_TriangleElement]"
"[ND_QuadrilateralElement]"
"[ND_TetrahedronElement]"
"[ND_WedgeElement]"
"[ND_HexahedronElement]")
{
int maxOrder = 5;
int resolution = 10;
SECTION("ND_TriangleElement")
{
IsoparametricTransformation T;
GetReferenceTransformation(Element::TRIANGLE, T);
for (int order =1; order <= maxOrder; ++order)
{
std::cout << "Testing ND_TriangleElement::CalcCurlShape() "
<< "for order " << order << std::endl;
ND_TriangleElement fe(order);
TestCalcCurlShape(&fe, &T, resolution);
}
}
SECTION("ND_QuadrilateralElement")
{
IsoparametricTransformation T;
GetReferenceTransformation(Element::QUADRILATERAL, T);
for (int order =1; order <= maxOrder; ++order)
{
std::cout << "Testing ND_QuadrilateralElement::CalcCurlShape() "
<< "for order " << order << std::endl;
ND_QuadrilateralElement fe(order);
TestCalcCurlShape(&fe, &T, resolution);
}
}
SECTION("ND_TetrahedronElement")
{
IsoparametricTransformation T;
GetReferenceTransformation(Element::TETRAHEDRON, T);
for (int order =1; order <= maxOrder; ++order)
{
std::cout << "Testing ND_TetrahedronElement::CalcCurlShape() "
<< "for order " << order << std::endl;
ND_TetrahedronElement fe(order);
TestCalcCurlShape(&fe, &T, resolution);
}
}
SECTION("ND_WedgeElement")
{
IsoparametricTransformation T;
GetReferenceTransformation(Element::WEDGE, T);
for (int order =1; order <= maxOrder; ++order)
{
std::cout << "Testing ND_WedgeElement::CalcCurlShape() "
<< "for order " << order << std::endl;
ND_WedgeElement fe(order);
TestCalcCurlShape(&fe, &T, resolution);
}
}
SECTION("ND_HexahedronElement")
{
IsoparametricTransformation T;
GetReferenceTransformation(Element::HEXAHEDRON, T);
for (int order =1; order <= maxOrder; ++order)
{
std::cout << "Testing ND_HexahedronElement::CalcCurlShape() "
<< "for order " << order << std::endl;
ND_HexahedronElement fe(order);
TestCalcCurlShape(&fe, &T, resolution);
}
}
}
<commit_msg>Partial copyright statement fix for testing<commit_after>// Copyright (c) 2010-2021, Lawrence Livermore National Security, LLC. Produced at
// the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights
// reserved. See file COPYRIGHT for details.
//
// This file is part of the MFEM library. For more information and source code
// availability see http://mfem.org.
//
// MFEM 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) version 2.1 dated February 1999.
#include "mfem.hpp"
#include "catch.hpp"
#include <iostream>
#include <cmath>
using namespace mfem;
/**
* Utility function to generate IntegerationPoints, based on param ip
* that are outside the unit interval. Results are placed in output
* parameter arr.
*
* Note: this is defined in test_calcshape.cpp
*/
void GetRelatedIntegrationPoints(const IntegrationPoint& ip, int dim,
Array<IntegrationPoint>& arr);
/**
* Utility function to setup IsoparametricTransformations for reference
* elements of various types.
*
* Note: this is defined in test_calcvshape.cpp
*/
void GetReferenceTransformation(const Element::Type ElemType,
IsoparametricTransformation & T);
/**
* Linear test function whose curl is equal to 1 in 2D and (1,1,1) in 3D.
*/
void test_curl_func(const Vector &x, Vector &v)
{
int dim = x.Size();
v.SetSize(dim);
v[0] = 4.0 * x[1];
v[1] = 5.0 * x[0];
if (dim == 3)
{
v[0] += 3.0 * x[2];
v[1] += x[2];
v[2] = 2.0 * (x[0] + x[1]);
}
}
/**
* Tests fe->CalcCurlShape() over a grid of IntegrationPoints
* of resolution res. Also tests at integration points
* that are outside the element.
*/
void TestCalcCurlShape(FiniteElement* fe, ElementTransformation * T, int res)
{
int dof = fe->GetDof();
int dim = fe->GetDim();
int cdim = 2 * dim - 3;
Vector dofs(dof);
Vector v(cdim);
DenseMatrix weights( dof, cdim );
VectorFunctionCoefficient vCoef(dim, test_curl_func);
fe->Project(vCoef, *T, dofs);
// Get a uniform grid or integration points
RefinedGeometry* ref = GlobGeometryRefiner.Refine( fe->GetGeomType(), res);
const IntegrationRule& intRule = ref->RefPts;
int npoints = intRule.GetNPoints();
for (int i=0; i < npoints; ++i)
{
// Get the current integration point from intRule
IntegrationPoint pt = intRule.IntPoint(i);
// Get several variants of this integration point
// some of which are inside the element and some are outside
Array<IntegrationPoint> ipArr;
GetRelatedIntegrationPoints( pt, dim, ipArr );
// For each such integration point check that the weights
// from CalcCurlShape() sum to one
for (int j=0; j < ipArr.Size(); ++j)
{
IntegrationPoint& ip = ipArr[j];
fe->CalcCurlShape(ip, weights);
weights.MultTranspose(dofs, v);
REQUIRE( v[0] == Approx(1.) );
if (dim == 3)
{
REQUIRE( v[1] == Approx(1.) );
REQUIRE( v[2] == Approx(1.) );
}
}
}
}
TEST_CASE("CalcCurlShape for several ND FiniteElement instances",
"[ND_TriangleElement]"
"[ND_QuadrilateralElement]"
"[ND_TetrahedronElement]"
"[ND_WedgeElement]"
"[ND_HexahedronElement]")
{
int maxOrder = 5;
int resolution = 10;
SECTION("ND_TriangleElement")
{
IsoparametricTransformation T;
GetReferenceTransformation(Element::TRIANGLE, T);
for (int order =1; order <= maxOrder; ++order)
{
std::cout << "Testing ND_TriangleElement::CalcCurlShape() "
<< "for order " << order << std::endl;
ND_TriangleElement fe(order);
TestCalcCurlShape(&fe, &T, resolution);
}
}
SECTION("ND_QuadrilateralElement")
{
IsoparametricTransformation T;
GetReferenceTransformation(Element::QUADRILATERAL, T);
for (int order =1; order <= maxOrder; ++order)
{
std::cout << "Testing ND_QuadrilateralElement::CalcCurlShape() "
<< "for order " << order << std::endl;
ND_QuadrilateralElement fe(order);
TestCalcCurlShape(&fe, &T, resolution);
}
}
SECTION("ND_TetrahedronElement")
{
IsoparametricTransformation T;
GetReferenceTransformation(Element::TETRAHEDRON, T);
for (int order =1; order <= maxOrder; ++order)
{
std::cout << "Testing ND_TetrahedronElement::CalcCurlShape() "
<< "for order " << order << std::endl;
ND_TetrahedronElement fe(order);
TestCalcCurlShape(&fe, &T, resolution);
}
}
SECTION("ND_WedgeElement")
{
IsoparametricTransformation T;
GetReferenceTransformation(Element::WEDGE, T);
for (int order =1; order <= maxOrder; ++order)
{
std::cout << "Testing ND_WedgeElement::CalcCurlShape() "
<< "for order " << order << std::endl;
ND_WedgeElement fe(order);
TestCalcCurlShape(&fe, &T, resolution);
}
}
SECTION("ND_HexahedronElement")
{
IsoparametricTransformation T;
GetReferenceTransformation(Element::HEXAHEDRON, T);
for (int order =1; order <= maxOrder; ++order)
{
std::cout << "Testing ND_HexahedronElement::CalcCurlShape() "
<< "for order " << order << std::endl;
ND_HexahedronElement fe(order);
TestCalcCurlShape(&fe, &T, resolution);
}
}
}
<|endoftext|> |
<commit_before>/**
* Touhou Community Reliant Automatic Patcher
* Tasogare Frontier support plugin
*
* ----
*
* Plugin entry point.
*/
#include <thcrap.h>
#include "thcrap_tasofro.h"
#include "th135.h"
tasofro_game_t game_id;
// Translate strings to IDs.
static tasofro_game_t game_id_from_string(const char *game)
{
if (game == NULL) {
return TH_NONE;
}
else if (!strcmp(game, "megamari")) {
return TH_MEGAMARI;
}
else if (!strcmp(game, "nsml")) {
return TH_NSML;
}
else if (!strcmp(game, "th105")) {
return TH105;
}
else if (!strcmp(game, "th123")) {
return TH123;
}
else if (!strcmp(game, "th135")) {
return TH135;
}
else if (!strcmp(game, "th145")) {
return TH145;
}
else if (!strcmp(game, "th155")) {
return TH155;
}
return TH_FUTURE;
}
int __stdcall thcrap_plugin_init()
{
int base_tasofro_removed = stack_remove_if_unneeded("base_tasofro");
if (base_tasofro_removed == 1) {
return 1;
}
const char *game = json_object_get_string(runconfig_get(), "game");
game_id = game_id_from_string(game);
if(base_tasofro_removed == -1) {
if(game_id == TH145) {
log_mboxf(NULL, MB_OK | MB_ICONINFORMATION,
"Support for TH14.5 has been moved out of the sandbox.\n"
"\n"
"Please reconfigure your patch stack; otherwise, you might "
"encounter errors or missing functionality after further "
"updates.\n"
);
} else {
return 1;
}
}
if (game_id >= TH135) {
return th135_init();
}
else {
return nsml_init();
}
return 0;
}
<commit_msg>thcrap_tasofro: Add the Steam AppID for th155. [V]<commit_after>/**
* Touhou Community Reliant Automatic Patcher
* Tasogare Frontier support plugin
*
* ----
*
* Plugin entry point.
*/
#include <thcrap.h>
#include "thcrap_tasofro.h"
#include "th135.h"
tasofro_game_t game_id;
// Translate strings to IDs.
static tasofro_game_t game_id_from_string(const char *game)
{
if (game == NULL) {
return TH_NONE;
}
else if (!strcmp(game, "megamari")) {
return TH_MEGAMARI;
}
else if (!strcmp(game, "nsml")) {
return TH_NSML;
}
else if (!strcmp(game, "th105")) {
return TH105;
}
else if (!strcmp(game, "th123")) {
return TH123;
}
else if (!strcmp(game, "th135")) {
return TH135;
}
else if (!strcmp(game, "th145")) {
return TH145;
}
else if (!strcmp(game, "th155")) {
return TH155;
}
return TH_FUTURE;
}
extern "C" __declspec(dllexport) const char* steam_appid(void)
{
switch(game_id) {
case TH155:
return "716710";
default: // -Wswitch...
return nullptr;
}
}
int __stdcall thcrap_plugin_init()
{
int base_tasofro_removed = stack_remove_if_unneeded("base_tasofro");
if (base_tasofro_removed == 1) {
return 1;
}
const char *game = json_object_get_string(runconfig_get(), "game");
game_id = game_id_from_string(game);
if(base_tasofro_removed == -1) {
if(game_id == TH145) {
log_mboxf(NULL, MB_OK | MB_ICONINFORMATION,
"Support for TH14.5 has been moved out of the sandbox.\n"
"\n"
"Please reconfigure your patch stack; otherwise, you might "
"encounter errors or missing functionality after further "
"updates.\n"
);
} else {
return 1;
}
}
if (game_id >= TH135) {
return th135_init();
}
else {
return nsml_init();
}
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <thrift/lib/cpp/util/PausableTimer.h>
#include <stdint.h>
#include <sys/time.h>
namespace apache { namespace thrift { namespace util {
PausableTimer::PausableTimer(int timeLimit) {
isTimeLimitFinite_ = timeLimit > 0;
timeLimit_.tv_sec = static_cast<int>(timeLimit / 1000);
timeLimit_.tv_usec = static_cast<int>((timeLimit % 1000) * 1000);
reset();
}
void PausableTimer::reset() {
if (isTimeLimitFinite_) {
totalTimed_ = (struct timeval){ 0 };
lastRunningTime_ = (struct timeval){ 0 };
paused_ = true;
}
}
void PausableTimer::start() {
if (isTimeLimitFinite_) {
if (paused_) {
gettimeofday(&startTime_, nullptr);
paused_ = false;
}
}
}
void PausableTimer::stop() {
if (isTimeLimitFinite_) {
if (!paused_) {
struct timeval end;
gettimeofday(&end, nullptr);
timersub(&end, &startTime_, &lastRunningTime_);
timeradd(&lastRunningTime_, &totalTimed_, &totalTimed_);
paused_ = true;
}
}
}
bool PausableTimer::hasExceededTimeLimit() {
if (isTimeLimitFinite_) {
return timercmp(&totalTimed_, &timeLimit_, >);
}
return false;
}
bool PausableTimer::didLastRunningTimeExceedLimit(
uint64_t limit_in_microseconds)
{
if (limit_in_microseconds == 0) {
return false;
}
return
1000 * 1000 * lastRunningTime_.tv_sec +
(uint64_t) lastRunningTime_.tv_usec >
limit_in_microseconds;
}
}}}
<commit_msg>Construct timeval in a way that MSVC likes<commit_after>/*
* Copyright 2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <thrift/lib/cpp/util/PausableTimer.h>
#include <stdint.h>
#include <sys/time.h>
namespace apache { namespace thrift { namespace util {
PausableTimer::PausableTimer(int timeLimit) {
isTimeLimitFinite_ = timeLimit > 0;
timeLimit_.tv_sec = static_cast<int>(timeLimit / 1000);
timeLimit_.tv_usec = static_cast<int>((timeLimit % 1000) * 1000);
reset();
}
void PausableTimer::reset() {
if (isTimeLimitFinite_) {
totalTimed_ = timeval{ 0 };
lastRunningTime_ = timeval{ 0 };
paused_ = true;
}
}
void PausableTimer::start() {
if (isTimeLimitFinite_) {
if (paused_) {
gettimeofday(&startTime_, nullptr);
paused_ = false;
}
}
}
void PausableTimer::stop() {
if (isTimeLimitFinite_) {
if (!paused_) {
struct timeval end;
gettimeofday(&end, nullptr);
timersub(&end, &startTime_, &lastRunningTime_);
timeradd(&lastRunningTime_, &totalTimed_, &totalTimed_);
paused_ = true;
}
}
}
bool PausableTimer::hasExceededTimeLimit() {
if (isTimeLimitFinite_) {
return timercmp(&totalTimed_, &timeLimit_, >);
}
return false;
}
bool PausableTimer::didLastRunningTimeExceedLimit(
uint64_t limit_in_microseconds)
{
if (limit_in_microseconds == 0) {
return false;
}
return
1000 * 1000 * lastRunningTime_.tv_sec +
(uint64_t) lastRunningTime_.tv_usec >
limit_in_microseconds;
}
}}}
<|endoftext|> |
<commit_before>/* Copyright 2007-2015 QReal Research Group
*
* 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 "generatorBase/semanticTree/switchNode.h"
#include <qrutils/stringUtils.h>
using namespace generatorBase::semantics;
using namespace qReal;
SwitchNode::SwitchNode(const Id &idBinded, QObject *parent)
: NonZoneNode(idBinded, parent)
, mDefaultBranch(nullptr)
, mBranchesMerged(false)
, mGenerateIfs(false)
{
}
void SwitchNode::addBranch(const QString &value, SemanticNode * const node)
{
ZoneNode * const zone = new ZoneNode(this);
zone->setParentNode(this);
bind(value, zone);
if (node) {
zone->appendChild(node);
}
}
void SwitchNode::mergeBranch(const QString &value, NonZoneNode * const node)
{
Q_ASSERT(node);
bind(value, node->parentZone());
}
bool SwitchNode::branchesMerged() const
{
return mBranchesMerged;
}
void SwitchNode::setBranchesMergedFlag()
{
mBranchesMerged = true;
}
void SwitchNode::setGenerateIfs()
{
mGenerateIfs = true;
}
QString SwitchNode::toStringImpl(GeneratorCustomizer &customizer, int indent, const QString &indentString) const
{
QString result;
bool isHead = true;
for (ZoneNode * const zone : mBranches.values().toSet()) {
if (zone == mDefaultBranch) {
// Branches merged with default on the diagram will be merged with it in code too
continue;
}
result += generatePart(customizer, indent, indentString, zone, isHead
? customizer.factory()->switchHeadGenerator(mId, customizer, mBranches.keys(zone), mGenerateIfs || !customizer.supportsSwitchUnstableToBreaks())
: customizer.factory()->switchMiddleGenerator(mId, customizer, mBranches.keys(zone), mGenerateIfs || !customizer.supportsSwitchUnstableToBreaks()));
isHead = false;
}
if (result.isEmpty()) {
// Then all branches lead to one block, we may ignore switch construction.
return mDefaultBranch->toString(customizer, indent, indentString);
}
result += generatePart(customizer, indent, indentString, mDefaultBranch
, customizer.factory()->switchDefaultGenerator(mId, customizer, mGenerateIfs || !customizer.supportsSwitchUnstableToBreaks()));
return result;
}
void SwitchNode::bind(const QString &value, ZoneNode *zone)
{
if (value.isEmpty()) {
mDefaultBranch = zone;
} else {
mBranches[value] = zone;
}
}
QString SwitchNode::generatePart(generatorBase::GeneratorCustomizer &customizer
, int indent
, const QString &indentString
, ZoneNode * const zone
, generatorBase::simple::AbstractSimpleGenerator *generator) const
{
return utils::StringUtils::addIndent(generator->generate()
.replace("@@BODY@@", zone->toString(customizer, indent + 1, indentString)), indent, indentString);
}
QLinkedList<SemanticNode *> SwitchNode::children() const
{
QLinkedList<SemanticNode *> result;
for (ZoneNode * const zone : mBranches.values().toSet()) {
result << zone;
}
if (mDefaultBranch) {
result << mDefaultBranch;
}
return result;
}
<commit_msg>Style guide fixes<commit_after>/* Copyright 2007-2015 QReal Research Group
*
* 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 "generatorBase/semanticTree/switchNode.h"
#include <qrutils/stringUtils.h>
using namespace generatorBase::semantics;
using namespace qReal;
SwitchNode::SwitchNode(const Id &idBinded, QObject *parent)
: NonZoneNode(idBinded, parent)
, mDefaultBranch(nullptr)
, mBranchesMerged(false)
, mGenerateIfs(false)
{
}
void SwitchNode::addBranch(const QString &value, SemanticNode * const node)
{
ZoneNode * const zone = new ZoneNode(this);
zone->setParentNode(this);
bind(value, zone);
if (node) {
zone->appendChild(node);
}
}
void SwitchNode::mergeBranch(const QString &value, NonZoneNode * const node)
{
Q_ASSERT(node);
bind(value, node->parentZone());
}
bool SwitchNode::branchesMerged() const
{
return mBranchesMerged;
}
void SwitchNode::setBranchesMergedFlag()
{
mBranchesMerged = true;
}
void SwitchNode::setGenerateIfs()
{
mGenerateIfs = true;
}
QString SwitchNode::toStringImpl(GeneratorCustomizer &customizer, int indent, const QString &indentString) const
{
QString result;
bool isHead = true;
for (ZoneNode * const zone : mBranches.values().toSet()) {
if (zone == mDefaultBranch) {
// Branches merged with default on the diagram will be merged with it in code too
continue;
}
result += generatePart(customizer, indent, indentString, zone, isHead
? customizer.factory()->switchHeadGenerator(mId, customizer, mBranches.keys(zone)
, mGenerateIfs || !customizer.supportsSwitchUnstableToBreaks())
: customizer.factory()->switchMiddleGenerator(mId, customizer, mBranches.keys(zone)
, mGenerateIfs || !customizer.supportsSwitchUnstableToBreaks()));
isHead = false;
}
if (result.isEmpty()) {
// Then all branches lead to one block, we may ignore switch construction.
return mDefaultBranch->toString(customizer, indent, indentString);
}
result += generatePart(customizer, indent, indentString, mDefaultBranch
, customizer.factory()->switchDefaultGenerator(mId, customizer
, mGenerateIfs || !customizer.supportsSwitchUnstableToBreaks()));
return result;
}
void SwitchNode::bind(const QString &value, ZoneNode *zone)
{
if (value.isEmpty()) {
mDefaultBranch = zone;
} else {
mBranches[value] = zone;
}
}
QString SwitchNode::generatePart(generatorBase::GeneratorCustomizer &customizer
, int indent
, const QString &indentString
, ZoneNode * const zone
, generatorBase::simple::AbstractSimpleGenerator *generator) const
{
return utils::StringUtils::addIndent(generator->generate()
.replace("@@BODY@@", zone->toString(customizer, indent + 1, indentString)), indent, indentString);
}
QLinkedList<SemanticNode *> SwitchNode::children() const
{
QLinkedList<SemanticNode *> result;
for (ZoneNode * const zone : mBranches.values().toSet()) {
result << zone;
}
if (mDefaultBranch) {
result << mDefaultBranch;
}
return result;
}
<|endoftext|> |
<commit_before>// @(#)root/tmva $Id$
// Author: Simon Pfreundschuh
/*************************************************************************
* Copyright (C) 2016, Simon Pfreundschuh *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
////////////////////////////////////////////////////////////////////
// Concrete instantiation of the generic backpropagation test for //
// multi-threaded CPU architectures. //
////////////////////////////////////////////////////////////////////
#include "TMatrix.h"
#include "TMVA/DNN/Architectures/Cpu.h"
#include "TestBackpropagation.h"
using namespace TMVA::DNN;
int main()
{
using Scalar_t = Double_t;
std::cout << "Testing Backpropagation:" << std::endl;
double error;
error = testBackpropagationWeightsLinear<TCpu<Scalar_t>>(1.0);
if (error > 1e-3)
return 1;
error = testBackpropagationL1Regularization<TCpu<Scalar_t>>(1e-2);
if (error > 1e-3)
return 1;
error = testBackpropagationL2Regularization<TCpu<Scalar_t>>(1.0);
if (error > 1e-3)
return 1;
error = testBackpropagationBiasesLinear<TCpu<Scalar_t>>(1.0);
if (error > 1e-3)
return 1;
return 0;
}
<commit_msg>Continue testing if one test fails<commit_after>// @(#)root/tmva $Id$
// Author: Simon Pfreundschuh
/*************************************************************************
* Copyright (C) 2016, Simon Pfreundschuh *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
////////////////////////////////////////////////////////////////////
// Concrete instantiation of the generic backpropagation test for //
// multi-threaded CPU architectures. //
////////////////////////////////////////////////////////////////////
#include "TMatrix.h"
#include "TMVA/DNN/Architectures/Cpu.h"
#include "TestBackpropagation.h"
using namespace TMVA::DNN;
int main()
{
using Scalar_t = Double_t;
std::cout << "Testing Backpropagation:" << std::endl;
double error;
int iret = 0;
error = testBackpropagationWeightsLinear<TCpu<Scalar_t>>(1.0);
if (error > 1e-3)
iret++;
error = testBackpropagationL1Regularization<TCpu<Scalar_t>>(1e-2);
if (error > 1e-3)
iret++;
error = testBackpropagationL2Regularization<TCpu<Scalar_t>>(1.0);
if (error > 1e-3)
iret++;
error = testBackpropagationBiasesLinear<TCpu<Scalar_t>>(1.0);
if (error > 1e-3)
iret++;
return iret;
}
<|endoftext|> |
<commit_before>// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2011,2012 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#include "keeper.hpp"
#include <iostream>
#include <glog/logging.h>
#include "../common/membership.hpp"
#include "../common/exception.hpp"
#include "server_util.hpp"
using namespace jubatus;
using namespace jubatus::framework;
keeper::keeper(const keeper_argv& a)
: pfi::network::mprpc::rpc_server(a.timeout),
a_(a),
zk_(common::create_lock_service("cached_zk", a.z, a.timeout))
// zk_(common::create_lock_service("zk", a.z, a.timeout))
{
ls = zk_;
jubatus::common::prepare_jubatus(*zk_);
if(!register_keeper(*zk_, a_.eth, a_.port) ){
throw JUBATUS_EXCEPTION(membership_error("can't register to zookeeper."));
}
}
keeper::~keeper(){
}
int keeper::run()
{
try {
{ LOG(INFO) << "running in port=" << a_.port; }
set_exit_on_term();
return this->serv(a_.port, a_.threadnum);
} catch (const jubatus::exception::jubatus_exception& e) {
std::cout << e.diagnostic_information(true) << std::endl;
return -1;
}
}
void keeper::get_members_(const std::string& name, std::vector<std::pair<std::string, int> >& ret){
using namespace std;
ret.clear();
vector<string> list;
string path = common::ACTOR_BASE_PATH + "/" + name + "/nodes";
{
pfi::concurrent::scoped_lock lk(mutex_);
zk_->list(path, list);
}
vector<string>::const_iterator it;
// FIXME:
// do you return all server list? it can be very large
for(it = list.begin(); it!= list.end(); ++it){
string ip;
int port;
common::revert(*it, ip, port);
ret.push_back(make_pair(ip,port));
}
}
<commit_msg>Fix ignoring SIGPIPE deleted by 877d3a9086c0e0cc58b07afe32514a0f76fa3a80<commit_after>// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2011,2012 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#include "keeper.hpp"
#include <iostream>
#include <glog/logging.h>
#include "../common/membership.hpp"
#include "../common/exception.hpp"
#include "server_util.hpp"
using namespace jubatus;
using namespace jubatus::framework;
keeper::keeper(const keeper_argv& a)
: pfi::network::mprpc::rpc_server(a.timeout),
a_(a),
zk_(common::create_lock_service("cached_zk", a.z, a.timeout))
// zk_(common::create_lock_service("zk", a.z, a.timeout))
{
ls = zk_;
jubatus::common::prepare_jubatus(*zk_);
if(!register_keeper(*zk_, a_.eth, a_.port) ){
throw JUBATUS_EXCEPTION(membership_error("can't register to zookeeper."));
}
}
keeper::~keeper(){
}
int keeper::run()
{
try {
{ LOG(INFO) << "running in port=" << a_.port; }
set_exit_on_term();
ignore_sigpipe();
return this->serv(a_.port, a_.threadnum);
} catch (const jubatus::exception::jubatus_exception& e) {
std::cout << e.diagnostic_information(true) << std::endl;
return -1;
}
}
void keeper::get_members_(const std::string& name, std::vector<std::pair<std::string, int> >& ret){
using namespace std;
ret.clear();
vector<string> list;
string path = common::ACTOR_BASE_PATH + "/" + name + "/nodes";
{
pfi::concurrent::scoped_lock lk(mutex_);
zk_->list(path, list);
}
vector<string>::const_iterator it;
// FIXME:
// do you return all server list? it can be very large
for(it = list.begin(); it!= list.end(); ++it){
string ip;
int port;
common::revert(*it, ip, port);
ret.push_back(make_pair(ip,port));
}
}
<|endoftext|> |
<commit_before>//-----------------------------------------------------------------------------
// Copyright (c) 2016, Jeff Hutchinson
// 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 project nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//-----------------------------------------------------------------------------
#ifndef _GRAPHICS_CONTEXT_HPP_
#define _GRAPHICS_CONTEXT_HPP_
#include "graphics/renderer.hpp"
class Window;
enum ContextAPI : int {
OpenGL,
// WebGL,
D3D11
};
class Context {
public:
void init(Window *window);
virtual void destroy() = 0;
virtual void swapBuffers() const = 0;
virtual Renderer* getRenderer() const = 0;
protected:
Renderer *mRenderer;
Window *mWindow;
virtual void initContext() = 0;
};
class ContextFactory {
public:
static Context* createContext(ContextAPI api);
static void releaseContext(Context *context);
static void setCurrentContext(Context *current);
};
extern Context *gCurrentContext;
#define RENDERER gCurrentContext->getRenderer()
#endif // _GRAPHICS_CONTEXT_HPP_<commit_msg>virtual destructor for Context<commit_after>//-----------------------------------------------------------------------------
// Copyright (c) 2016, Jeff Hutchinson
// 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 project nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//-----------------------------------------------------------------------------
#ifndef _GRAPHICS_CONTEXT_HPP_
#define _GRAPHICS_CONTEXT_HPP_
#include "graphics/renderer.hpp"
class Window;
enum ContextAPI : int {
OpenGL,
// WebGL,
D3D11
};
class Context {
public:
virtual ~Context() {}
void init(Window *window);
virtual void destroy() = 0;
virtual void swapBuffers() const = 0;
virtual Renderer* getRenderer() const = 0;
protected:
Renderer *mRenderer;
Window *mWindow;
virtual void initContext() = 0;
};
class ContextFactory {
public:
static Context* createContext(ContextAPI api);
static void releaseContext(Context *context);
static void setCurrentContext(Context *current);
};
extern Context *gCurrentContext;
#define RENDERER gCurrentContext->getRenderer()
#endif // _GRAPHICS_CONTEXT_HPP_<|endoftext|> |
<commit_before>#include <QDir>
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QSettings>
#include "functions.h"
#include "language-loader.h"
#include "main-screen.h"
#include "models/image.h"
#include "models/profile.h"
#include "models/qml-auth.h"
#include "models/qml-auth-setting-field.h"
#include "models/qml-image.h"
#include "models/qml-site.h"
#include "settings.h"
#include "share/share-utils.h"
#include "syntax-highlighter-helper.h"
#if defined(Q_OS_ANDROID)
#include <QStandardPaths>
#include <QtAndroid>
#include "logger.h"
bool checkPermission(const QString &perm)
{
auto already = QtAndroid::checkPermission(perm);
if (already == QtAndroid::PermissionResult::Denied) {
auto results = QtAndroid::requestPermissionsSync(QStringList() << perm);
if (results[perm] == QtAndroid::PermissionResult::Denied) {
return false;
}
}
return true;
}
#endif
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
app.setApplicationName("Grabber");
app.setApplicationVersion(VERSION);
app.setOrganizationName("Bionus");
app.setOrganizationDomain("bionus.fr.cr");
qmlRegisterType<ShareUtils>("Grabber", 1, 0, "ShareUtils");
qmlRegisterType<SyntaxHighlighterHelper>("Grabber", 1, 0, "SyntaxHighlighterHelper");
qRegisterMetaType<QSharedPointer<Image>>("QSharedPointer<Image>");
qRegisterMetaType<Settings*>("Settings*");
qRegisterMetaType<QmlImage*>("QmlImage*");
qRegisterMetaType<QList<QmlImage*>>("QList>QmlImage*>");
qRegisterMetaType<QmlSite*>("QmlSite*");
qRegisterMetaType<QList<QmlSite*>>("QList<QmlSite*>");
qRegisterMetaType<QList<QmlAuth*>>("QList<QmlAuth*>");
qRegisterMetaType<QList<QmlAuthSettingField*>>("QList<QmlAuthSettingField*>");
// Copy settings files to writable directory
const QStringList toCopy { "sites/", "themes/", "webservices/" };
for (const QString &tgt : toCopy) {
const QString from = savePath(tgt, true, false);
const QString to = savePath(tgt, true, true);
if (!QDir(to).exists() && QDir(from).exists()) {
copyRecursively(from, to);
}
}
const QUrl url(QStringLiteral("qrc:/main-screen.qml"));
QQmlApplicationEngine engine;
QObject::connect(&engine, &QQmlApplicationEngine::objectCreated, &app, [url](QObject *obj, const QUrl &objUrl) {
if (!obj && url == objUrl) {
QCoreApplication::exit(-1);
}
}, Qt::QueuedConnection);
// Define a few globals
engine.rootContext()->setContextProperty("VERSION", QString(VERSION));
#ifdef NIGHTLY
engine.rootContext()->setContextProperty("NIGHTLY", true);
engine.rootContext()->setContextProperty("NIGHTLY_COMMIT", QString(NIGHTLY_COMMIT));
#else
engine.rootContext()->setContextProperty("NIGHTLY", false);
engine.rootContext()->setContextProperty("NIGHTLY_COMMIT", QString());
#endif
Profile profile(savePath());
MainScreen mainScreen(&profile, &engine);
engine.setObjectOwnership(&mainScreen, QQmlEngine::CppOwnership);
engine.rootContext()->setContextProperty("backend", &mainScreen);
Settings settings(profile.getSettings());
engine.rootContext()->setContextProperty("settings", &settings);
// Load translations
LanguageLoader languageLoader(savePath("languages/", true, false));
languageLoader.install(qApp);
languageLoader.setLanguage(profile.getSettings()->value("language", "English").toString());
engine.rootContext()->setContextProperty("languageLoader", &languageLoader);
#if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0))
QObject::connect(&languageLoader, &LanguageLoader::languageChanged, &engine, &QQmlEngine::retranslate);
#endif
#if defined(Q_OS_ANDROID)
if (!checkPermission("android.permission.WRITE_EXTERNAL_STORAGE")) {
log(QStringLiteral("Android write permission not granted"), Logger::Error);
}
if (settings.value("Save/path").toString().isEmpty()) {
settings.setValue("Save/path", QStandardPaths::standardLocations(QStandardPaths::PicturesLocation).first() + "/Grabber");
}
#endif
engine.load(url);
#if defined(Q_OS_ANDROID)
QtAndroid::hideSplashScreen(250);
#endif
return app.exec();
}
<commit_msg>Copy words.txt file in QML version<commit_after>#include <QDir>
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QSettings>
#include "functions.h"
#include "language-loader.h"
#include "main-screen.h"
#include "models/image.h"
#include "models/profile.h"
#include "models/qml-auth.h"
#include "models/qml-auth-setting-field.h"
#include "models/qml-image.h"
#include "models/qml-site.h"
#include "settings.h"
#include "share/share-utils.h"
#include "syntax-highlighter-helper.h"
#if defined(Q_OS_ANDROID)
#include <QStandardPaths>
#include <QtAndroid>
#include "logger.h"
bool checkPermission(const QString &perm)
{
auto already = QtAndroid::checkPermission(perm);
if (already == QtAndroid::PermissionResult::Denied) {
auto results = QtAndroid::requestPermissionsSync(QStringList() << perm);
if (results[perm] == QtAndroid::PermissionResult::Denied) {
return false;
}
}
return true;
}
#endif
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
app.setApplicationName("Grabber");
app.setApplicationVersion(VERSION);
app.setOrganizationName("Bionus");
app.setOrganizationDomain("bionus.fr.cr");
qmlRegisterType<ShareUtils>("Grabber", 1, 0, "ShareUtils");
qmlRegisterType<SyntaxHighlighterHelper>("Grabber", 1, 0, "SyntaxHighlighterHelper");
qRegisterMetaType<QSharedPointer<Image>>("QSharedPointer<Image>");
qRegisterMetaType<Settings*>("Settings*");
qRegisterMetaType<QmlImage*>("QmlImage*");
qRegisterMetaType<QList<QmlImage*>>("QList>QmlImage*>");
qRegisterMetaType<QmlSite*>("QmlSite*");
qRegisterMetaType<QList<QmlSite*>>("QList<QmlSite*>");
qRegisterMetaType<QList<QmlAuth*>>("QList<QmlAuth*>");
qRegisterMetaType<QList<QmlAuthSettingField*>>("QList<QmlAuthSettingField*>");
// Copy settings files to writable directory
const QStringList toCopy { "sites/", "themes/", "webservices/" };
for (const QString &tgt : toCopy) {
const QString from = savePath(tgt, true, false);
const QString to = savePath(tgt, true, true);
if (!QDir(to).exists() && QDir(from).exists()) {
copyRecursively(from, to);
}
}
const QStringList filesToCopy { "words.txt" };
for (const QString &tgt : filesToCopy) {
const QString from = savePath(tgt, true, false);
const QString to = savePath(tgt, true, true);
if (!QFile::exists(to) && QFile::exists(from)) {
QFile::copy(from, to);
}
}
const QUrl url(QStringLiteral("qrc:/main-screen.qml"));
QQmlApplicationEngine engine;
QObject::connect(&engine, &QQmlApplicationEngine::objectCreated, &app, [url](QObject *obj, const QUrl &objUrl) {
if (!obj && url == objUrl) {
QCoreApplication::exit(-1);
}
}, Qt::QueuedConnection);
// Define a few globals
engine.rootContext()->setContextProperty("VERSION", QString(VERSION));
#ifdef NIGHTLY
engine.rootContext()->setContextProperty("NIGHTLY", true);
engine.rootContext()->setContextProperty("NIGHTLY_COMMIT", QString(NIGHTLY_COMMIT));
#else
engine.rootContext()->setContextProperty("NIGHTLY", false);
engine.rootContext()->setContextProperty("NIGHTLY_COMMIT", QString());
#endif
Profile profile(savePath());
MainScreen mainScreen(&profile, &engine);
engine.setObjectOwnership(&mainScreen, QQmlEngine::CppOwnership);
engine.rootContext()->setContextProperty("backend", &mainScreen);
Settings settings(profile.getSettings());
engine.rootContext()->setContextProperty("settings", &settings);
// Load translations
LanguageLoader languageLoader(savePath("languages/", true, false));
languageLoader.install(qApp);
languageLoader.setLanguage(profile.getSettings()->value("language", "English").toString());
engine.rootContext()->setContextProperty("languageLoader", &languageLoader);
#if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0))
QObject::connect(&languageLoader, &LanguageLoader::languageChanged, &engine, &QQmlEngine::retranslate);
#endif
#if defined(Q_OS_ANDROID)
if (!checkPermission("android.permission.WRITE_EXTERNAL_STORAGE")) {
log(QStringLiteral("Android write permission not granted"), Logger::Error);
}
if (settings.value("Save/path").toString().isEmpty()) {
settings.setValue("Save/path", QStandardPaths::standardLocations(QStandardPaths::PicturesLocation).first() + "/Grabber");
}
#endif
engine.load(url);
#if defined(Q_OS_ANDROID)
QtAndroid::hideSplashScreen(250);
#endif
return app.exec();
}
<|endoftext|> |
<commit_before>// Copyright (c) 2010-2021, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
#include "unit_tests.hpp"
#include "test_linearform_ext.hpp"
using namespace mfem;
using namespace linearform_ext_tests;
namespace mfem
{
namespace linearform_ext_tests
{
void LinearFormExtTest::Description()
{
mfem::out << "[LinearFormExt]"
<< " p=" << p
<< " q=" << q
<< " "<< dim << "D"
<< " "<< vdim << "-"
<< (problem%2?"Scalar":"Vector")
<< (problem>2?"Grad":"")
//<< (gll ? "GLL" : "GL")
<< std::endl;
}
void LinearFormExtTest::Run()
{
Description();
AssembleBoth();
REQUIRE((lf_full*lf_full) == MFEM_Approx(lf_legacy*lf_legacy));
}
} // namespace linearform_ext_tests
} // namespace mfem
TEST_CASE("Linear Form Extension", "[LinearformExt], [CUDA]")
{
const auto N = GENERATE(2,3,4);
const auto dim = GENERATE(2,3);
const auto order = GENERATE(1,2,3);
const auto gll = GENERATE(false,true); // q=p+2, q=p+1
SECTION("Scalar")
{
const auto vdim = 1;
const auto problem = GENERATE(LinearFormExtTest::DomainLF,
LinearFormExtTest::DomainLFGrad);
LinearFormExtTest(N, dim, vdim, gll, problem, order, true).Run();
}
SECTION("Vector")
{
const auto vdim = GENERATE(1,2,24);
const auto problem = GENERATE(LinearFormExtTest::VectorDomainLF,
LinearFormExtTest::VectorDomainLFGrad);
LinearFormExtTest(N, dim, vdim, gll, problem, order, true).Run();
}
} // test case
<commit_msg>Include fix<commit_after>// Copyright (c) 2010-2021, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
#include "unit_tests.hpp"
#include "tests/unit/fem/test_linearform_ext.hpp"
using namespace mfem;
using namespace linearform_ext_tests;
namespace mfem
{
namespace linearform_ext_tests
{
void LinearFormExtTest::Description()
{
mfem::out << "[LinearFormExt]"
<< " p=" << p
<< " q=" << q
<< " "<< dim << "D"
<< " "<< vdim << "-"
<< (problem%2?"Scalar":"Vector")
<< (problem>2?"Grad":"")
//<< (gll ? "GLL" : "GL")
<< std::endl;
}
void LinearFormExtTest::Run()
{
Description();
AssembleBoth();
REQUIRE((lf_full*lf_full) == MFEM_Approx(lf_legacy*lf_legacy));
}
} // namespace linearform_ext_tests
} // namespace mfem
TEST_CASE("Linear Form Extension", "[LinearformExt], [CUDA]")
{
const auto N = GENERATE(2,3,4);
const auto dim = GENERATE(2,3);
const auto order = GENERATE(1,2,3);
const auto gll = GENERATE(false,true); // q=p+2, q=p+1
SECTION("Scalar")
{
const auto vdim = 1;
const auto problem = GENERATE(LinearFormExtTest::DomainLF,
LinearFormExtTest::DomainLFGrad);
LinearFormExtTest(N, dim, vdim, gll, problem, order, true).Run();
}
SECTION("Vector")
{
const auto vdim = GENERATE(1,2,24);
const auto problem = GENERATE(LinearFormExtTest::VectorDomainLF,
LinearFormExtTest::VectorDomainLFGrad);
LinearFormExtTest(N, dim, vdim, gll, problem, order, true).Run();
}
} // test case
<|endoftext|> |
<commit_before>/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* Written (W) 2014 pl8787
*/
#include <shogun/base/init.h>
#include <shogun/statistics/HSIC.h>
#include <shogun/kernel/GaussianKernel.h>
#include <shogun/features/DenseFeatures.h>
#include <shogun/mathematics/Statistics.h>
#include <gtest/gtest.h>
using namespace shogun;
void create_fixed_data_kernel_small(CFeatures*& features_p,
CFeatures*& features_q, CKernel*& kernel_p, CKernel*& kernel_q)
{
index_t m=2;
index_t d=3;
SGMatrix<float64_t> p(d,2*m);
for (index_t i=0; i<2*d*m; ++i)
p.matrix[i]=i;
// p.display_matrix("p");
SGMatrix<float64_t> q(d,2*m);
for (index_t i=0; i<2*d*m; ++i)
q.matrix[i]=i+10;
// q.display_matrix("q");
features_p=new CDenseFeatures<float64_t>(p);
features_q=new CDenseFeatures<float64_t>(q);
float64_t sigma_x=2;
float64_t sigma_y=3;
float64_t sq_sigma_x_twice=sigma_x*sigma_x*2;
float64_t sq_sigma_y_twice=sigma_y*sigma_y*2;
/* shoguns kernel width is different */
kernel_p=new CGaussianKernel(10, sq_sigma_x_twice);
kernel_q=new CGaussianKernel(10, sq_sigma_y_twice);
}
void create_fixed_data_kernel_big(CFeatures*& features_p,
CFeatures*& features_q, CKernel*& kernel_p, CKernel*& kernel_q)
{
index_t m=10;
index_t d=7;
SGMatrix<float64_t> p(d,m);
for (index_t i=0; i<d*m; ++i)
p.matrix[i]=(i+8)%3;
// p.display_matrix("p");
SGMatrix<float64_t> q(d,m);
for (index_t i=0; i<d*m; ++i)
q.matrix[i]=((i+10)*(i%4+2))%4;
// q.display_matrix("q");
features_p=new CDenseFeatures<float64_t>(p);
features_q=new CDenseFeatures<float64_t>(q);
float64_t sigma_x=2;
float64_t sigma_y=3;
float64_t sq_sigma_x_twice=sigma_x*sigma_x*2;
float64_t sq_sigma_y_twice=sigma_y*sigma_y*2;
/* shoguns kernel width is different */
kernel_p=new CGaussianKernel(10, sq_sigma_x_twice);
kernel_q=new CGaussianKernel(10, sq_sigma_y_twice);
}
/** tests the hsic statistic for a single fixed data case and ensures
* equality with sma implementation */
TEST(HSICTEST, hsic_fixed)
{
CFeatures* features_p=NULL;
CFeatures* features_q=NULL;
CKernel* kernel_p=NULL;
CKernel* kernel_q=NULL;
create_fixed_data_kernel_small(features_p, features_q, kernel_p, kernel_q);
index_t m=features_p->get_num_vectors();
CHSIC* hsic=new CHSIC(kernel_p, kernel_q, features_p, features_q);
/* assert matlab result, note that compute statistic computes m*hsic */
float64_t difference=hsic->compute_statistic();
//SG_SPRINT("hsic fixed: %f\n", difference);
EXPECT_NEAR(difference, m*0.164761446385339, 1e-15);
SG_UNREF(hsic);
}
TEST(HSICTEST, hsic_gamma)
{
CFeatures* features_p=NULL;
CFeatures* features_q=NULL;
CKernel* kernel_p=NULL;
CKernel* kernel_q=NULL;
create_fixed_data_kernel_big(features_p, features_q, kernel_p, kernel_q);
CHSIC* hsic=new CHSIC(kernel_p, kernel_q, features_p, features_q);
hsic->set_null_approximation_method(HSIC_GAMMA);
float64_t p=hsic->compute_p_value(0.05);
//SG_SPRINT("p-value: %f\n", p);
EXPECT_NEAR(p, 0.172182287884256, 1e-14);
SG_UNREF(hsic);
}
TEST(HSICTEST, hsic_sample_null)
{
CFeatures* features_p=NULL;
CFeatures* features_q=NULL;
CKernel* kernel_p=NULL;
CKernel* kernel_q=NULL;
create_fixed_data_kernel_big(features_p, features_q, kernel_p, kernel_q);
CHSIC* hsic=new CHSIC(kernel_p, kernel_q, features_p, features_q);
/* do sampling null */
hsic->set_null_approximation_method(PERMUTATION);
float64_t p=hsic->compute_p_value(0.05);
//SG_SPRINT("p-value: %f\n", p);
//EXPECT_NEAR(p, 0.576000, 1e-14);
/* ensure that sampling null of hsic leads to same results as using
* CKernelIndependenceTest */
CMath::init_random(1);
float64_t mean1=CStatistics::mean(hsic->sample_null());
float64_t var1=CStatistics::variance(hsic->sample_null());
//SG_SPRINT("mean1=%f, var1=%f\n", mean1, var1);
CMath::init_random(1);
float64_t mean2=CStatistics::mean(
hsic->CKernelIndependenceTest::sample_null());
float64_t var2=CStatistics::variance(hsic->sample_null());
//SG_SPRINT("mean2=%f, var2=%f\n", mean2, var2);
/* assert than results are the same from bot sampling null impl. */
EXPECT_NEAR(mean1, mean2, 1e-7);
EXPECT_NEAR(var1, var2, 1e-7);
SG_UNREF(hsic);
}
<commit_msg>Code format modify.<commit_after>/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* Written (W) 2014 pl8787
*/
#include <shogun/base/init.h>
#include <shogun/statistics/HSIC.h>
#include <shogun/kernel/GaussianKernel.h>
#include <shogun/features/DenseFeatures.h>
#include <shogun/mathematics/Statistics.h>
#include <gtest/gtest.h>
using namespace shogun;
void create_fixed_data_kernel_small(CFeatures*& features_p,
CFeatures*& features_q, CKernel*& kernel_p, CKernel*& kernel_q)
{
index_t m=2;
index_t d=3;
SGMatrix<float64_t> p(d,2*m);
for (index_t i=0; i<2*d*m; ++i)
p.matrix[i]=i;
SGMatrix<float64_t> q(d,2*m);
for (index_t i=0; i<2*d*m; ++i)
q.matrix[i]=i+10;
features_p=new CDenseFeatures<float64_t>(p);
features_q=new CDenseFeatures<float64_t>(q);
float64_t sigma_x=2;
float64_t sigma_y=3;
float64_t sq_sigma_x_twice=sigma_x*sigma_x*2;
float64_t sq_sigma_y_twice=sigma_y*sigma_y*2;
/* shoguns kernel width is different */
kernel_p=new CGaussianKernel(10, sq_sigma_x_twice);
kernel_q=new CGaussianKernel(10, sq_sigma_y_twice);
}
void create_fixed_data_kernel_big(CFeatures*& features_p,
CFeatures*& features_q, CKernel*& kernel_p, CKernel*& kernel_q)
{
index_t m=10;
index_t d=7;
SGMatrix<float64_t> p(d,m);
for (index_t i=0; i<d*m; ++i)
p.matrix[i]=(i+8)%3;
SGMatrix<float64_t> q(d,m);
for (index_t i=0; i<d*m; ++i)
q.matrix[i]=((i+10)*(i%4+2))%4;
features_p=new CDenseFeatures<float64_t>(p);
features_q=new CDenseFeatures<float64_t>(q);
float64_t sigma_x=2;
float64_t sigma_y=3;
float64_t sq_sigma_x_twice=sigma_x*sigma_x*2;
float64_t sq_sigma_y_twice=sigma_y*sigma_y*2;
/* shoguns kernel width is different */
kernel_p=new CGaussianKernel(10, sq_sigma_x_twice);
kernel_q=new CGaussianKernel(10, sq_sigma_y_twice);
}
/** tests the hsic statistic for a single fixed data case and ensures
* equality with sma implementation */
TEST(HSIC, hsic_fixed)
{
CFeatures* features_p=NULL;
CFeatures* features_q=NULL;
CKernel* kernel_p=NULL;
CKernel* kernel_q=NULL;
create_fixed_data_kernel_small(features_p, features_q, kernel_p, kernel_q);
index_t m=features_p->get_num_vectors();
CHSIC* hsic=new CHSIC(kernel_p, kernel_q, features_p, features_q);
/* assert matlab result, note that compute statistic computes m*hsic */
float64_t difference=hsic->compute_statistic();
EXPECT_NEAR(difference, m*0.164761446385339, 1e-15);
SG_UNREF(hsic);
}
TEST(HSIC, hsic_gamma)
{
CFeatures* features_p=NULL;
CFeatures* features_q=NULL;
CKernel* kernel_p=NULL;
CKernel* kernel_q=NULL;
create_fixed_data_kernel_big(features_p, features_q, kernel_p, kernel_q);
CHSIC* hsic=new CHSIC(kernel_p, kernel_q, features_p, features_q);
hsic->set_null_approximation_method(HSIC_GAMMA);
float64_t p=hsic->compute_p_value(0.05);
EXPECT_NEAR(p, 0.172182287884256, 1e-14);
SG_UNREF(hsic);
}
TEST(HSIC, hsic_sample_null)
{
CFeatures* features_p=NULL;
CFeatures* features_q=NULL;
CKernel* kernel_p=NULL;
CKernel* kernel_q=NULL;
create_fixed_data_kernel_big(features_p, features_q, kernel_p, kernel_q);
CHSIC* hsic=new CHSIC(kernel_p, kernel_q, features_p, features_q);
/* do sampling null */
hsic->set_null_approximation_method(PERMUTATION);
hsic->compute_p_value(0.05);
/* ensure that sampling null of hsic leads to same results as using
* CKernelIndependenceTest */
CMath::init_random(1);
float64_t mean1=CStatistics::mean(hsic->sample_null());
float64_t var1=CStatistics::variance(hsic->sample_null());
CMath::init_random(1);
float64_t mean2=CStatistics::mean(
hsic->CKernelIndependenceTest::sample_null());
float64_t var2=CStatistics::variance(hsic->sample_null());
/* assert than results are the same from bot sampling null impl. */
EXPECT_NEAR(mean1, mean2, 1e-7);
EXPECT_NEAR(var1, var2, 1e-7);
SG_UNREF(hsic);
}
<|endoftext|> |
<commit_before>// Copyright 2011 Gregory Szorc
//
// 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 STORE_WATCHER_HPP
#define STORE_WATCHER_HPP
#include <zippylog/zippylog.hpp>
#include <zippylog/device/device.hpp>
#include <zippylog/platform.hpp>
#include <zippylog/store.hpp>
#include <zmq.hpp>
namespace zippylog {
/// Parameters to instantiate a StoreWatcher class
class ZIPPYLOG_EXPORT StoreWatcherStartParams {
public:
/// 0MQ context to use
::zmq::context_t *zctx;
/// Store filesystem path to watch
::std::string store_path;
/// 0MQ socket endpoint to send change notifications to
::std::string endpoint;
/// 0MQ endpoint to send log messages to
::std::string logging_endpoint;
/// Semaphore to control whether device should run
::zippylog::platform::ConditionalWait *active;
};
/// A directory watcher for file-based stores
///
/// This class watches the specified store directory for changes.
/// When changes are detected, it executes function callbacks, which
/// must be defined in an inherited class.
///
/// The directory watcher is currently designed to execute on its own
/// thread. Just instantiate a directory watcher and invoke Run(). This
/// function will block until the active semaphore contained in the start
/// parameters goes to false.
///
/// @todo move to device namespace
class ZIPPYLOG_EXPORT StoreWatcher : public ::zippylog::device::Device {
public:
/// Instantiate a store watcher with the given parameters
///
/// Will not actually start the store watcher. To do that, execute
/// Run().
///
/// @param params Parameters to construct watcher with
StoreWatcher(StoreWatcherStartParams params);
virtual ~StoreWatcher();
/// Performs work
///
/// @param timeout
::zippylog::device::PumpResult Pump(int32 timeout = 100000);
///@{
/// Device hooks
virtual void OnRunStart();
virtual void OnRunFinish();
///@}
protected:
// Function that performs actions when something is created
//
// Receives the path that was added as a store path (e.g.
// "/bucket/store/20101107T1615") and a stat record that describes
// the filesystem entity.
virtual void HandleAdded(::std::string path, platform::FileStat &stat) = 0;
/// Function that performs actions when something is deleted
///
/// @param path The path that was deleted
virtual void HandleDeleted(::std::string path) = 0;
/// Performs actions when something (probably a stream) is modified
///
/// @param path The path that was modified
/// @param stat The result of a stat() on the modified path
virtual void HandleModified(::std::string path, platform::FileStat &stat) = 0;
/// Sends a change notification across the socket
///
/// @param e Envelope to send
void SendChangeMessage(Envelope &e);
/// The store we are watching
SimpleDirectoryStore * _store;
/// 0MQ context
::zmq::context_t *_ctx;
/// 0MQ endpoint to send notification messages to
::std::string _endpoint;
/// 0MQ endpoint to send logging messages to
::std::string logging_endpoint;
/// Unique identifier of this device
::std::string id;
/// 0MQ socket we are sending notifications on
::zmq::socket_t * socket;
/// 0MQ socket we are sending logging messages on
::zmq::socket_t * logging_sock;
/// The underlying watcher looking for store changes
platform::DirectoryWatcher watcher;
private:
// we don't provide these
StoreWatcher(StoreWatcher const &orig);
StoreWatcher & operator=(StoreWatcher const &orig);
};
}
#endif<commit_msg>documentation<commit_after>// Copyright 2011 Gregory Szorc
//
// 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 STORE_WATCHER_HPP
#define STORE_WATCHER_HPP
#include <zippylog/zippylog.hpp>
#include <zippylog/device/device.hpp>
#include <zippylog/platform.hpp>
#include <zippylog/store.hpp>
#include <zmq.hpp>
namespace zippylog {
/// Parameters to instantiate a StoreWatcher class
class ZIPPYLOG_EXPORT StoreWatcherStartParams {
public:
/// 0MQ context to use
::zmq::context_t *zctx;
/// Store filesystem path to watch
::std::string store_path;
/// 0MQ socket endpoint to send change notifications to
::std::string endpoint;
/// 0MQ endpoint to send log messages to
::std::string logging_endpoint;
/// Semaphore to control whether device should run
::zippylog::platform::ConditionalWait *active;
};
/// A directory watcher for file-based stores
///
/// This class watches the specified store directory for changes.
/// When changes are detected, it executes function callbacks, which
/// must be defined in an inherited class.
///
/// The directory watcher is currently designed to execute on its own
/// thread. Just instantiate a directory watcher and invoke Run(). This
/// function will block until the active semaphore contained in the start
/// parameters goes to false.
///
/// @todo move to device namespace
class ZIPPYLOG_EXPORT StoreWatcher : public ::zippylog::device::Device {
public:
/// Instantiate a store watcher with the given parameters
///
/// Will not actually start the store watcher. To do that, execute
/// Run().
///
/// @param params Parameters to construct watcher with
StoreWatcher(StoreWatcherStartParams params);
virtual ~StoreWatcher();
/// Performs work
///
/// @param timeout
::zippylog::device::PumpResult Pump(int32 timeout = 100000);
///@{
/// Device hooks
virtual void OnRunStart();
virtual void OnRunFinish();
///@}
protected:
/// Function that performs actions when something is created
///
/// Receives the path that was added as a store path (e.g.
/// "/bucket/store/20101107T1615") and a stat record that describes
/// the filesystem entity.
///
/// @param path Store path that was added
/// @param stat Filesystem stat result of new path
virtual void HandleAdded(::std::string path, platform::FileStat &stat) = 0;
/// Function that performs actions when something is deleted
///
/// @param path The path that was deleted
virtual void HandleDeleted(::std::string path) = 0;
/// Performs actions when something (probably a stream) is modified
///
/// @param path The path that was modified
/// @param stat The result of a stat() on the modified path
virtual void HandleModified(::std::string path, platform::FileStat &stat) = 0;
/// Sends a change notification across the socket
///
/// @param e Envelope to send
void SendChangeMessage(Envelope &e);
/// The store we are watching
SimpleDirectoryStore * _store;
/// 0MQ context
::zmq::context_t *_ctx;
/// 0MQ endpoint to send notification messages to
::std::string _endpoint;
/// 0MQ endpoint to send logging messages to
::std::string logging_endpoint;
/// Unique identifier of this device
::std::string id;
/// 0MQ socket we are sending notifications on
::zmq::socket_t * socket;
/// 0MQ socket we are sending logging messages on
::zmq::socket_t * logging_sock;
/// The underlying watcher looking for store changes
platform::DirectoryWatcher watcher;
private:
// we don't provide these
StoreWatcher(StoreWatcher const &orig);
StoreWatcher & operator=(StoreWatcher const &orig);
};
}
#endif<|endoftext|> |
<commit_before>/*-------------------------------------------------------
Spruce
Filesystem Wrapper Library for C++11
Copyright (c) 2014, Joseph Davis (@josephdavisco)
All rights reserved. See LICENSE for license info.
---------------------------------------------------------*/
#include "spruce.hh"
#include <utility>
#include <algorithm>
#include <fstream>
#include <sstream>
#include <cstdio>
extern "C" {
#include <sys/stat.h>
}
/*-------------------------------------------------------
Windows includes
---------------------------------------------------------
Notes:
POSIX functions named such as mkdir are deprecated on
Windows. Functions are prefixed with an underscore (_),
mkdir() becomes _mkdir().
"In Windows NT, both the (\) and (/) are valid path
delimiters in character strings in run-time routines."
http://msdn.microsoft.com/en-us/library/
---------------------------------------------------------*/
#if defined(_WIN32) || defined(_WIN64)
#define SPRUCE_WIN
#include <direct.h>
auto SPRUCE_CHDIR = _chdir;
auto SPRUCE_GETCWD = _getcwd;
auto SPRUCE_RMDIR = _rmdir;
auto SPRUCE_MKDIR = _mkdir;
#else
/*-------------------------------------------------------
Unix/Posix includes
---------------------------------------------------------*/
extern "C" {
#include <sys/types.h>
#include <unistd.h>
}
auto SPRUCE_CHDIR = chdir;
auto SPRUCE_GETCWD = getcwd;
auto SPRUCE_RMDIR = rmdir;
auto SPRUCE_MKDIR = []( const char* pathTomake )
{
return mkdir( pathTomake, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH );
};
#endif
/*-------------------------------------------------------
class path default constructor
---------------------------------------------------------*/
spruce::path::path()
{
path_str = "";
}
/*-------------------------------------------------------
class path constructor
---------------------------------------------------------*/
spruce::path::path( std::string path_ ) : path_str( path_ )
{
normalize();
}
/*-------------------------------------------------------
class path destructor
---------------------------------------------------------*/
spruce::path::~path()
{
}
/*-------------------------------------------------------
path.setStr
---------------------------------------------------------*/
void spruce::path::setStr( std::string path_ )
{
path_str = path_;
normalize();
}
/*-------------------------------------------------------
path.getStr
---------------------------------------------------------*/
std::string spruce::path::getStr() const
{
return path_str;
}
/*-------------------------------------------------------
class path.split
---------------------------------------------------------*/
std::vector<std::string> spruce::path::split()
{
std::vector<std::string> v;
std::istringstream ss( path_str );
while ( !ss.eof() )
{
std::string temp;
std::getline( ss, temp, '/' );
v.push_back( temp );
}
return v;
}
/*-------------------------------------------------------
class path.extension
---------------------------------------------------------*/
std::string spruce::path::extension()
{
size_t dot( path_str.rfind( '.' ) );
if ( dot == std::string::npos )
{
return "";
}
return path_str.substr( dot );
}
void spruce::path::append(std::string const & str)
{
if(isFile())
return;
std::string str_append;
if(str.find('/') == 0)
str_append = str.substr(1, str.length());
else
str_append = str;
if(path_str.rfind('/') == path_str.length())
path_str.append(str_append);
else
path_str.append("/" + str_append);
}
void spruce::path::setExtension(std::string const & str)
{
size_t ext = path_str.rfind(extension());
if(ext == std::string::npos)
ext = path_str.length();
path_str = path_str.substr(0, ext) + str;
}
/*-------------------------------------------------------
class path.root
---------------------------------------------------------*/
std::string spruce::path::root()
{
size_t position( path_str.rfind( '/' ) );
if ( position == std::string::npos )
{
return "";
}
return path_str.substr( 0, position );
}
/*-------------------------------------------------------
class path.isFile
---------------------------------------------------------*/
bool spruce::path::isFile() const
{
if ( !exists() ) return false;
#ifdef SPRUCE_WIN
struct _stat attributes;
_stat( path_str.c_str(), &attributes );
#else
struct stat attributes;
stat( path_str.c_str(), &attributes );
#endif
return S_ISREG( attributes.st_mode ) != 0;
}
/*-------------------------------------------------------
class path.isDir
---------------------------------------------------------*/
bool spruce::path::isDir() const
{
if ( !exists() ) return false;
#ifdef SPRUCE_WIN
struct _stat attributes;
_stat( path_str.c_str(), &attributes );
#else
struct stat attributes;
stat( path_str.c_str(), &attributes );
#endif
return S_ISDIR( attributes.st_mode ) != 0;
}
/*-------------------------------------------------------
class path.exists
---------------------------------------------------------*/
bool spruce::path::exists() const
{
#ifdef SPRUCE_WIN
struct _stat attributes;
return _stat( path_str.c_str(), &attributes ) == 0;
#else
struct stat attributes;
return stat( path_str.c_str(), &attributes ) == 0;
#endif
}
/*-------------------------------------------------------
class path.setAsHome
---------------------------------------------------------*/
void spruce::path::setAsHome()
{
char* home;
#ifdef SPRUCE_WIN
home = std::getenv( "HOMEPATH" );
#else
home = std::getenv( "HOME" );
#endif
if ( home != NULL )
{
setStr( home );
}
}
/*-------------------------------------------------------
class path.setAsTemp
---------------------------------------------------------*/
void spruce::path::setAsTemp()
{
char* cwd = std::getenv( "TMPDIR" );
if ( !cwd ) cwd = std::getenv( "TEMPDIR" );
if ( !cwd ) cwd = std::getenv( "TMP" );
if ( !cwd ) cwd = std::getenv( "TEMP" );
if ( !cwd )
{
setStr( "/tmp" );
}
else
{
setStr( cwd );
}
}
/*-------------------------------------------------------
class path.setAsCurrent
---------------------------------------------------------*/
void spruce::path::setAsCurrent()
{
setStr( SPRUCE_GETCWD( NULL, 0 ) );
}
/*-------------------------------------------------------
class path.normalize
---------------------------------------------------------*/
void spruce::path::normalize()
{
std::replace( path_str.begin(), path_str.end(), '\\', '/' );
if ( path_str.back() == '/' ) path_str = path_str.substr(0, path_str.length()-1);
}
/*-------------------------------------------------------
ostream operator<< class path
---------------------------------------------------------*/
std::ostream& operator<<( std::ostream& output, const spruce::path& p )
{
return output << p.getStr();
}
/*-------------------------------------------------------
file::remove
---------------------------------------------------------*/
bool spruce::file::remove( const spruce::path& p )
{
if ( !p.isFile() || ( std::remove( ( p.getStr() ).c_str() ) != 0 ) )
return false;
return true;
}
/*-------------------------------------------------------
file::rename
---------------------------------------------------------*/
bool spruce::file::rename( const spruce::path& source, const spruce::path& dest )
{
if ( std::rename( source.getStr().c_str(), dest.getStr().c_str() ) != 0 )
return false;
return true;
}
/*-------------------------------------------------------
file::copy
---------------------------------------------------------*/
bool spruce::file::copy( const spruce::path& source, const spruce::path& dest )
{
std::ifstream in( source.getStr(), std::ios::binary );
std::ofstream out( dest.getStr(), std::ios::binary );
out << in.rdbuf();
if ( out.fail() )
{
return false;
}
return true;
}
/*-------------------------------------------------------
file::readAsString
---------------------------------------------------------*/
bool spruce::file::readAsString( const spruce::path& p,
std::string& readTo )
{
std::ifstream file( p.getStr() );
std::stringstream ss;
if ( file.is_open() )
{
while ( !file.eof() )
{
ss << static_cast<char>( file.get() );
}
file.close();
}
else
{
return false;
}
readTo = ss.str();
return true;
}
/*-------------------------------------------------------
file::writeAsString
---------------------------------------------------------*/
bool spruce::file::writeAsString( const spruce::path& p,
const std::string& content, bool append )
{
std::ofstream out;
if ( append )
{
out.open( ( p.getStr() ).c_str(),
std::ios_base::out | std::ios_base::app );
}
else
{
out.open( ( p.getStr() ).c_str() );
}
if ( out.fail() )
{
return false;
}
out << content;
out.close();
return true;
}
/*-------------------------------------------------------
dir::mkdir
---------------------------------------------------------*/
bool spruce::dir::mkdir( const spruce::path& p )
{
if ( SPRUCE_MKDIR( ( p.getStr() ).c_str() ) != 0 )
{
return false;
}
return true;
}
/*-------------------------------------------------------
dir::mkdirAll
---------------------------------------------------------*/
bool spruce::dir::mkdirAll( const spruce::path& p )
{
size_t pos = 1;
std::string temp( p.getStr() );
if ( temp == "" ) return false;
while ( ( pos = temp.find( '/', pos + 1 ) ) != std::string::npos )
{
if ( ( path( temp.substr( 0, pos ) ) ).exists() ) continue;
// if making a directory on the path fails we cannot continue
if ( SPRUCE_MKDIR( ( temp.substr( 0, pos ) ).c_str() ) != 0 )
return false;
}
if ( SPRUCE_MKDIR( temp.c_str() ) != 0 ) return false;
return true;
}
/*-------------------------------------------------------
dir::rmdir
---------------------------------------------------------*/
bool spruce::dir::rmdir( const spruce::path& p )
{
if ( SPRUCE_RMDIR( ( p.getStr() ).c_str() ) != 0 )
{
return false;
}
return true;
}
/*-------------------------------------------------------
dir::rename
---------------------------------------------------------*/
bool spruce::dir::rename( const spruce::path& source, const spruce::path& dest )
{
// cstdio accepts the name of a file or directory
return spruce::file::rename( source, dest );
}
/*-------------------------------------------------------
dir::chdir
---------------------------------------------------------*/
bool spruce::dir::chdir( const spruce::path& p )
{
if ( SPRUCE_CHDIR( ( p.getStr() ).c_str() ) != 0 ) return false;
return true;
}
<commit_msg>added alternative preprocessor macros for to S_ISREG and S_ISDIR<commit_after>/*-------------------------------------------------------
Spruce
Filesystem Wrapper Library for C++11
Copyright (c) 2014, Joseph Davis (@josephdavisco)
All rights reserved. See LICENSE for license info.
---------------------------------------------------------*/
#include "spruce.hh"
#include <utility>
#include <algorithm>
#include <fstream>
#include <sstream>
#include <cstdio>
extern "C" {
#include <sys/stat.h>
}
/*-------------------------------------------------------
Windows includes
---------------------------------------------------------
Notes:
POSIX functions named such as mkdir are deprecated on
Windows. Functions are prefixed with an underscore (_),
mkdir() becomes _mkdir().
"In Windows NT, both the (\) and (/) are valid path
delimiters in character strings in run-time routines."
http://msdn.microsoft.com/en-us/library/
---------------------------------------------------------*/
#if defined(_WIN32) || defined(_WIN64)
#define SPRUCE_WIN
#include <direct.h>
auto SPRUCE_CHDIR = _chdir;
auto SPRUCE_GETCWD = _getcwd;
auto SPRUCE_RMDIR = _rmdir;
auto SPRUCE_MKDIR = _mkdir;
#else
/*-------------------------------------------------------
Unix/Posix includes
---------------------------------------------------------*/
extern "C" {
#include <sys/types.h>
#include <unistd.h>
}
auto SPRUCE_CHDIR = chdir;
auto SPRUCE_GETCWD = getcwd;
auto SPRUCE_RMDIR = rmdir;
auto SPRUCE_MKDIR = []( const char* pathTomake )
{
return mkdir( pathTomake, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH );
};
#endif
#ifndef S_ISDIR
#define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
#endif
#ifndef S_ISREG
#define S_ISREG(mode) (((mode) & S_IFMT) == S_IFREG)
#endif
/*-------------------------------------------------------
class path default constructor
---------------------------------------------------------*/
spruce::path::path()
{
path_str = "";
}
/*-------------------------------------------------------
class path constructor
---------------------------------------------------------*/
spruce::path::path( std::string path_ ) : path_str( path_ )
{
normalize();
}
/*-------------------------------------------------------
class path destructor
---------------------------------------------------------*/
spruce::path::~path()
{
}
/*-------------------------------------------------------
path.setStr
---------------------------------------------------------*/
void spruce::path::setStr( std::string path_ )
{
path_str = path_;
normalize();
}
/*-------------------------------------------------------
path.getStr
---------------------------------------------------------*/
std::string spruce::path::getStr() const
{
return path_str;
}
/*-------------------------------------------------------
class path.split
---------------------------------------------------------*/
std::vector<std::string> spruce::path::split()
{
std::vector<std::string> v;
std::istringstream ss( path_str );
while ( !ss.eof() )
{
std::string temp;
std::getline( ss, temp, '/' );
v.push_back( temp );
}
return v;
}
/*-------------------------------------------------------
class path.extension
---------------------------------------------------------*/
std::string spruce::path::extension()
{
size_t dot( path_str.rfind( '.' ) );
if ( dot == std::string::npos )
{
return "";
}
return path_str.substr( dot );
}
void spruce::path::append(std::string const & str)
{
if(isFile())
return;
std::string str_append;
if(str.find('/') == 0)
str_append = str.substr(1, str.length());
else
str_append = str;
if(path_str.rfind('/') == path_str.length())
path_str.append(str_append);
else
path_str.append("/" + str_append);
}
void spruce::path::setExtension(std::string const & str)
{
size_t ext = path_str.rfind(extension());
if(ext == std::string::npos)
ext = path_str.length();
path_str = path_str.substr(0, ext) + str;
}
/*-------------------------------------------------------
class path.root
---------------------------------------------------------*/
std::string spruce::path::root()
{
size_t position( path_str.rfind( '/' ) );
if ( position == std::string::npos )
{
return "";
}
return path_str.substr( 0, position );
}
/*-------------------------------------------------------
class path.isFile
---------------------------------------------------------*/
bool spruce::path::isFile() const
{
if ( !exists() ) return false;
#ifdef SPRUCE_WIN
struct _stat attributes;
_stat( path_str.c_str(), &attributes );
#else
struct stat attributes;
stat( path_str.c_str(), &attributes );
#endif
return S_ISREG( attributes.st_mode ) != 0;
}
/*-------------------------------------------------------
class path.isDir
---------------------------------------------------------*/
bool spruce::path::isDir() const
{
if ( !exists() ) return false;
#ifdef SPRUCE_WIN
struct _stat attributes;
_stat( path_str.c_str(), &attributes );
#else
struct stat attributes;
stat( path_str.c_str(), &attributes );
#endif
return S_ISDIR( attributes.st_mode ) != 0;
}
/*-------------------------------------------------------
class path.exists
---------------------------------------------------------*/
bool spruce::path::exists() const
{
#ifdef SPRUCE_WIN
struct _stat attributes;
return _stat( path_str.c_str(), &attributes ) == 0;
#else
struct stat attributes;
return stat( path_str.c_str(), &attributes ) == 0;
#endif
}
/*-------------------------------------------------------
class path.setAsHome
---------------------------------------------------------*/
void spruce::path::setAsHome()
{
char* home;
#ifdef SPRUCE_WIN
home = std::getenv( "HOMEPATH" );
#else
home = std::getenv( "HOME" );
#endif
if ( home != NULL )
{
setStr( home );
}
}
/*-------------------------------------------------------
class path.setAsTemp
---------------------------------------------------------*/
void spruce::path::setAsTemp()
{
char* cwd = std::getenv( "TMPDIR" );
if ( !cwd ) cwd = std::getenv( "TEMPDIR" );
if ( !cwd ) cwd = std::getenv( "TMP" );
if ( !cwd ) cwd = std::getenv( "TEMP" );
if ( !cwd )
{
setStr( "/tmp" );
}
else
{
setStr( cwd );
}
}
/*-------------------------------------------------------
class path.setAsCurrent
---------------------------------------------------------*/
void spruce::path::setAsCurrent()
{
setStr( SPRUCE_GETCWD( NULL, 0 ) );
}
/*-------------------------------------------------------
class path.normalize
---------------------------------------------------------*/
void spruce::path::normalize()
{
std::replace( path_str.begin(), path_str.end(), '\\', '/' );
if ( path_str.back() == '/' ) path_str = path_str.substr(0, path_str.length()-1);
}
/*-------------------------------------------------------
ostream operator<< class path
---------------------------------------------------------*/
std::ostream& operator<<( std::ostream& output, const spruce::path& p )
{
return output << p.getStr();
}
/*-------------------------------------------------------
file::remove
---------------------------------------------------------*/
bool spruce::file::remove( const spruce::path& p )
{
if ( !p.isFile() || ( std::remove( ( p.getStr() ).c_str() ) != 0 ) )
return false;
return true;
}
/*-------------------------------------------------------
file::rename
---------------------------------------------------------*/
bool spruce::file::rename( const spruce::path& source, const spruce::path& dest )
{
if ( std::rename( source.getStr().c_str(), dest.getStr().c_str() ) != 0 )
return false;
return true;
}
/*-------------------------------------------------------
file::copy
---------------------------------------------------------*/
bool spruce::file::copy( const spruce::path& source, const spruce::path& dest )
{
std::ifstream in( source.getStr(), std::ios::binary );
std::ofstream out( dest.getStr(), std::ios::binary );
out << in.rdbuf();
if ( out.fail() )
{
return false;
}
return true;
}
/*-------------------------------------------------------
file::readAsString
---------------------------------------------------------*/
bool spruce::file::readAsString( const spruce::path& p,
std::string& readTo )
{
std::ifstream file( p.getStr() );
std::stringstream ss;
if ( file.is_open() )
{
while ( !file.eof() )
{
ss << static_cast<char>( file.get() );
}
file.close();
}
else
{
return false;
}
readTo = ss.str();
return true;
}
/*-------------------------------------------------------
file::writeAsString
---------------------------------------------------------*/
bool spruce::file::writeAsString( const spruce::path& p,
const std::string& content, bool append )
{
std::ofstream out;
if ( append )
{
out.open( ( p.getStr() ).c_str(),
std::ios_base::out | std::ios_base::app );
}
else
{
out.open( ( p.getStr() ).c_str() );
}
if ( out.fail() )
{
return false;
}
out << content;
out.close();
return true;
}
/*-------------------------------------------------------
dir::mkdir
---------------------------------------------------------*/
bool spruce::dir::mkdir( const spruce::path& p )
{
if ( SPRUCE_MKDIR( ( p.getStr() ).c_str() ) != 0 )
{
return false;
}
return true;
}
/*-------------------------------------------------------
dir::mkdirAll
---------------------------------------------------------*/
bool spruce::dir::mkdirAll( const spruce::path& p )
{
size_t pos = 1;
std::string temp( p.getStr() );
if ( temp == "" ) return false;
while ( ( pos = temp.find( '/', pos + 1 ) ) != std::string::npos )
{
if ( ( path( temp.substr( 0, pos ) ) ).exists() ) continue;
// if making a directory on the path fails we cannot continue
if ( SPRUCE_MKDIR( ( temp.substr( 0, pos ) ).c_str() ) != 0 )
return false;
}
if ( SPRUCE_MKDIR( temp.c_str() ) != 0 ) return false;
return true;
}
/*-------------------------------------------------------
dir::rmdir
---------------------------------------------------------*/
bool spruce::dir::rmdir( const spruce::path& p )
{
if ( SPRUCE_RMDIR( ( p.getStr() ).c_str() ) != 0 )
{
return false;
}
return true;
}
/*-------------------------------------------------------
dir::rename
---------------------------------------------------------*/
bool spruce::dir::rename( const spruce::path& source, const spruce::path& dest )
{
// cstdio accepts the name of a file or directory
return spruce::file::rename( source, dest );
}
/*-------------------------------------------------------
dir::chdir
---------------------------------------------------------*/
bool spruce::dir::chdir( const spruce::path& p )
{
if ( SPRUCE_CHDIR( ( p.getStr() ).c_str() ) != 0 ) return false;
return true;
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.