text
stringlengths 54
60.6k
|
|---|
<commit_before>/**
* This file contains functions to create and save a png file
*/
#include "png.h"
#ifndef Z_BEST_SPEED
#define Z_BEST_SPEED 6
#endif
namespace PNG {
PNG::PNG(const std::filesystem::path &file) : file(file), imageHandle(nullptr) {
set_type(UNKNOWN);
_line = _height = _width = _padding = 0;
pngPtr = NULL;
pngInfoPtr = NULL;
}
void PNG::_close() {
if (imageHandle) {
fclose(imageHandle);
imageHandle = nullptr;
}
_line = 0;
}
bool PNG::error_callback() {
// libpng will issue a longjmp on error, so code flow will end up here if
// something goes wrong in the code below
if (setjmp(png_jmpbuf(pngPtr))) {
logger::error("libpng encountered an error\n");
return true;
}
return false;
}
ColorType PNG::set_type(int type) {
switch (type) {
case GRAYSCALEALPHA:
_type = GRAYSCALEALPHA;
_bytesPerPixel = 2;
break;
case GRAYSCALE:
_type = GRAYSCALE;
_bytesPerPixel = 1;
break;
case PALETTE:
_type = PALETTE;
_bytesPerPixel = 1;
break;
case RGB:
_type = RGB;
_bytesPerPixel = 3;
break;
case RGBA:
_type = RGBA;
_bytesPerPixel = 4;
break;
default:
_type = UNKNOWN;
_bytesPerPixel = 0;
}
return _type;
}
PNGWriter::PNGWriter(const std::filesystem::path &file) : super::PNG(file) {
buffer = nullptr;
set_type(RGBA);
}
PNGWriter::~PNGWriter() {
if (buffer)
delete[] buffer;
}
void PNGWriter::_close() {
png_write_end(pngPtr, NULL);
png_destroy_write_struct(&pngPtr, &pngInfoPtr);
super::_close();
}
void PNGWriter::set_text(const Comments &_comments) { comments = _comments; }
void write_text(png_structp pngPtr, png_infop pngInfoPtr,
const Comments &comments) {
std::vector<png_text> text(comments.size());
size_t index = 0;
for (auto const &pair : comments) {
text[index].compression = PNG_TEXT_COMPRESSION_NONE;
text[index].key = (png_charp)pair.first.c_str();
text[index].text = (png_charp)pair.second.c_str();
text[index].text_length = pair.second.length();
index++;
}
png_set_text(pngPtr, pngInfoPtr, &text[0], text.size());
}
void PNGWriter::_open() {
if (!(super::imageHandle = fopen(file.string().c_str(), "wb"))) {
throw(std::runtime_error("Error opening '" + file.string() +
"' for writing: " + std::string(strerror(errno))));
}
if (!(get_width() || get_height())) {
logger::warn("Nothing to output: canvas is empty !\n");
return;
}
logger::deep_debug("PNGWriter: image {}x{}, {}bpp\n", get_width(),
get_height(), 8 * _bytesPerPixel);
FSEEK(imageHandle, 0, SEEK_SET);
// Write header
pngPtr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if (error_callback())
return;
if (pngPtr == NULL) {
return;
}
pngInfoPtr = png_create_info_struct(pngPtr);
if (pngInfoPtr == NULL) {
png_destroy_write_struct(&pngPtr, NULL);
return;
}
png_init_io(pngPtr, imageHandle);
write_text(pngPtr, pngInfoPtr, comments);
// The png file format works by having blocks piled up in a certain order.
// Check out http://www.libpng.org/pub/png/book/chapter11.html for more
// info.
// First, dump the required IHDR block.
png_set_IHDR(pngPtr, pngInfoPtr, get_width(), get_height(), 8,
PNG_COLOR_TYPE_RGBA, PNG_INTERLACE_NONE,
PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
png_write_info(pngPtr, pngInfoPtr);
return;
}
void PNGWriter::pad() {
getBuffer();
memset(buffer, 0, row_size());
for (size_t k = 0; k < _padding; k++)
png_write_row(pngPtr, (png_bytep)buffer);
}
uint8_t *PNGWriter::getBuffer() {
if (!buffer) {
buffer = new uint8_t[row_size()];
memset(buffer, 0, row_size());
}
return buffer + _padding * _bytesPerPixel;
}
uint32_t PNGWriter::writeLine() {
if (!_line++) {
_open();
pad();
}
png_write_row(pngPtr, (png_bytep)buffer);
if (_line == _height) {
pad();
_close();
}
return row_size();
}
PNGReader::PNGReader(const std::filesystem::path &file) : PNG(file) {
_open();
_close();
}
PNGReader::PNGReader(const PNGReader &other) : PNG(other.file) {}
PNGReader::~PNGReader() {}
void PNGReader::_close() {
png_destroy_read_struct(&pngPtr, &pngInfoPtr, NULL);
super::_close();
}
void PNGReader::_open() {
if (!(super::imageHandle = fopen(file.string().c_str(), "rb"))) {
throw(std::runtime_error("Error opening '" + file.string() +
"' for reading: " + std::string(strerror(errno))));
}
// Check the validity of the header
png_byte header[8];
if (fread(header, 1, 8, imageHandle) != 8 || !png_check_sig(header, 8)) {
logger::error("PNGReader: File {} is not a PNG\n", file.string());
return;
}
pngPtr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
// Tell libpng the file's header has been handled
png_set_sig_bytes(pngPtr, 8);
if (pngPtr == NULL || error_callback()) {
logger::error("PNGReader: Error reading {}\n", file.string());
return;
}
pngInfoPtr = png_create_info_struct(pngPtr);
png_uint_32 width, height;
int type, interlace, comp, filter, _bitDepth;
png_init_io(pngPtr, imageHandle);
png_read_info(pngPtr, pngInfoPtr);
// Check image format (square, RGBA)
png_uint_32 ret = png_get_IHDR(pngPtr, pngInfoPtr, &width, &height,
&_bitDepth, &type, &interlace, &comp, &filter);
if (ret == 0) {
logger::error("Error getting IDHR block of file\n");
png_destroy_read_struct(&pngPtr, &pngInfoPtr, NULL);
return;
}
// Use the gathered info to fill the struct
_width = width;
_height = height;
set_type(type);
logger::deep_debug("PNGReader: PNG file of size {}x{}, {}bpp\n", get_width(),
get_height(), 8 * _bytesPerPixel);
}
uint32_t PNGReader::getLine(uint8_t *buffer, size_t size) {
// Open and initialize if this is the first read
if (!_line++)
_open();
if (size < get_width()) {
logger::error("Buffer too small");
return 0;
}
png_bytep row_pointer = (png_bytep)buffer;
png_read_row(pngPtr, row_pointer, NULL);
if (_line == _height)
_close();
return get_width();
}
} // namespace PNG
<commit_msg>Updated PNG status and errors<commit_after>/**
* This file contains functions to create and save a png file
*/
#include "png.h"
#ifndef Z_BEST_SPEED
#define Z_BEST_SPEED 6
#endif
namespace PNG {
PNG::PNG(const std::filesystem::path &file) : file(file), imageHandle(nullptr) {
set_type(UNKNOWN);
_line = _height = _width = _padding = 0;
pngPtr = NULL;
pngInfoPtr = NULL;
}
void PNG::_close() {
if (imageHandle) {
fclose(imageHandle);
imageHandle = nullptr;
}
_line = 0;
}
bool PNG::error_callback() {
// libpng will issue a longjmp on error, so code flow will end up here if
// something goes wrong in the code below
if (setjmp(png_jmpbuf(pngPtr))) {
logger::error("[PNG] libpng encountered an error\n");
return true;
}
return false;
}
ColorType PNG::set_type(int type) {
switch (type) {
case GRAYSCALEALPHA:
_type = GRAYSCALEALPHA;
_bytesPerPixel = 2;
break;
case GRAYSCALE:
_type = GRAYSCALE;
_bytesPerPixel = 1;
break;
case PALETTE:
_type = PALETTE;
_bytesPerPixel = 1;
break;
case RGB:
_type = RGB;
_bytesPerPixel = 3;
break;
case RGBA:
_type = RGBA;
_bytesPerPixel = 4;
break;
default:
_type = UNKNOWN;
_bytesPerPixel = 0;
}
return _type;
}
PNGWriter::PNGWriter(const std::filesystem::path &file) : super::PNG(file) {
buffer = nullptr;
set_type(RGBA);
}
PNGWriter::~PNGWriter() {
if (buffer)
delete[] buffer;
}
void PNGWriter::_close() {
png_write_end(pngPtr, NULL);
png_destroy_write_struct(&pngPtr, &pngInfoPtr);
super::_close();
}
void PNGWriter::set_text(const Comments &_comments) { comments = _comments; }
void write_text(png_structp pngPtr, png_infop pngInfoPtr,
const Comments &comments) {
std::vector<png_text> text(comments.size());
size_t index = 0;
for (auto const &pair : comments) {
text[index].compression = PNG_TEXT_COMPRESSION_NONE;
text[index].key = (png_charp)pair.first.c_str();
text[index].text = (png_charp)pair.second.c_str();
text[index].text_length = pair.second.length();
index++;
}
png_set_text(pngPtr, pngInfoPtr, &text[0], text.size());
}
void PNGWriter::_open() {
if (!(get_width() || get_height())) {
logger::warn("[PNGWriter] Nothing to output: canvas is empty !\n");
return;
}
logger::deep_debug("[PNGWriter] image {}x{}, {}bpp, writing to {}\n",
get_width(), get_height(), 8 * _bytesPerPixel,
file.string());
if (!(super::imageHandle = fopen(file.c_str(), "wb"))) {
logger::error("[PNGWriter] Error opening '{}' for writing: {}\n",
file.string(), strerror(errno));
return;
}
FSEEK(imageHandle, 0, SEEK_SET);
// Write header
pngPtr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if (error_callback())
return;
if (pngPtr == NULL) {
return;
}
pngInfoPtr = png_create_info_struct(pngPtr);
if (pngInfoPtr == NULL) {
png_destroy_write_struct(&pngPtr, NULL);
return;
}
png_init_io(pngPtr, imageHandle);
write_text(pngPtr, pngInfoPtr, comments);
// The png file format works by having blocks piled up in a certain order.
// Check out http://www.libpng.org/pub/png/book/chapter11.html for more
// info.
// First, dump the required IHDR block.
png_set_IHDR(pngPtr, pngInfoPtr, get_width(), get_height(), 8,
PNG_COLOR_TYPE_RGBA, PNG_INTERLACE_NONE,
PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
png_write_info(pngPtr, pngInfoPtr);
return;
}
void PNGWriter::pad() {
getBuffer();
memset(buffer, 0, row_size());
for (size_t k = 0; k < _padding; k++)
png_write_row(pngPtr, (png_bytep)buffer);
}
uint8_t *PNGWriter::getBuffer() {
if (!buffer) {
buffer = new uint8_t[row_size()];
memset(buffer, 0, row_size());
}
return buffer + _padding * _bytesPerPixel;
}
uint32_t PNGWriter::writeLine() {
if (!_line++) {
_open();
pad();
}
png_write_row(pngPtr, (png_bytep)buffer);
if (_line == _height) {
pad();
_close();
}
return row_size();
}
PNGReader::PNGReader(const std::filesystem::path &file) : PNG(file) {
_open();
_close();
}
PNGReader::PNGReader(const PNGReader &other) : PNG(other.file) {}
PNGReader::~PNGReader() {}
void PNGReader::_close() {
png_destroy_read_struct(&pngPtr, &pngInfoPtr, NULL);
super::_close();
}
void PNGReader::_open() {
logger::deep_debug("[PNGReader] Opening '{}'\n", file.string());
if (!(super::imageHandle = fopen(file.string().c_str(), "rb"))) {
logger::error("[PNGReader] Error opening '{}' for reading: {}\n",
file.string(), strerror(errno));
return;
}
// Check the validity of the header
png_byte header[8];
if (fread(header, 1, 8, imageHandle) != 8 || !png_check_sig(header, 8)) {
logger::error("[PNGReader] File '{}' is not a PNG\n", file.string());
return;
}
pngPtr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
// Tell libpng the file's header has been handled
png_set_sig_bytes(pngPtr, 8);
if (pngPtr == NULL || error_callback()) {
logger::error("[PNGReader] Error reading '{}'\n", file.string());
return;
}
pngInfoPtr = png_create_info_struct(pngPtr);
png_uint_32 width, height;
int type, interlace, comp, filter, _bitDepth;
png_init_io(pngPtr, imageHandle);
png_read_info(pngPtr, pngInfoPtr);
// Check image format (square, RGBA)
png_uint_32 ret = png_get_IHDR(pngPtr, pngInfoPtr, &width, &height,
&_bitDepth, &type, &interlace, &comp, &filter);
if (ret == 0) {
logger::error("[PNGReader] Error getting IDHR block of '{}'\n",
file.string());
png_destroy_read_struct(&pngPtr, &pngInfoPtr, NULL);
return;
}
// Use the gathered info to fill the struct
_width = width;
_height = height;
set_type(type);
logger::deep_debug("[PNGReader] '{}': PNG file of size {}x{}, {}bpp\n",
file.string(), get_width(), get_height(),
8 * _bytesPerPixel);
}
uint32_t PNGReader::getLine(uint8_t *buffer, size_t size) {
// Open and initialize if this is the first read
if (!_line++)
_open();
if (size < get_width()) {
logger::error("[PNGReader] Buffer too small reading '{}' !\n",
file.string());
return 0;
}
png_bytep row_pointer = (png_bytep)buffer;
png_read_row(pngPtr, row_pointer, NULL);
if (_line == _height)
_close();
return get_width();
}
} // namespace PNG
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: pageproperties.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2005-09-09 00:15:40 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _SDR_PROPERTIES_PAGEPROPERTIES_HXX
#include <svx/sdr/properties/pageproperties.hxx>
#endif
#ifndef _SFXITEMSET_HXX
#include <svtools/itemset.hxx>
#endif
#ifndef _SVDOBJ_HXX
#include <svdobj.hxx>
#endif
#ifndef _SVDPOOL_HXX
#include <svdpool.hxx>
#endif
//////////////////////////////////////////////////////////////////////////////
namespace sdr
{
namespace properties
{
// create a new itemset
SfxItemSet& PageProperties::CreateObjectSpecificItemSet(SfxItemPool& rPool)
{
// overloaded to legally return a valid ItemSet
return *(new SfxItemSet(rPool));
}
PageProperties::PageProperties(SdrObject& rObj)
: EmptyProperties(rObj)
{
}
PageProperties::PageProperties(const PageProperties& rProps, SdrObject& rObj)
: EmptyProperties(rProps, rObj)
{
}
PageProperties::~PageProperties()
{
}
BaseProperties& PageProperties::Clone(SdrObject& rObj) const
{
return *(new PageProperties(*this, rObj));
}
// get itemset. Overloaded here to allow creating the empty itemset
// without asserting
const SfxItemSet& PageProperties::GetObjectItemSet() const
{
if(!mpEmptyItemSet)
{
((PageProperties*)this)->mpEmptyItemSet = &(((PageProperties*)this)->CreateObjectSpecificItemSet(*GetSdrObject().GetObjectItemPool()));
}
DBG_ASSERT(mpEmptyItemSet, "Could not create an SfxItemSet(!)");
return *mpEmptyItemSet;
}
void PageProperties::ItemChange(const sal_uInt16 nWhich, const SfxPoolItem* pNewItem)
{
// #86481# simply ignore item setting on page objects
}
SfxStyleSheet* PageProperties::GetStyleSheet() const
{
// overloaded to legally return a 0L pointer here
return 0L;
}
void PageProperties::ClearObjectItem(const sal_uInt16 nWhich)
{
// simply ignore item clearing on page objects
}
} // end of namespace properties
} // end of namespace sdr
////////////////////////////////////////////////////////////////////////////////////////////////////
// eof
<commit_msg>INTEGRATION: CWS warnings01 (1.5.222); FILE MERGED 2006/02/21 16:59:34 aw 1.5.222.1: #i55991# Adaptions to warning free code<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: pageproperties.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: hr $ $Date: 2006-06-19 16:31:11 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _SDR_PROPERTIES_PAGEPROPERTIES_HXX
#include <svx/sdr/properties/pageproperties.hxx>
#endif
#ifndef _SFXITEMSET_HXX
#include <svtools/itemset.hxx>
#endif
#ifndef _SVDOBJ_HXX
#include <svdobj.hxx>
#endif
#ifndef _SVDPOOL_HXX
#include <svdpool.hxx>
#endif
//////////////////////////////////////////////////////////////////////////////
namespace sdr
{
namespace properties
{
// create a new itemset
SfxItemSet& PageProperties::CreateObjectSpecificItemSet(SfxItemPool& rPool)
{
// overloaded to legally return a valid ItemSet
return *(new SfxItemSet(rPool));
}
PageProperties::PageProperties(SdrObject& rObj)
: EmptyProperties(rObj)
{
}
PageProperties::PageProperties(const PageProperties& rProps, SdrObject& rObj)
: EmptyProperties(rProps, rObj)
{
}
PageProperties::~PageProperties()
{
}
BaseProperties& PageProperties::Clone(SdrObject& rObj) const
{
return *(new PageProperties(*this, rObj));
}
// get itemset. Overloaded here to allow creating the empty itemset
// without asserting
const SfxItemSet& PageProperties::GetObjectItemSet() const
{
if(!mpEmptyItemSet)
{
((PageProperties*)this)->mpEmptyItemSet = &(((PageProperties*)this)->CreateObjectSpecificItemSet(*GetSdrObject().GetObjectItemPool()));
}
DBG_ASSERT(mpEmptyItemSet, "Could not create an SfxItemSet(!)");
return *mpEmptyItemSet;
}
void PageProperties::ItemChange(const sal_uInt16 /*nWhich*/, const SfxPoolItem* /*pNewItem*/)
{
// #86481# simply ignore item setting on page objects
}
SfxStyleSheet* PageProperties::GetStyleSheet() const
{
// overloaded to legally return a 0L pointer here
return 0L;
}
void PageProperties::ClearObjectItem(const sal_uInt16 /*nWhich*/)
{
// simply ignore item clearing on page objects
}
} // end of namespace properties
} // end of namespace sdr
////////////////////////////////////////////////////////////////////////////////////////////////////
// eof
<|endoftext|>
|
<commit_before><commit_msg>ww8: warning C4701: potentially uninitialized local variable<commit_after><|endoftext|>
|
<commit_before>#include "scenetree.h"
#include <game/gameserver.h>
#include <game/digitanks/digitanksgame.h>
#include "digitankswindow.h"
#include "hud.h"
#include <renderer\renderer.h>
#include <game/digitanks/dt_camera.h>
#include "instructor.h"
CSceneTree::CSceneTree()
: CTree(CRenderer::LoadTextureIntoGL(L"textures/hud/arrow.png"), 0, 0)
{
}
void CSceneTree::Layout()
{
SetSize(90, glgui::CRootPanel::Get()->GetHeight()-300);
SetPos(15, 60);
BaseClass::Layout();
}
void CSceneTree::BuildTree(bool bForce)
{
CDigitanksTeam* pCurrentLocalTeam = DigitanksGame()->GetCurrentLocalDigitanksTeam();
if (!pCurrentLocalTeam)
return;
if (m_hTeam == pCurrentLocalTeam && !bForce)
return;
ClearTree();
m_hTeam = pCurrentLocalTeam;
for (size_t i = 0; i < GameServer()->GetMaxEntities(); i++)
{
CSelectable* pEntity = CBaseEntity::GetEntityType<CSelectable>(i);
if (!pEntity)
continue;
if (pEntity->GetDigitanksTeam() != pCurrentLocalTeam)
continue;
unittype_t eUnit = pEntity->GetUnitType();
CSceneTreeGroup* pTreeGroup = GetUnitNode(eUnit);
pTreeGroup->AddNode(new CSceneTreeUnit(pEntity, pTreeGroup, this));
}
Layout();
}
CSceneTreeGroup* CSceneTree::GetUnitNode(unittype_t eUnit)
{
for (size_t i = 0; i < m_apNodes.size(); i++)
{
CSceneTreeGroup* pTreeGroup = dynamic_cast<CSceneTreeGroup*>(m_apNodes[i]);
if (eUnit == pTreeGroup->GetUnitType())
return pTreeGroup;
}
// It's not there. Insert it.
for (size_t i = 0; i < m_apNodes.size(); i++)
{
CSceneTreeGroup* pTreeGroup = dynamic_cast<CSceneTreeGroup*>(m_apNodes[i]);
if (eUnit < pTreeGroup->GetUnitType())
{
CSceneTreeGroup* pReturn = new CSceneTreeGroup(eUnit, this);
AddNode(pReturn, i);
return pReturn;
}
}
CSceneTreeGroup* pReturn = new CSceneTreeGroup(eUnit, this);
AddNode(pReturn);
return pReturn;
}
void CSceneTree::Paint(int x, int y, int w, int h)
{
glgui::CRootPanel::PaintRect(x, y, w, h, m_clrBackground);
if (m_iHilighted != ~0)
{
IControl* pNode = m_apControls[m_iHilighted];
int cx, cy, cw, ch;
pNode->GetAbsDimensions(cx, cy, cw, ch);
glgui::CRootPanel::PaintRect(cx+ch, cy, ch, ch, Color(255, 255, 255, 100));
}
// Skip CTree, we override its hilight and selection methods.
CPanel::Paint(x, y, w, h);
}
void CSceneTree::OnAddEntityToTeam(CDigitanksTeam* pTeam, CBaseEntity* pEntity)
{
CSelectable* pSelectable = dynamic_cast<CSelectable*>(pEntity);
if (!pSelectable)
return;
if (pTeam != m_hTeam)
return;
unittype_t eUnit = pSelectable->GetUnitType();
CSceneTreeGroup* pTreeGroup = GetUnitNode(eUnit);
pTreeGroup->AddNode(new CSceneTreeUnit(pSelectable, pTreeGroup, this));
Layout();
}
void CSceneTree::OnRemoveEntityFromTeam(CDigitanksTeam* pTeam, CBaseEntity* pEntity)
{
CSelectable* pSelectable = dynamic_cast<CSelectable*>(pEntity);
if (!pSelectable)
return;
if (pTeam != m_hTeam)
return;
unittype_t eUnit = pSelectable->GetUnitType();
CSceneTreeGroup* pTreeGroup = GetUnitNode(eUnit);
for (size_t i = 0; i < pTreeGroup->m_apNodes.size(); i++)
{
CSceneTreeUnit* pUnit = dynamic_cast<CSceneTreeUnit*>(pTreeGroup->m_apNodes[i]);
if (!pUnit)
continue;
if (pUnit->GetEntity() == pSelectable)
{
RemoveNode(pUnit);
pUnit->Destructor();
pUnit->Delete();
if (pTreeGroup->m_apNodes.size() == 0)
{
RemoveNode(pTreeGroup);
pTreeGroup->Destructor();
pTreeGroup->Delete();
}
break;
}
}
Layout();
}
CSceneTreeGroup::CSceneTreeGroup(unittype_t eUnit, glgui::CTree* pTree)
: CSceneTreeNode(NULL, pTree)
{
m_eUnit = eUnit;
}
void CSceneTreeGroup::Paint(int x, int y, int w, int h, bool bFloating)
{
if (!IsVisible())
return;
BaseClass::Paint(x, y, w, h, bFloating);
CDigitanksTeam* pCurrentLocalTeam = DigitanksGame()->GetCurrentLocalDigitanksTeam();
CRenderingContext c(GameServer()->GetRenderer());
c.SetBlend(BLEND_ALPHA);
CHUD::PaintUnitSheet(m_eUnit, x+h, y, h, h, pCurrentLocalTeam?pCurrentLocalTeam->GetColor():Color(255,255,255,255));
}
CSceneTreeUnit::CSceneTreeUnit(CEntityHandle<CSelectable> hEntity, glgui::CTreeNode* pParent, glgui::CTree* pTree)
: CSceneTreeNode(pParent, pTree)
{
m_hEntity = hEntity;
}
void CSceneTreeUnit::Paint(int x, int y, int w, int h, bool bFloating)
{
if (!IsVisible())
return;
BaseClass::Paint(x, y, w, h, bFloating);
if (m_hEntity == NULL)
return;
CRenderingContext c(GameServer()->GetRenderer());
c.SetBlend(BLEND_ALPHA);
Color clrTeam = m_hEntity->GetTeam()?m_hEntity->GetTeam()->GetColor():Color(255,255,255,255);
CDigitank* pTank = dynamic_cast<CDigitank*>(m_hEntity.GetPointer());
if (pTank && !pTank->NeedsOrders())
clrTeam.SetAlpha(100);
CDigitanksTeam* pCurrentLocalTeam = DigitanksGame()->GetCurrentLocalDigitanksTeam();
if (pCurrentLocalTeam && pCurrentLocalTeam->IsSelected(m_hEntity))
{
Color clrSelection(255, 255, 255, 64);
if (pCurrentLocalTeam->IsPrimarySelection(m_hEntity))
clrSelection = Color(255, 255, 255, 128);
glgui::CRootPanel::PaintRect(x+h, y, h, h, clrSelection);
clrSelection = Color(255, 255, 255, 128);
if (pCurrentLocalTeam->IsPrimarySelection(m_hEntity))
clrSelection = Color(255, 255, 255, 255);
glgui::CRootPanel::PaintRect(x+h, y, h, 1, clrSelection);
glgui::CRootPanel::PaintRect(x+h, y, 1, h, clrSelection);
glgui::CRootPanel::PaintRect(x+h+h, y, 1, h, clrSelection);
glgui::CRootPanel::PaintRect(x+h, y+h, h, 1, clrSelection);
}
CHUD::PaintUnitSheet(m_hEntity->GetUnitType(), x+h+2, y+2, h-4, h-4, clrTeam);
glgui::CRootPanel::PaintRect(x+h, y - 3, (int)(h*m_hEntity->GetHealth()/m_hEntity->GetTotalHealth()), 3, Color(100, 255, 100));
if (pTank)
{
float flAttackPower = pTank->GetBaseAttackPower(true);
float flDefensePower = pTank->GetBaseDefensePower(true);
float flMovementPower = pTank->GetUsedMovementEnergy(true);
float flTotalPower = pTank->GetStartingPower();
flAttackPower = flAttackPower/flTotalPower;
flDefensePower = flDefensePower/flTotalPower;
flMovementPower = flMovementPower/pTank->GetMaxMovementEnergy();
glgui::CRootPanel::PaintRect(x+h, y, (int)(h*flAttackPower), 3, Color(255, 0, 0));
glgui::CRootPanel::PaintRect(x+h+(int)(h*flAttackPower), y, (int)(h*flDefensePower), 3, Color(0, 0, 255));
glgui::CRootPanel::PaintRect(x+h, y + 3, (int)(h*flMovementPower), 3, Color(255, 255, 0));
size_t iSize = 22;
CHUD::PaintWeaponSheet(pTank->GetCurrentWeapon(), x+h+h+4, y+4, iSize, iSize, Color(255, 255, 255, 255));
size_t iX = x+h+h+h+4;
if (pTank->IsFortified() || pTank->IsFortifying())
{
glgui::CRootPanel::PaintTexture(CDigitank::GetFortifyIcon(), iX, y+4, iSize, iSize);
iX += h;
}
if (pTank->IsSentried())
{
glgui::CRootPanel::PaintTexture(CDigitank::GetSentryIcon(), iX, y+4, iSize, iSize);
iX += h;
}
}
CStructure* pStructure = dynamic_cast<CStructure*>(m_hEntity.GetPointer());
if (pStructure && (pStructure->IsConstructing() || pStructure->IsUpgrading()))
{
int iTurnsRemaining = 0;
int iTotalTurns = 0;
if (pStructure->IsConstructing())
{
iTurnsRemaining = pStructure->GetTurnsToConstruct();
iTotalTurns = pStructure->GetTurnsRemainingToConstruct();
}
else if (pStructure->IsUpgrading())
{
iTurnsRemaining = pStructure->GetTurnsToUpgrade();
iTotalTurns = pStructure->GetTurnsRemainingToUpgrade();
}
int iTurns = iTotalTurns-iTurnsRemaining;
glgui::CRootPanel::PaintRect(x+h, y+h-1, (int)((float)h*iTurns/iTotalTurns), 3, Color(255, 255, 100));
}
}
void CSceneTreeUnit::Selected()
{
if (m_hEntity != NULL)
{
CDigitanksTeam* pCurrentLocalTeam = DigitanksGame()->GetCurrentLocalDigitanksTeam();
if (DigitanksWindow()->IsShiftDown())
pCurrentLocalTeam->AddToSelection(m_hEntity);
else
{
pCurrentLocalTeam->SetPrimarySelection(m_hEntity);
DigitanksGame()->GetDigitanksCamera()->SetTarget(m_hEntity->GetOrigin());
}
DigitanksWindow()->GetInstructor()->FinishedTutorial(CInstructor::TUTORIAL_INGAME_ARTILLERY_SELECT, true);
if (m_hEntity->GetUnitType() == UNIT_MOBILECPU)
DigitanksWindow()->GetInstructor()->FinishedTutorial(CInstructor::TUTORIAL_INGAME_STRATEGY_SELECT, true);
}
BaseClass::Selected();
}
CSceneTreeNode::CSceneTreeNode(glgui::CTreeNode* pParent, glgui::CTree* pTree)
: glgui::CTreeNode(pParent, pTree, L"")
{
}
void CSceneTreeNode::Paint(int x, int y, int w, int h, bool bFloating)
{
BaseClass::Paint(x, y, w, h, bFloating);
}
<commit_msg>Reorganize the scene tree.<commit_after>#include "scenetree.h"
#include <game/gameserver.h>
#include <game/digitanks/digitanksgame.h>
#include "digitankswindow.h"
#include "hud.h"
#include <renderer\renderer.h>
#include <game/digitanks/dt_camera.h>
#include "instructor.h"
CSceneTree::CSceneTree()
: CTree(CRenderer::LoadTextureIntoGL(L"textures/hud/arrow.png"), 0, 0)
{
}
void CSceneTree::Layout()
{
SetSize(90, glgui::CRootPanel::Get()->GetHeight()-300);
SetPos(15, 60);
BaseClass::Layout();
}
void CSceneTree::BuildTree(bool bForce)
{
CDigitanksTeam* pCurrentLocalTeam = DigitanksGame()->GetCurrentLocalDigitanksTeam();
if (!pCurrentLocalTeam)
return;
if (m_hTeam == pCurrentLocalTeam && !bForce)
return;
ClearTree();
m_hTeam = pCurrentLocalTeam;
for (size_t i = 0; i < GameServer()->GetMaxEntities(); i++)
{
CSelectable* pEntity = CBaseEntity::GetEntityType<CSelectable>(i);
if (!pEntity)
continue;
if (pEntity->GetDigitanksTeam() != pCurrentLocalTeam)
continue;
unittype_t eUnit = pEntity->GetUnitType();
if (eUnit == STRUCTURE_BUFFER)
continue;
if (eUnit == STRUCTURE_MINIBUFFER)
continue;
if (eUnit == STRUCTURE_BATTERY)
continue;
if (eUnit == STRUCTURE_PSU)
continue;
CSceneTreeGroup* pTreeGroup = GetUnitNode(eUnit);
pTreeGroup->AddNode(new CSceneTreeUnit(pEntity, pTreeGroup, this));
}
Layout();
}
CSceneTreeGroup* CSceneTree::GetUnitNode(unittype_t eUnit)
{
for (size_t i = 0; i < m_apNodes.size(); i++)
{
CSceneTreeGroup* pTreeGroup = dynamic_cast<CSceneTreeGroup*>(m_apNodes[i]);
if (eUnit == pTreeGroup->GetUnitType())
return pTreeGroup;
if (pTreeGroup->GetUnitType() == STRUCTURE_CPU)
{
if (eUnit == STRUCTURE_INFANTRYLOADER)
return pTreeGroup;
if (eUnit == STRUCTURE_TANKLOADER)
return pTreeGroup;
if (eUnit == STRUCTURE_ARTILLERYLOADER)
return pTreeGroup;
}
}
// It's not there. Insert it.
for (size_t i = 0; i < m_apNodes.size(); i++)
{
CSceneTreeGroup* pTreeGroup = dynamic_cast<CSceneTreeGroup*>(m_apNodes[i]);
if (eUnit < pTreeGroup->GetUnitType())
{
CSceneTreeGroup* pReturn = new CSceneTreeGroup(eUnit, this);
AddNode(pReturn, i);
return pReturn;
}
}
CSceneTreeGroup* pReturn = new CSceneTreeGroup(eUnit, this);
AddNode(pReturn);
return pReturn;
}
void CSceneTree::Paint(int x, int y, int w, int h)
{
glgui::CRootPanel::PaintRect(x, y, w, h, m_clrBackground);
if (m_iHilighted != ~0)
{
IControl* pNode = m_apControls[m_iHilighted];
int cx, cy, cw, ch;
pNode->GetAbsDimensions(cx, cy, cw, ch);
glgui::CRootPanel::PaintRect(cx+ch, cy, ch, ch, Color(255, 255, 255, 100));
}
// Skip CTree, we override its hilight and selection methods.
CPanel::Paint(x, y, w, h);
}
void CSceneTree::OnAddEntityToTeam(CDigitanksTeam* pTeam, CBaseEntity* pEntity)
{
CSelectable* pSelectable = dynamic_cast<CSelectable*>(pEntity);
if (!pSelectable)
return;
if (pTeam != m_hTeam)
return;
unittype_t eUnit = pSelectable->GetUnitType();
if (eUnit == STRUCTURE_BUFFER)
return;
if (eUnit == STRUCTURE_MINIBUFFER)
return;
if (eUnit == STRUCTURE_BATTERY)
return;
if (eUnit == STRUCTURE_PSU)
return;
CSceneTreeGroup* pTreeGroup = GetUnitNode(eUnit);
pTreeGroup->AddNode(new CSceneTreeUnit(pSelectable, pTreeGroup, this));
Layout();
}
void CSceneTree::OnRemoveEntityFromTeam(CDigitanksTeam* pTeam, CBaseEntity* pEntity)
{
CSelectable* pSelectable = dynamic_cast<CSelectable*>(pEntity);
if (!pSelectable)
return;
if (pTeam != m_hTeam)
return;
unittype_t eUnit = pSelectable->GetUnitType();
if (eUnit == STRUCTURE_BUFFER)
return;
if (eUnit == STRUCTURE_MINIBUFFER)
return;
if (eUnit == STRUCTURE_BATTERY)
return;
if (eUnit == STRUCTURE_PSU)
return;
CSceneTreeGroup* pTreeGroup = GetUnitNode(eUnit);
for (size_t i = 0; i < pTreeGroup->m_apNodes.size(); i++)
{
CSceneTreeUnit* pUnit = dynamic_cast<CSceneTreeUnit*>(pTreeGroup->m_apNodes[i]);
if (!pUnit)
continue;
if (pUnit->GetEntity() == pSelectable)
{
RemoveNode(pUnit);
pUnit->Destructor();
pUnit->Delete();
if (pTreeGroup->m_apNodes.size() == 0)
{
RemoveNode(pTreeGroup);
pTreeGroup->Destructor();
pTreeGroup->Delete();
}
break;
}
}
Layout();
}
CSceneTreeGroup::CSceneTreeGroup(unittype_t eUnit, glgui::CTree* pTree)
: CSceneTreeNode(NULL, pTree)
{
m_eUnit = eUnit;
}
void CSceneTreeGroup::Paint(int x, int y, int w, int h, bool bFloating)
{
if (!IsVisible())
return;
BaseClass::Paint(x, y, w, h, bFloating);
CDigitanksTeam* pCurrentLocalTeam = DigitanksGame()->GetCurrentLocalDigitanksTeam();
CRenderingContext c(GameServer()->GetRenderer());
c.SetBlend(BLEND_ALPHA);
CHUD::PaintUnitSheet(m_eUnit, x+h, y, h, h, pCurrentLocalTeam?pCurrentLocalTeam->GetColor():Color(255,255,255,255));
}
CSceneTreeUnit::CSceneTreeUnit(CEntityHandle<CSelectable> hEntity, glgui::CTreeNode* pParent, glgui::CTree* pTree)
: CSceneTreeNode(pParent, pTree)
{
m_hEntity = hEntity;
}
void CSceneTreeUnit::Paint(int x, int y, int w, int h, bool bFloating)
{
if (!IsVisible())
return;
BaseClass::Paint(x, y, w, h, bFloating);
if (m_hEntity == NULL)
return;
CRenderingContext c(GameServer()->GetRenderer());
c.SetBlend(BLEND_ALPHA);
Color clrTeam = m_hEntity->GetTeam()?m_hEntity->GetTeam()->GetColor():Color(255,255,255,255);
CDigitank* pTank = dynamic_cast<CDigitank*>(m_hEntity.GetPointer());
if (pTank && !pTank->NeedsOrders())
clrTeam.SetAlpha(100);
CDigitanksTeam* pCurrentLocalTeam = DigitanksGame()->GetCurrentLocalDigitanksTeam();
if (pCurrentLocalTeam && pCurrentLocalTeam->IsSelected(m_hEntity))
{
Color clrSelection(255, 255, 255, 64);
if (pCurrentLocalTeam->IsPrimarySelection(m_hEntity))
clrSelection = Color(255, 255, 255, 128);
glgui::CRootPanel::PaintRect(x+h, y, h, h, clrSelection);
clrSelection = Color(255, 255, 255, 128);
if (pCurrentLocalTeam->IsPrimarySelection(m_hEntity))
clrSelection = Color(255, 255, 255, 255);
glgui::CRootPanel::PaintRect(x+h, y, h, 1, clrSelection);
glgui::CRootPanel::PaintRect(x+h, y, 1, h, clrSelection);
glgui::CRootPanel::PaintRect(x+h+h, y, 1, h, clrSelection);
glgui::CRootPanel::PaintRect(x+h, y+h, h, 1, clrSelection);
}
CHUD::PaintUnitSheet(m_hEntity->GetUnitType(), x+h+2, y+2, h-4, h-4, clrTeam);
glgui::CRootPanel::PaintRect(x+h, y - 3, (int)(h*m_hEntity->GetHealth()/m_hEntity->GetTotalHealth()), 3, Color(100, 255, 100));
if (pTank)
{
float flAttackPower = pTank->GetBaseAttackPower(true);
float flDefensePower = pTank->GetBaseDefensePower(true);
float flMovementPower = pTank->GetUsedMovementEnergy(true);
float flTotalPower = pTank->GetStartingPower();
flAttackPower = flAttackPower/flTotalPower;
flDefensePower = flDefensePower/flTotalPower;
flMovementPower = flMovementPower/pTank->GetMaxMovementEnergy();
glgui::CRootPanel::PaintRect(x+h, y, (int)(h*flAttackPower), 3, Color(255, 0, 0));
glgui::CRootPanel::PaintRect(x+h+(int)(h*flAttackPower), y, (int)(h*flDefensePower), 3, Color(0, 0, 255));
glgui::CRootPanel::PaintRect(x+h, y + 3, (int)(h*flMovementPower), 3, Color(255, 255, 0));
size_t iSize = 22;
CHUD::PaintWeaponSheet(pTank->GetCurrentWeapon(), x+h+h+4, y+4, iSize, iSize, Color(255, 255, 255, 255));
size_t iX = x+h+h+h+4;
if (pTank->IsFortified() || pTank->IsFortifying())
{
glgui::CRootPanel::PaintTexture(CDigitank::GetFortifyIcon(), iX, y+4, iSize, iSize);
iX += h;
}
if (pTank->IsSentried())
{
glgui::CRootPanel::PaintTexture(CDigitank::GetSentryIcon(), iX, y+4, iSize, iSize);
iX += h;
}
}
CStructure* pStructure = dynamic_cast<CStructure*>(m_hEntity.GetPointer());
if (pStructure && (pStructure->IsConstructing() || pStructure->IsUpgrading()))
{
int iTurnsRemaining = 0;
int iTotalTurns = 0;
if (pStructure->IsConstructing())
{
iTurnsRemaining = pStructure->GetTurnsToConstruct();
iTotalTurns = pStructure->GetTurnsRemainingToConstruct();
}
else if (pStructure->IsUpgrading())
{
iTurnsRemaining = pStructure->GetTurnsToUpgrade();
iTotalTurns = pStructure->GetTurnsRemainingToUpgrade();
}
int iTurns = iTotalTurns-iTurnsRemaining;
glgui::CRootPanel::PaintRect(x+h, y+h-1, (int)((float)h*iTurns/iTotalTurns), 3, Color(255, 255, 100));
}
}
void CSceneTreeUnit::Selected()
{
if (m_hEntity != NULL)
{
CDigitanksTeam* pCurrentLocalTeam = DigitanksGame()->GetCurrentLocalDigitanksTeam();
if (DigitanksWindow()->IsShiftDown())
pCurrentLocalTeam->AddToSelection(m_hEntity);
else
{
pCurrentLocalTeam->SetPrimarySelection(m_hEntity);
DigitanksGame()->GetDigitanksCamera()->SetTarget(m_hEntity->GetOrigin());
}
DigitanksWindow()->GetInstructor()->FinishedTutorial(CInstructor::TUTORIAL_INGAME_ARTILLERY_SELECT, true);
if (m_hEntity->GetUnitType() == UNIT_MOBILECPU)
DigitanksWindow()->GetInstructor()->FinishedTutorial(CInstructor::TUTORIAL_INGAME_STRATEGY_SELECT, true);
}
BaseClass::Selected();
}
CSceneTreeNode::CSceneTreeNode(glgui::CTreeNode* pParent, glgui::CTree* pTree)
: glgui::CTreeNode(pParent, pTree, L"")
{
}
void CSceneTreeNode::Paint(int x, int y, int w, int h, bool bFloating)
{
BaseClass::Paint(x, y, w, h, bFloating);
}
<|endoftext|>
|
<commit_before>/*
This file is part of Magnum.
Copyright © 2010, 2011, 2012, 2013 Vladimír Vondruš <mosra@centrum.cz>
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 "AbstractFramebuffer.h"
#include "BufferImage.h"
#include "Context.h"
#include "Extensions.h"
#include "Image.h"
#include "Implementation/FramebufferState.h"
#include "Implementation/State.h"
namespace Magnum {
AbstractFramebuffer::CheckStatusImplementation AbstractFramebuffer::checkStatusImplementation = &AbstractFramebuffer::checkStatusImplementationDefault;
AbstractFramebuffer::ReadImplementation AbstractFramebuffer::readImplementation = &AbstractFramebuffer::readImplementationDefault;
AbstractFramebuffer::DrawBuffersImplementation AbstractFramebuffer::drawBuffersImplementation = &AbstractFramebuffer::drawBuffersImplementationDefault;
AbstractFramebuffer::DrawBufferImplementation AbstractFramebuffer::drawBufferImplementation = &AbstractFramebuffer::drawBufferImplementationDefault;
AbstractFramebuffer::ReadBufferImplementation AbstractFramebuffer::readBufferImplementation = &AbstractFramebuffer::readBufferImplementationDefault;
#ifdef MAGNUM_TARGET_GLES2
FramebufferTarget AbstractFramebuffer::readTarget = FramebufferTarget::ReadDraw;
FramebufferTarget AbstractFramebuffer::drawTarget = FramebufferTarget::ReadDraw;
#endif
void AbstractFramebuffer::bind(FramebufferTarget target) {
bindInternal(target);
setViewportInternal();
}
void AbstractFramebuffer::bindInternal(FramebufferTarget target) {
Implementation::FramebufferState* state = Context::current()->state().framebuffer;
/* If already bound, done, otherwise update tracked state */
if(target == FramebufferTarget::Read) {
if(state->readBinding == _id) return;
state->readBinding = _id;
} else if(target == FramebufferTarget::Draw) {
if(state->drawBinding == _id) return;
state->drawBinding = _id;
} else if(target == FramebufferTarget::ReadDraw) {
if(state->readBinding == _id && state->drawBinding == _id) return;
state->readBinding = state->drawBinding = _id;
} else CORRADE_ASSERT_UNREACHABLE();
glBindFramebuffer(static_cast<GLenum>(target), _id);
}
FramebufferTarget AbstractFramebuffer::bindInternal() {
Implementation::FramebufferState* state = Context::current()->state().framebuffer;
/* Return target to which the framebuffer is already bound */
if(state->readBinding == _id && state->drawBinding == _id)
return FramebufferTarget::ReadDraw;
if(state->readBinding == _id)
return FramebufferTarget::Read;
if(state->drawBinding == _id)
return FramebufferTarget::Draw;
/* Or bind it, if not already */
state->readBinding = _id;
#ifndef MAGNUM_TARGET_GLES2
glBindFramebuffer(GLenum(FramebufferTarget::Read), _id);
return FramebufferTarget::Read;
#else
if(readTarget == FramebufferTarget::ReadDraw) state->drawBinding = _id;
glBindFramebuffer(GLenum(readTarget), _id);
return readTarget;
#endif
}
void AbstractFramebuffer::blit(AbstractFramebuffer& source, AbstractFramebuffer& destination, const Rectanglei& sourceRectangle, const Rectanglei& destinationRectangle, FramebufferBlitMask mask, FramebufferBlitFilter filter) {
source.bindInternal(FramebufferTarget::Read);
destination.bindInternal(FramebufferTarget::Draw);
/** @todo Get some extension wrangler instead to avoid undeclared glBlitFramebuffer() on ES2 */
#ifndef MAGNUM_TARGET_GLES2
glBlitFramebuffer(sourceRectangle.left(), sourceRectangle.bottom(), sourceRectangle.right(), sourceRectangle.top(), destinationRectangle.left(), destinationRectangle.bottom(), destinationRectangle.right(), destinationRectangle.top(), static_cast<GLbitfield>(mask), static_cast<GLenum>(filter));
#else
static_cast<void>(sourceRectangle);
static_cast<void>(destinationRectangle);
static_cast<void>(mask);
static_cast<void>(filter);
#endif
}
AbstractFramebuffer& AbstractFramebuffer::setViewport(const Rectanglei& rectangle) {
_viewport = rectangle;
/* Update the viewport if the framebuffer is currently bound */
if(Context::current()->state().framebuffer->drawBinding == _id)
setViewportInternal();
return *this;
}
void AbstractFramebuffer::setViewportInternal() {
Implementation::FramebufferState* state = Context::current()->state().framebuffer;
CORRADE_INTERNAL_ASSERT(state->drawBinding == _id);
/* Already up-to-date, nothing to do */
if(state->viewport == _viewport)
return;
/* Update the state and viewport */
state->viewport = _viewport;
glViewport(_viewport.left(), _viewport.bottom(), _viewport.width(), _viewport.height());
}
void AbstractFramebuffer::clear(FramebufferClearMask mask) {
#ifndef MAGNUM_TARGET_GLES2
bindInternal(FramebufferTarget::Draw);
#else
bindInternal(drawTarget);
#endif
glClear(static_cast<GLbitfield>(mask));
}
void AbstractFramebuffer::read(const Vector2i& offset, const Vector2i& size, Image2D& image) {
#ifndef MAGNUM_TARGET_GLES2
bindInternal(FramebufferTarget::Read);
#else
bindInternal(readTarget);
#endif
const std::size_t dataSize = image.pixelSize()*size.product();
char* const data = new char[dataSize];
readImplementation(offset, size, image.format(), image.type(), dataSize, data);
image.setData(image.format(), image.type(), size, data);
}
#ifndef MAGNUM_TARGET_GLES2
void AbstractFramebuffer::read(const Vector2i& offset, const Vector2i& size, BufferImage2D& image, Buffer::Usage usage) {
#ifndef MAGNUM_TARGET_GLES2
bindInternal(FramebufferTarget::Read);
#else
bindInternal(readTarget);
#endif
/* If the buffer doesn't have sufficient size, resize it */
/** @todo Explicitly reset also when buffer usage changes */
if(image.size() != size)
image.setData(size, image.format(), image.type(), nullptr, usage);
image.buffer().bind(Buffer::Target::PixelPack);
/** @todo De-duplicate buffer size computation */
readImplementation(offset, size, image.format(), image.type(), image.pixelSize()*size.product(), nullptr);
}
#endif
void AbstractFramebuffer::invalidateImplementation(GLsizei count, GLenum* attachments) {
/** @todo Re-enable when extension wrangler is available for ES2 */
#ifndef MAGNUM_TARGET_GLES2
glInvalidateFramebuffer(GLenum(bindInternal()), count, attachments);
#else
//glDiscardFramebufferEXT(GLenum(bindInternal()), count, attachments);
static_cast<void>(count);
static_cast<void>(attachments);
#endif
}
void AbstractFramebuffer::invalidateImplementation(GLsizei count, GLenum* attachments, const Rectanglei& rectangle) {
/** @todo Re-enable when extension wrangler is available for ES2 */
#ifndef MAGNUM_TARGET_GLES2
glInvalidateSubFramebuffer(GLenum(bindInternal()), count, attachments, rectangle.left(), rectangle.bottom(), rectangle.width(), rectangle.height());
#else
//glDiscardSubFramebufferEXT(GLenum(bindInternal()), count, attachments, rectangle.left(), rectangle.bottom(), rectangle.width(), rectangle.height());
static_cast<void>(count);
static_cast<void>(attachments);
static_cast<void>(rectangle);
#endif
}
void AbstractFramebuffer::initializeContextBasedFunctionality(Context& context) {
#ifndef MAGNUM_TARGET_GLES
if(context.isExtensionSupported<Extensions::GL::EXT::direct_state_access>()) {
Debug() << "AbstractFramebuffer: using" << Extensions::GL::EXT::direct_state_access::string() << "features";
checkStatusImplementation = &AbstractFramebuffer::checkStatusImplementationDSA;
drawBuffersImplementation = &AbstractFramebuffer::drawBuffersImplementationDSA;
drawBufferImplementation = &AbstractFramebuffer::drawBufferImplementationDSA;
readBufferImplementation = &AbstractFramebuffer::readBufferImplementationDSA;
}
#endif
#ifdef MAGNUM_TARGET_GLES2
/* Optimistically set separate binding targets and check if one of the
extensions providing them is available */
readTarget = FramebufferTarget::Read;
drawTarget = FramebufferTarget::Draw;
if(context->isExtensionSupported<Extensions::GL::ANGLE::framebuffer_blit>())
Debug() << "AbstractFramebuffer: using" << Extensions::GL::ANGLE::framebuffer_blit::string() << "features";
else if(context->isExtensionSupported<Extensions::GL::APPLE::framebuffer_multisample>())
Debug() << "AbstractFramebuffer: using" << Extensions::GL::APPLE::framebuffer_multisample::string() << "features";
else if(context->isExtensionSupported<Extensions::GL::NV::framebuffer_blit>())
Debug() << "AbstractFramebuffer: using" << Extensions::GL::NV::framebuffer_blit::string() << "features";
/* NV_framebuffer_multisample requires NV_framebuffer_blit, which has these
enums. However, on my system only NV_framebuffer_multisample is
supported, but NV_framebuffer_blit isn't. I will hold my breath and
assume these enums are available. */
else if(context->isExtensionSupported<Extensions::GL::NV::framebuffer_multisample>())
Debug() << "AbstractFramebuffer: using" << Extensions::GL::NV::framebuffer_multisample::string() << "features";
/* If no such extension is available, reset back to unified target */
else readTarget = drawTarget = FramebufferTarget::ReadDraw;
#endif
#ifndef MAGNUM_TARGET_GLES3
#ifndef MAGNUM_TARGET_GLES
if(context.isExtensionSupported<Extensions::GL::ARB::robustness>())
#else
if(context.isExtensionSupported<Extensions::GL::EXT::robustness>())
#endif
{
#ifndef MAGNUM_TARGET_GLES
Debug() << "AbstractFramebuffer: using" << Extensions::GL::ARB::robustness::string() << "features";
#else
//Debug() << "AbstractFramebuffer: using" << Extensions::GL::EXT::robustness::string() << "features";
#endif
/** @todo Enable when extension wrangler for ES is available */
#ifndef MAGNUM_TARGET_GLES
readImplementation = &AbstractFramebuffer::readImplementationRobustness;
#endif
}
#else
static_cast<void>(context);
#endif
}
GLenum AbstractFramebuffer::checkStatusImplementationDefault(const FramebufferTarget target) {
bindInternal(target);
return glCheckFramebufferStatus(GLenum(target));
}
#ifndef MAGNUM_TARGET_GLES
GLenum AbstractFramebuffer::checkStatusImplementationDSA(const FramebufferTarget target) {
return glCheckNamedFramebufferStatusEXT(_id, GLenum(target));
}
#endif
void AbstractFramebuffer::drawBuffersImplementationDefault(GLsizei count, const GLenum* buffers) {
/** @todo Re-enable when extension wrangler is available for ES2 */
#ifndef MAGNUM_TARGET_GLES2
#ifndef MAGNUM_TARGET_GLES2
bindInternal(FramebufferTarget::Draw);
#else
bindInternal(drawTarget);
#endif
glDrawBuffers(count, buffers);
#else
static_cast<void>(count);
static_cast<void>(buffers);
#endif
}
#ifndef MAGNUM_TARGET_GLES
void AbstractFramebuffer::drawBuffersImplementationDSA(GLsizei count, const GLenum* buffers) {
glFramebufferDrawBuffersEXT(_id, count, buffers);
}
#endif
void AbstractFramebuffer::drawBufferImplementationDefault(GLenum buffer) {
/** @todo Re-enable when extension wrangler is available for ES2 */
#ifndef MAGNUM_TARGET_GLES2
#ifndef MAGNUM_TARGET_GLES2
bindInternal(FramebufferTarget::Draw);
#else
bindInternal(drawTarget);
#endif
#ifndef MAGNUM_TARGET_GLES3
glDrawBuffer(buffer);
#else
glDrawBuffers(1, &buffer);
#endif
#else
static_cast<void>(buffer);
#endif
}
#ifndef MAGNUM_TARGET_GLES
void AbstractFramebuffer::drawBufferImplementationDSA(GLenum buffer) {
glFramebufferDrawBufferEXT(_id, buffer);
}
#endif
void AbstractFramebuffer::readBufferImplementationDefault(GLenum buffer) {
/** @todo Get some extension wrangler instead to avoid undeclared glReadBuffer() on ES2 */
#ifndef MAGNUM_TARGET_GLES2
#ifndef MAGNUM_TARGET_GLES2
bindInternal(FramebufferTarget::Read);
#else
bindInternal(readTarget);
#endif
glReadBuffer(buffer);
#else
static_cast<void>(buffer);
#endif
}
#ifndef MAGNUM_TARGET_GLES
void AbstractFramebuffer::readBufferImplementationDSA(GLenum buffer) {
glFramebufferReadBufferEXT(_id, buffer);
}
#endif
void AbstractFramebuffer::readImplementationDefault(const Vector2i& offset, const Vector2i& size, const ImageFormat format, const ImageType type, const std::size_t, GLvoid* const data) {
glReadPixels(offset.x(), offset.y(), size.x(), size.y(), static_cast<GLenum>(format), static_cast<GLenum>(type), data);
}
#ifndef MAGNUM_TARGET_GLES3
void AbstractFramebuffer::readImplementationRobustness(const Vector2i& offset, const Vector2i& size, const ImageFormat format, const ImageType type, const std::size_t dataSize, GLvoid* const data) {
/** @todo Enable when extension wrangler for ES is available */
#ifndef MAGNUM_TARGET_GLES
glReadnPixelsARB(offset.x(), offset.y(), size.x(), size.y(), static_cast<GLenum>(format), static_cast<GLenum>(type), dataSize, data);
#else
CORRADE_INTERNAL_ASSERT(false);
//glReadnPixelsEXT(offset.x(), offset.y(), size.x(), size.y(), static_cast<GLenum>(format), static_cast<GLenum>(type), data);
static_cast<void>(offset);
static_cast<void>(size);
static_cast<void>(format);
static_cast<void>(type);
static_cast<void>(dataSize);
static_cast<void>(data);
#endif
}
#endif
}
<commit_msg>OpenGL ES build fixes.<commit_after>/*
This file is part of Magnum.
Copyright © 2010, 2011, 2012, 2013 Vladimír Vondruš <mosra@centrum.cz>
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 "AbstractFramebuffer.h"
#include "BufferImage.h"
#include "Context.h"
#include "Extensions.h"
#include "Image.h"
#include "Implementation/FramebufferState.h"
#include "Implementation/State.h"
namespace Magnum {
AbstractFramebuffer::CheckStatusImplementation AbstractFramebuffer::checkStatusImplementation = &AbstractFramebuffer::checkStatusImplementationDefault;
AbstractFramebuffer::ReadImplementation AbstractFramebuffer::readImplementation = &AbstractFramebuffer::readImplementationDefault;
AbstractFramebuffer::DrawBuffersImplementation AbstractFramebuffer::drawBuffersImplementation = &AbstractFramebuffer::drawBuffersImplementationDefault;
AbstractFramebuffer::DrawBufferImplementation AbstractFramebuffer::drawBufferImplementation = &AbstractFramebuffer::drawBufferImplementationDefault;
AbstractFramebuffer::ReadBufferImplementation AbstractFramebuffer::readBufferImplementation = &AbstractFramebuffer::readBufferImplementationDefault;
#ifdef MAGNUM_TARGET_GLES2
FramebufferTarget AbstractFramebuffer::readTarget = FramebufferTarget::ReadDraw;
FramebufferTarget AbstractFramebuffer::drawTarget = FramebufferTarget::ReadDraw;
#endif
void AbstractFramebuffer::bind(FramebufferTarget target) {
bindInternal(target);
setViewportInternal();
}
void AbstractFramebuffer::bindInternal(FramebufferTarget target) {
Implementation::FramebufferState* state = Context::current()->state().framebuffer;
/* If already bound, done, otherwise update tracked state */
if(target == FramebufferTarget::Read) {
if(state->readBinding == _id) return;
state->readBinding = _id;
} else if(target == FramebufferTarget::Draw) {
if(state->drawBinding == _id) return;
state->drawBinding = _id;
} else if(target == FramebufferTarget::ReadDraw) {
if(state->readBinding == _id && state->drawBinding == _id) return;
state->readBinding = state->drawBinding = _id;
} else CORRADE_ASSERT_UNREACHABLE();
glBindFramebuffer(static_cast<GLenum>(target), _id);
}
FramebufferTarget AbstractFramebuffer::bindInternal() {
Implementation::FramebufferState* state = Context::current()->state().framebuffer;
/* Return target to which the framebuffer is already bound */
if(state->readBinding == _id && state->drawBinding == _id)
return FramebufferTarget::ReadDraw;
if(state->readBinding == _id)
return FramebufferTarget::Read;
if(state->drawBinding == _id)
return FramebufferTarget::Draw;
/* Or bind it, if not already */
state->readBinding = _id;
#ifndef MAGNUM_TARGET_GLES2
glBindFramebuffer(GLenum(FramebufferTarget::Read), _id);
return FramebufferTarget::Read;
#else
if(readTarget == FramebufferTarget::ReadDraw) state->drawBinding = _id;
glBindFramebuffer(GLenum(readTarget), _id);
return readTarget;
#endif
}
void AbstractFramebuffer::blit(AbstractFramebuffer& source, AbstractFramebuffer& destination, const Rectanglei& sourceRectangle, const Rectanglei& destinationRectangle, FramebufferBlitMask mask, FramebufferBlitFilter filter) {
source.bindInternal(FramebufferTarget::Read);
destination.bindInternal(FramebufferTarget::Draw);
/** @todo Get some extension wrangler instead to avoid undeclared glBlitFramebuffer() on ES2 */
#ifndef MAGNUM_TARGET_GLES2
glBlitFramebuffer(sourceRectangle.left(), sourceRectangle.bottom(), sourceRectangle.right(), sourceRectangle.top(), destinationRectangle.left(), destinationRectangle.bottom(), destinationRectangle.right(), destinationRectangle.top(), static_cast<GLbitfield>(mask), static_cast<GLenum>(filter));
#else
static_cast<void>(sourceRectangle);
static_cast<void>(destinationRectangle);
static_cast<void>(mask);
static_cast<void>(filter);
#endif
}
AbstractFramebuffer& AbstractFramebuffer::setViewport(const Rectanglei& rectangle) {
_viewport = rectangle;
/* Update the viewport if the framebuffer is currently bound */
if(Context::current()->state().framebuffer->drawBinding == _id)
setViewportInternal();
return *this;
}
void AbstractFramebuffer::setViewportInternal() {
Implementation::FramebufferState* state = Context::current()->state().framebuffer;
CORRADE_INTERNAL_ASSERT(state->drawBinding == _id);
/* Already up-to-date, nothing to do */
if(state->viewport == _viewport)
return;
/* Update the state and viewport */
state->viewport = _viewport;
glViewport(_viewport.left(), _viewport.bottom(), _viewport.width(), _viewport.height());
}
void AbstractFramebuffer::clear(FramebufferClearMask mask) {
#ifndef MAGNUM_TARGET_GLES2
bindInternal(FramebufferTarget::Draw);
#else
bindInternal(drawTarget);
#endif
glClear(static_cast<GLbitfield>(mask));
}
void AbstractFramebuffer::read(const Vector2i& offset, const Vector2i& size, Image2D& image) {
#ifndef MAGNUM_TARGET_GLES2
bindInternal(FramebufferTarget::Read);
#else
bindInternal(readTarget);
#endif
const std::size_t dataSize = image.pixelSize()*size.product();
char* const data = new char[dataSize];
readImplementation(offset, size, image.format(), image.type(), dataSize, data);
image.setData(image.format(), image.type(), size, data);
}
#ifndef MAGNUM_TARGET_GLES2
void AbstractFramebuffer::read(const Vector2i& offset, const Vector2i& size, BufferImage2D& image, Buffer::Usage usage) {
#ifndef MAGNUM_TARGET_GLES2
bindInternal(FramebufferTarget::Read);
#else
bindInternal(readTarget);
#endif
/* If the buffer doesn't have sufficient size, resize it */
/** @todo Explicitly reset also when buffer usage changes */
if(image.size() != size)
image.setData(size, image.format(), image.type(), nullptr, usage);
image.buffer().bind(Buffer::Target::PixelPack);
/** @todo De-duplicate buffer size computation */
readImplementation(offset, size, image.format(), image.type(), image.pixelSize()*size.product(), nullptr);
}
#endif
void AbstractFramebuffer::invalidateImplementation(GLsizei count, GLenum* attachments) {
/** @todo Re-enable when extension wrangler is available for ES2 */
#ifndef MAGNUM_TARGET_GLES2
glInvalidateFramebuffer(GLenum(bindInternal()), count, attachments);
#else
//glDiscardFramebufferEXT(GLenum(bindInternal()), count, attachments);
static_cast<void>(count);
static_cast<void>(attachments);
#endif
}
void AbstractFramebuffer::invalidateImplementation(GLsizei count, GLenum* attachments, const Rectanglei& rectangle) {
/** @todo Re-enable when extension wrangler is available for ES2 */
#ifndef MAGNUM_TARGET_GLES2
glInvalidateSubFramebuffer(GLenum(bindInternal()), count, attachments, rectangle.left(), rectangle.bottom(), rectangle.width(), rectangle.height());
#else
//glDiscardSubFramebufferEXT(GLenum(bindInternal()), count, attachments, rectangle.left(), rectangle.bottom(), rectangle.width(), rectangle.height());
static_cast<void>(count);
static_cast<void>(attachments);
static_cast<void>(rectangle);
#endif
}
void AbstractFramebuffer::initializeContextBasedFunctionality(Context& context) {
#ifndef MAGNUM_TARGET_GLES
if(context.isExtensionSupported<Extensions::GL::EXT::direct_state_access>()) {
Debug() << "AbstractFramebuffer: using" << Extensions::GL::EXT::direct_state_access::string() << "features";
checkStatusImplementation = &AbstractFramebuffer::checkStatusImplementationDSA;
drawBuffersImplementation = &AbstractFramebuffer::drawBuffersImplementationDSA;
drawBufferImplementation = &AbstractFramebuffer::drawBufferImplementationDSA;
readBufferImplementation = &AbstractFramebuffer::readBufferImplementationDSA;
}
#endif
#ifdef MAGNUM_TARGET_GLES2
/* Optimistically set separate binding targets and check if one of the
extensions providing them is available */
readTarget = FramebufferTarget::Read;
drawTarget = FramebufferTarget::Draw;
if(context.isExtensionSupported<Extensions::GL::ANGLE::framebuffer_blit>())
Debug() << "AbstractFramebuffer: using" << Extensions::GL::ANGLE::framebuffer_blit::string() << "features";
else if(context.isExtensionSupported<Extensions::GL::APPLE::framebuffer_multisample>())
Debug() << "AbstractFramebuffer: using" << Extensions::GL::APPLE::framebuffer_multisample::string() << "features";
else if(context.isExtensionSupported<Extensions::GL::NV::framebuffer_blit>())
Debug() << "AbstractFramebuffer: using" << Extensions::GL::NV::framebuffer_blit::string() << "features";
/* NV_framebuffer_multisample requires NV_framebuffer_blit, which has these
enums. However, on my system only NV_framebuffer_multisample is
supported, but NV_framebuffer_blit isn't. I will hold my breath and
assume these enums are available. */
else if(context.isExtensionSupported<Extensions::GL::NV::framebuffer_multisample>())
Debug() << "AbstractFramebuffer: using" << Extensions::GL::NV::framebuffer_multisample::string() << "features";
/* If no such extension is available, reset back to unified target */
else readTarget = drawTarget = FramebufferTarget::ReadDraw;
#endif
#ifndef MAGNUM_TARGET_GLES3
#ifndef MAGNUM_TARGET_GLES
if(context.isExtensionSupported<Extensions::GL::ARB::robustness>())
#else
if(context.isExtensionSupported<Extensions::GL::EXT::robustness>())
#endif
{
#ifndef MAGNUM_TARGET_GLES
Debug() << "AbstractFramebuffer: using" << Extensions::GL::ARB::robustness::string() << "features";
#else
//Debug() << "AbstractFramebuffer: using" << Extensions::GL::EXT::robustness::string() << "features";
#endif
/** @todo Enable when extension wrangler for ES is available */
#ifndef MAGNUM_TARGET_GLES
readImplementation = &AbstractFramebuffer::readImplementationRobustness;
#endif
}
#else
static_cast<void>(context);
#endif
}
GLenum AbstractFramebuffer::checkStatusImplementationDefault(const FramebufferTarget target) {
bindInternal(target);
return glCheckFramebufferStatus(GLenum(target));
}
#ifndef MAGNUM_TARGET_GLES
GLenum AbstractFramebuffer::checkStatusImplementationDSA(const FramebufferTarget target) {
return glCheckNamedFramebufferStatusEXT(_id, GLenum(target));
}
#endif
void AbstractFramebuffer::drawBuffersImplementationDefault(GLsizei count, const GLenum* buffers) {
/** @todo Re-enable when extension wrangler is available for ES2 */
#ifndef MAGNUM_TARGET_GLES2
#ifndef MAGNUM_TARGET_GLES2
bindInternal(FramebufferTarget::Draw);
#else
bindInternal(drawTarget);
#endif
glDrawBuffers(count, buffers);
#else
static_cast<void>(count);
static_cast<void>(buffers);
#endif
}
#ifndef MAGNUM_TARGET_GLES
void AbstractFramebuffer::drawBuffersImplementationDSA(GLsizei count, const GLenum* buffers) {
glFramebufferDrawBuffersEXT(_id, count, buffers);
}
#endif
void AbstractFramebuffer::drawBufferImplementationDefault(GLenum buffer) {
/** @todo Re-enable when extension wrangler is available for ES2 */
#ifndef MAGNUM_TARGET_GLES2
#ifndef MAGNUM_TARGET_GLES2
bindInternal(FramebufferTarget::Draw);
#else
bindInternal(drawTarget);
#endif
#ifndef MAGNUM_TARGET_GLES3
glDrawBuffer(buffer);
#else
glDrawBuffers(1, &buffer);
#endif
#else
static_cast<void>(buffer);
#endif
}
#ifndef MAGNUM_TARGET_GLES
void AbstractFramebuffer::drawBufferImplementationDSA(GLenum buffer) {
glFramebufferDrawBufferEXT(_id, buffer);
}
#endif
void AbstractFramebuffer::readBufferImplementationDefault(GLenum buffer) {
/** @todo Get some extension wrangler instead to avoid undeclared glReadBuffer() on ES2 */
#ifndef MAGNUM_TARGET_GLES2
#ifndef MAGNUM_TARGET_GLES2
bindInternal(FramebufferTarget::Read);
#else
bindInternal(readTarget);
#endif
glReadBuffer(buffer);
#else
static_cast<void>(buffer);
#endif
}
#ifndef MAGNUM_TARGET_GLES
void AbstractFramebuffer::readBufferImplementationDSA(GLenum buffer) {
glFramebufferReadBufferEXT(_id, buffer);
}
#endif
void AbstractFramebuffer::readImplementationDefault(const Vector2i& offset, const Vector2i& size, const ImageFormat format, const ImageType type, const std::size_t, GLvoid* const data) {
glReadPixels(offset.x(), offset.y(), size.x(), size.y(), static_cast<GLenum>(format), static_cast<GLenum>(type), data);
}
#ifndef MAGNUM_TARGET_GLES3
void AbstractFramebuffer::readImplementationRobustness(const Vector2i& offset, const Vector2i& size, const ImageFormat format, const ImageType type, const std::size_t dataSize, GLvoid* const data) {
/** @todo Enable when extension wrangler for ES is available */
#ifndef MAGNUM_TARGET_GLES
glReadnPixelsARB(offset.x(), offset.y(), size.x(), size.y(), static_cast<GLenum>(format), static_cast<GLenum>(type), dataSize, data);
#else
CORRADE_INTERNAL_ASSERT(false);
//glReadnPixelsEXT(offset.x(), offset.y(), size.x(), size.y(), static_cast<GLenum>(format), static_cast<GLenum>(type), data);
static_cast<void>(offset);
static_cast<void>(size);
static_cast<void>(format);
static_cast<void>(type);
static_cast<void>(dataSize);
static_cast<void>(data);
#endif
}
#endif
}
<|endoftext|>
|
<commit_before>#include "acmacs-base/argv.hh"
#include "acmacs-base/guile.hh"
#include "acmacs-chart-2/chart-modify.hh"
#include "acmacs-chart-2/factory-import.hh"
// ----------------------------------------------------------------------
using namespace acmacs::argv;
struct Options : public argv
{
Options(int a_argc, const char* const a_argv[], on_error on_err = on_error::exit) : argv() { parse(a_argc, a_argv, on_err); }
option<str_array> scripts{*this, 's', desc{"run scheme script (multiple switches allowed) before processing files"}};
option<str_array> verbose{*this, 'v', "verbose", desc{"comma separated list (or multiple switches) of log enablers"}};
argument<str> to_eval{*this, arg_name{"<guile-expression>"}, mandatory};
};
static void guile_defines();
int main(int argc, char* const argv[])
{
using namespace std::string_view_literals;
int exit_code = 0;
try {
Options opt(argc, argv);
acmacs::log::enable(opt.verbose);
guile::init(guile_defines, *opt.scripts);
scm_c_eval_string(opt.to_eval->data());
}
catch (std::exception& err) {
AD_ERROR("{}", err);
exit_code = 2;
}
return exit_code;
}
// ----------------------------------------------------------------------
static SCM load_chart(SCM args);
void guile_defines()
{
using namespace guile;
using namespace std::string_view_literals;
define("load-chart"sv, load_chart);
// scm_c_define_gsubr("load-chart", 0, 0, 1, guile::subr(load_chart));
} // guile_defines
// ----------------------------------------------------------------------
SCM load_chart(SCM filename)
{
auto chart = std::make_unique<acmacs::chart::ChartModify>(acmacs::chart::import_from_file(guile::from_scm<std::string>(filename)));
fmt::print("loaded: {}\n", chart->make_name());
return guile::VOID;
} // load_chart
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<commit_msg>guile-test<commit_after>#include "acmacs-base/argv.hh"
#include "acmacs-base/guile.hh"
#include "acmacs-chart-2/chart-modify.hh"
#include "acmacs-chart-2/factory-import.hh"
// ----------------------------------------------------------------------
using namespace acmacs::argv;
struct Options : public argv
{
Options(int a_argc, const char* const a_argv[], on_error on_err = on_error::exit) : argv() { parse(a_argc, a_argv, on_err); }
option<str_array> scripts{*this, 's', desc{"run scheme script (multiple switches allowed) before processing files"}};
option<str_array> verbose{*this, 'v', "verbose", desc{"comma separated list (or multiple switches) of log enablers"}};
argument<str> to_eval{*this, arg_name{"<guile-expression>"}, mandatory};
};
static void guile_defines();
int main(int argc, char* const argv[])
{
using namespace std::string_view_literals;
int exit_code = 0;
try {
Options opt(argc, argv);
acmacs::log::enable(opt.verbose);
guile::init(guile_defines, *opt.scripts);
scm_c_eval_string(opt.to_eval->data());
}
catch (std::exception& err) {
AD_ERROR("{}", err);
exit_code = 2;
}
return exit_code;
}
// ----------------------------------------------------------------------
static SCM load_chart(SCM filename);
static SCM chart_name(SCM chart);
static SCM chart_type;
struct Sample
{
Sample(std::string_view a_name) : name(a_name) { AD_DEBUG("Sample({})", name); }
~Sample() { AD_DEBUG("~Sample[{}]", name); }
std::string name;
static inline void finalize(SCM sample_obj) { delete static_cast<Sample*>(scm_foreign_object_ref(sample_obj, 0)); }
};
void guile_defines()
{
using namespace guile;
using namespace std::string_view_literals;
// scm_c_eval_string("(use-modules (oop goops))");
chart_type = scm_make_foreign_object_type(scm_from_utf8_symbol("<Chart>"), scm_list_1(scm_from_utf8_symbol("data")), Sample::finalize);
define("load-chart"sv, load_chart);
define("chart-name"sv, chart_name);
// scm_c_define_gsubr("load-chart", 0, 0, 1, guile::subr(load_chart));
} // guile_defines
// ----------------------------------------------------------------------
SCM load_chart(SCM filename)
{
// auto chart = new acmacs::chart::ChartModify(acmacs::chart::import_from_file(guile::from_scm<std::string>(filename)));
// fmt::print("loaded: {}\n", chart->make_name());
// return scm_make_foreign_object_1(chart_type, chart);
auto chart = new Sample {guile::from_scm<std::string>(filename)};
return scm_make_foreign_object_1(chart_type, chart);
} // load_chart
// ----------------------------------------------------------------------
SCM chart_name(SCM chart_obj)
{
scm_assert_foreign_object_type(chart_type, chart_obj);
auto* chart = static_cast<Sample*>(scm_foreign_object_ref(chart_obj, 0));
return guile::to_scm(chart->name);
} // chart_name
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<|endoftext|>
|
<commit_before>#pragma once
#include <cmath>
#include <limits>
#include <iostream>
#include "acmacs-base/float.hh"
#include "acmacs-base/to-string.hh"
// ----------------------------------------------------------------------
namespace acmacs::detail
{
template <char Tag> class SizeScale
{
public:
constexpr SizeScale() : mValue(0) {}
constexpr explicit SizeScale(double aValue) : mValue(aValue) {}
constexpr SizeScale(const SizeScale& a) = default;
constexpr bool operator==(SizeScale<Tag> a) const { return float_equal(mValue, a.mValue); }
constexpr bool operator!=(SizeScale<Tag> a) const { return !operator==(a); }
constexpr bool operator<(SizeScale<Tag> a) const { return mValue < a.mValue; }
constexpr SizeScale& operator = (double aValue) { mValue = aValue; return *this; }
constexpr SizeScale& operator = (const SizeScale& a) = default;
constexpr double value() const { return mValue; }
constexpr SizeScale operator / (double a) const { return SizeScale{mValue / a}; }
constexpr SizeScale operator * (double a) const { return SizeScale{mValue * a}; }
constexpr SizeScale& operator *= (double a) { mValue *= a; return *this; }
constexpr SizeScale operator - () const { return SizeScale{- mValue}; }
constexpr SizeScale operator - (SizeScale<Tag> a) const { return SizeScale{mValue - a.mValue}; }
constexpr SizeScale operator + (SizeScale<Tag> a) const { return SizeScale{mValue + a.mValue}; }
constexpr SizeScale& operator += (SizeScale<Tag> a) { mValue += a.mValue; return *this; }
constexpr bool empty() const { return std::isnan(mValue); }
static constexpr SizeScale make_empty() { return SizeScale(std::numeric_limits<double>::quiet_NaN()); }
private:
double mValue;
};
}
using Pixels = acmacs::detail::SizeScale<'P'>; // size in pixels, indepenent from the surface internal coordinate system
using Scaled = acmacs::detail::SizeScale<'S'>; // size in the surface internal coordinate system
// ----------------------------------------------------------------------
using Aspect = acmacs::detail::SizeScale<'A'>;
using Rotation = acmacs::detail::SizeScale<'R'>;
constexpr inline Rotation RotationDegrees(double aAngle)
{
return Rotation{aAngle * M_PI / 180.0};
}
constexpr const Rotation NoRotation{0.0};
constexpr const Rotation RotationReassortant{0.5};
constexpr const Rotation Rotation90DegreesClockwise{RotationDegrees(90)};
constexpr const Rotation Rotation90DegreesAnticlockwise{RotationDegrees(-90)};
constexpr const Aspect AspectNormal{1.0};
constexpr const Aspect AspectEgg{0.75};
// ----------------------------------------------------------------------
inline std::ostream& operator<<(std::ostream& out, Pixels aPixels) { return out << "Pixels{" << aPixels.value() << '}'; }
inline std::ostream& operator<<(std::ostream& out, Scaled aScaled) { return out << "Scaled{" << aScaled.value() << '}'; }
inline std::ostream& operator<<(std::ostream& out, Aspect aAspect) { if (aAspect == AspectNormal) return out << "AspectNormal"; else return out << "Aspect{" << aAspect.value() << '}'; }
inline std::ostream& operator<<(std::ostream& out, Rotation aRotation) { if (aRotation == NoRotation) return out << "NoRotation"; else return out << "Rotation{" << aRotation.value() << '}'; }
namespace acmacs
{
inline std::string to_string(Aspect aAspect) { return aAspect == AspectNormal ? std::string{"1.0"} : to_string(aAspect.value()); }
inline std::string to_string(Rotation aRotation) { return aRotation == NoRotation ? std::string{"0.0"} : to_string(aRotation.value()); }
inline std::string to_string(Pixels aPixels) { return to_string(aPixels.value()); }
inline std::string to_string(Scaled aScaled) { return to_string(aScaled.value()); }
} // namespace acmacs
namespace acmacs::detail
{
using ::operator<<;
} // namespace acmacs::detail
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<commit_msg>SizeScale improvement<commit_after>#pragma once
#include <cmath>
#include <limits>
#include <iostream>
#include "acmacs-base/float.hh"
#include "acmacs-base/to-string.hh"
#include "acmacs-base/fmt.hh"
// ----------------------------------------------------------------------
namespace acmacs::detail
{
template <typename Tag> class SizeScale
{
public:
constexpr explicit SizeScale() : mValue{0} {}
constexpr explicit SizeScale(double aValue) : mValue{aValue} {}
constexpr SizeScale(const SizeScale& a) = default;
constexpr bool operator==(SizeScale<Tag> a) const { return float_equal(mValue, a.mValue); }
constexpr bool operator!=(SizeScale<Tag> a) const { return !operator==(a); }
constexpr bool operator<(SizeScale<Tag> a) const { return mValue < a.mValue; }
constexpr SizeScale& operator = (double aValue) { mValue = aValue; return *this; }
constexpr SizeScale& operator = (const SizeScale& a) = default;
constexpr double value() const { return mValue; }
constexpr SizeScale operator / (double a) const { return SizeScale{mValue / a}; }
constexpr SizeScale operator * (double a) const { return SizeScale{mValue * a}; }
constexpr SizeScale& operator *= (double a) { mValue *= a; return *this; }
constexpr SizeScale operator - () const { return SizeScale{- mValue}; }
constexpr SizeScale operator - (SizeScale<Tag> a) const { return SizeScale{mValue - a.mValue}; }
constexpr SizeScale operator + (SizeScale<Tag> a) const { return SizeScale{mValue + a.mValue}; }
constexpr SizeScale& operator += (SizeScale<Tag> a) { mValue += a.mValue; return *this; }
constexpr bool empty() const { return std::isnan(mValue); }
static constexpr SizeScale make_empty() { return SizeScale(std::numeric_limits<double>::quiet_NaN()); }
private:
double mValue;
};
}
using Pixels = acmacs::detail::SizeScale<struct Pixels_tag>; // size in pixels, indepenent from the surface internal coordinate system
using Scaled = acmacs::detail::SizeScale<struct Scaled_tag>; // size in the surface internal coordinate system
// ----------------------------------------------------------------------
using Aspect = acmacs::detail::SizeScale<struct Aspect_tag>;
using Rotation = acmacs::detail::SizeScale<struct Rotation_tag>;
constexpr inline Rotation RotationDegrees(double aAngle)
{
return Rotation{aAngle * M_PI / 180.0};
}
constexpr const Rotation NoRotation{0.0};
constexpr const Rotation RotationReassortant{0.5};
constexpr const Rotation Rotation90DegreesClockwise{RotationDegrees(90)};
constexpr const Rotation Rotation90DegreesAnticlockwise{RotationDegrees(-90)};
constexpr const Aspect AspectNormal{1.0};
constexpr const Aspect AspectEgg{0.75};
// ----------------------------------------------------------------------
inline std::ostream& operator<<(std::ostream& out, Pixels aPixels) { return out << "Pixels{" << aPixels.value() << '}'; }
inline std::ostream& operator<<(std::ostream& out, Scaled aScaled) { return out << "Scaled{" << aScaled.value() << '}'; }
inline std::ostream& operator<<(std::ostream& out, Aspect aAspect) { if (aAspect == AspectNormal) return out << "AspectNormal"; else return out << "Aspect{" << aAspect.value() << '}'; }
inline std::ostream& operator<<(std::ostream& out, Rotation aRotation) { if (aRotation == NoRotation) return out << "NoRotation"; else return out << "Rotation{" << aRotation.value() << '}'; }
namespace acmacs
{
inline std::string to_string(Aspect aAspect) { return aAspect == AspectNormal ? std::string{"1.0"} : to_string(aAspect.value()); }
inline std::string to_string(Rotation aRotation) { return aRotation == NoRotation ? std::string{"0.0"} : to_string(aRotation.value()); }
inline std::string to_string(Pixels aPixels) { return to_string(aPixels.value()); }
inline std::string to_string(Scaled aScaled) { return to_string(aScaled.value()); }
} // namespace acmacs
namespace acmacs::detail
{
using ::operator<<;
} // namespace acmacs::detail
// ----------------------------------------------------------------------
template <> struct fmt::formatter<Pixels>
{
template <typename ParseContext> constexpr auto parse(ParseContext &ctx) { return ctx.begin(); }
template <typename FormatContext> auto format(const Pixels& pixels, FormatContext& ctx) { return format_to(ctx.out(), "{}px", pixels.value()); }
};
template <> struct fmt::formatter<Scaled>
{
template <typename ParseContext> constexpr auto parse(ParseContext &ctx) { return ctx.begin(); }
template <typename FormatContext> auto format(const Scaled& scaled, FormatContext& ctx) { return format_to(ctx.out(), "{}scaled", scaled.value()); }
};
template <> struct fmt::formatter<Rotation>
{
template <typename ParseContext> constexpr auto parse(ParseContext &ctx) { return ctx.begin(); }
template <typename FormatContext> auto format(const Rotation& rotation, FormatContext& ctx) { return format_to(ctx.out(), "{}", rotation.value()); }
};
template <> struct fmt::formatter<Aspect>
{
template <typename ParseContext> constexpr auto parse(ParseContext &ctx) { return ctx.begin(); }
template <typename FormatContext> auto format(const Aspect& aspect, FormatContext& ctx) { return format_to(ctx.out(), "{}", aspect.value()); }
};
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<|endoftext|>
|
<commit_before>#include <iostream>
#include <cstdlib>
#include "min_max_heap.h"
#include "min_max_heap_test.h"
using namespace std;
void min_max_heap_test()
{
const int num_experiments = 500;
min_max_heap my_min_max_heap(num_experiments);
int data[num_experiments];
for (int i = 0; i < num_experiments; i++)
{
data[i] = -1;
}
for (int i = 0; i < num_experiments; i++)
{
int operation = rand() % 3;
if (my_min_max_heap.get_size() == 0)
{
// the only valid operation is insert a random value if the size is 0
operation = 0;
}
if (operation == 0)
{
int value = rand() % 50;
cout << i << ":\t Insert " << value << endl;
// Naive implementation
for (int i = 0; i < num_experiments; i++)
{
if (data[i] == -1)
{
data[i] = value;
break;
}
}
if (!my_min_max_heap.try_insert(value))
{
cout << "Fail" << endl;
}
}
else if (operation == 1)
{
cout << i << ":\t Delete min" << endl;
int min_value = INT_MAX;
int min_index = -1;
// Naive implementation
for (int j = 0; j < num_experiments; j++)
{
if (data[j] != -1)
{
if (data[j] < min_value)
{
min_value = data[j];
min_index = j;
}
}
}
data[min_index] = -1;
double test_min_value;
if (!my_min_max_heap.try_delete_min(&test_min_value))
{
cout << "Fail" << endl;
}
if (test_min_value != min_value)
{
cout << "Fail" << endl;
}
if (!my_min_max_heap.verify_consistency())
{
cout << "Fail" << endl;
}
}
else if (operation == 2)
{
cout << i << ":\t Delete max" << endl;
int max_value = INT_MIN;
int max_index = -1;
// Naive implementation
for (int j = 0; j < num_experiments; j++)
{
if (data[j] != -1)
{
if (data[j] > max_value)
{
max_value = data[j];
max_index = j;
}
}
}
data[max_index] = -1;
double test_max_value;
if (!my_min_max_heap.try_delete_max(&test_max_value))
{
cout << "Fail" << endl;
}
if (test_max_value != max_value)
{
cout << "Fail" << endl;
}
if (!my_min_max_heap.verify_consistency())
{
cout << "Fail" << endl;
}
}
}
}
<commit_msg>Fix Linux build<commit_after>#include <iostream>
#include <cstdlib>
#include <limits.h>
#include "min_max_heap.h"
#include "min_max_heap_test.h"
using namespace std;
void min_max_heap_test()
{
const int num_experiments = 500;
min_max_heap my_min_max_heap(num_experiments);
int data[num_experiments];
for (int i = 0; i < num_experiments; i++)
{
data[i] = -1;
}
for (int i = 0; i < num_experiments; i++)
{
int operation = rand() % 3;
if (my_min_max_heap.get_size() == 0)
{
// the only valid operation is insert a random value if the size is 0
operation = 0;
}
if (operation == 0)
{
int value = rand() % 50;
cout << i << ":\t Insert " << value << endl;
// Naive implementation
for (int i = 0; i < num_experiments; i++)
{
if (data[i] == -1)
{
data[i] = value;
break;
}
}
if (!my_min_max_heap.try_insert(value))
{
cout << "Fail" << endl;
}
}
else if (operation == 1)
{
cout << i << ":\t Delete min" << endl;
int min_value = INT_MAX;
int min_index = -1;
// Naive implementation
for (int j = 0; j < num_experiments; j++)
{
if (data[j] != -1)
{
if (data[j] < min_value)
{
min_value = data[j];
min_index = j;
}
}
}
data[min_index] = -1;
double test_min_value;
if (!my_min_max_heap.try_delete_min(&test_min_value))
{
cout << "Fail" << endl;
}
if (test_min_value != min_value)
{
cout << "Fail" << endl;
}
if (!my_min_max_heap.verify_consistency())
{
cout << "Fail" << endl;
}
}
else if (operation == 2)
{
cout << i << ":\t Delete max" << endl;
int max_value = INT_MIN;
int max_index = -1;
// Naive implementation
for (int j = 0; j < num_experiments; j++)
{
if (data[j] != -1)
{
if (data[j] > max_value)
{
max_value = data[j];
max_index = j;
}
}
}
data[max_index] = -1;
double test_max_value;
if (!my_min_max_heap.try_delete_max(&test_max_value))
{
cout << "Fail" << endl;
}
if (test_max_value != max_value)
{
cout << "Fail" << endl;
}
if (!my_min_max_heap.verify_consistency())
{
cout << "Fail" << endl;
}
}
}
}
<|endoftext|>
|
<commit_before>#include<iostream>
#include<iomanip>
using namespace std;
struct Trabajadores{
string nombre;
float salario;
}T[20];
int main(){
}
<commit_msg>Agregando<commit_after>#include<iostream>
#include<iomanip>
using namespace std;
/*
Variables
Son 20 Empleados
Leer a Cada uno
Nombre, Horas de Trabajo, Base de Pago, Edad
Otras Variables
Impuestos, Saldo Neto
*/
struct Trabajadores{
string nombre;
float salario;
}T[20];
int main(){
}
<|endoftext|>
|
<commit_before>//---------------------------------------------------------------------------//
/*
Copyright (c) 2012, Stuart R. Slattery
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 University of Wisconsin - Madison 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.
*/
//---------------------------------------------------------------------------//
/*!
* \file Chimera_HistoryBank.hpp
* \author Stuart R. Slattery
* \brief HistoryBank definition.
*/
//---------------------------------------------------------------------------//
#ifndef Chimera_HISTORYBANK_HPP
#define Chimera_HISTORYBANK_HPP
#include "Chimera_Assertion.hpp"
#include <Teuchos_Array.hpp>
namespace Chimera
{
//---------------------------------------------------------------------------//
/*!
* \class HistoryBank
* \brief History bank.
*
* This class is a stack using a Teuchos::Array as the underlying data
* structure so that we may use it for communication operations.
*/
//---------------------------------------------------------------------------//
template<class HT>
class HistoryBank
{
public:
//@{
//! Typedefs.
typedef HT history_type;
typedef typename Teuchos::Array<HT>::size_type size_type;
//@}
//! Default constructor.
HistoryBank()
: d_histories( 0 )
{ /* ... */ }
//! Stack constructor.
HistoryBank( const Teuchos::Array<HT>& histories )
: d_histories( histories )
{ /* ... */ }
//! Destructor.
~HistoryBank()
{ /* ... */ }
//! Set the history stack.
void setStack( const Teuchos::Array<HT>& histories )
{ d_histories = histories; }
//! Return if the bank is empty.
bool empty () const
{ return d_histories.empty(); }
//! Return the number of histories left in the bank.
size_type size() const
{ return d_histories.size(); }
//! Access the top history in the stack.
inline const HT& top() const;
//! Push history onto the stack.
void push( const HT& history )
{ d_histories.push_back(history); }
//! Pop a history off of the stack.
inline HT pop();
private:
// History stack.
Teuchos::Array<HT> d_histories;
};
//---------------------------------------------------------------------------//
// Inline functions.
//---------------------------------------------------------------------------//
template<class HT>
const HT& HistoryBank<HT>::top() const
{
testPrecondition( !empty() );
return d_histories.back();
}
//---------------------------------------------------------------------------//
template<class HT>
HT HistoryBank<HT>::pop()
{
testPrecondition( !empty() );
HT history = d_histories.back();
d_histories.pop_back();
return history;
}
//---------------------------------------------------------------------------//
} // end namespace Chimera
#endif // end Chimera_HISTORYBANK_HPP
//---------------------------------------------------------------------------//
// end Chimera_HistoryBank.hpp
//---------------------------------------------------------------------------//
<commit_msg>added non-const reference access to top of bank stack<commit_after>//---------------------------------------------------------------------------//
/*
Copyright (c) 2012, Stuart R. Slattery
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 University of Wisconsin - Madison 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.
*/
//---------------------------------------------------------------------------//
/*!
* \file Chimera_HistoryBank.hpp
* \author Stuart R. Slattery
* \brief HistoryBank definition.
*/
//---------------------------------------------------------------------------//
#ifndef Chimera_HISTORYBANK_HPP
#define Chimera_HISTORYBANK_HPP
#include "Chimera_Assertion.hpp"
#include <Teuchos_Array.hpp>
namespace Chimera
{
//---------------------------------------------------------------------------//
/*!
* \class HistoryBank
* \brief History bank.
*
* This class is a stack using a Teuchos::Array as the underlying data
* structure so that we may use it for communication operations.
*/
//---------------------------------------------------------------------------//
template<class HT>
class HistoryBank
{
public:
//@{
//! Typedefs.
typedef HT history_type;
typedef typename Teuchos::Array<HT>::size_type size_type;
//@}
//! Default constructor.
HistoryBank()
: d_histories( 0 )
{ /* ... */ }
//! Stack constructor.
HistoryBank( const Teuchos::Array<HT>& histories )
: d_histories( histories )
{ /* ... */ }
//! Destructor.
~HistoryBank()
{ /* ... */ }
//! Set the history stack.
void setStack( const Teuchos::Array<HT>& histories )
{ d_histories = histories; }
//! Return if the bank is empty.
bool empty () const
{ return d_histories.empty(); }
//! Return the number of histories left in the bank.
size_type size() const
{ return d_histories.size(); }
//! Access the top history in the stack.
inline const HT& top() const;
inline HT& top();
//! Push history onto the stack.
void push( const HT& history )
{ d_histories.push_back(history); }
//! Pop a history off of the stack.
inline HT pop();
private:
// History stack.
Teuchos::Array<HT> d_histories;
};
//---------------------------------------------------------------------------//
// Inline functions.
//---------------------------------------------------------------------------//
template<class HT>
const HT& HistoryBank<HT>::top() const
{
testPrecondition( !empty() );
return d_histories.back();
}
template<class HT>
HT& HistoryBank<HT>::top()
{
testPrecondition( !empty() );
return d_histories.back();
}
//---------------------------------------------------------------------------//
template<class HT>
HT HistoryBank<HT>::pop()
{
testPrecondition( !empty() );
HT history = d_histories.back();
d_histories.pop_back();
return history;
}
//---------------------------------------------------------------------------//
} // end namespace Chimera
#endif // end Chimera_HISTORYBANK_HPP
//---------------------------------------------------------------------------//
// end Chimera_HistoryBank.hpp
//---------------------------------------------------------------------------//
<|endoftext|>
|
<commit_before>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: NPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Netscape Public License
* Version 1.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla Communicator client code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the NPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the NPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "npapi.h"
#include "npupp.h"
//\\// DEFINE
#define NP_EXPORT
//\\// GLOBAL DATA
NPNetscapeFuncs* g_pNavigatorFuncs = 0;
extern "C"
{
#ifdef OJI
JRIGlobalRef Private_GetJavaClass(void);
//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\.
////\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//.
// Private_GetJavaClass (global function)
//
// Given a Java class reference (thru NPP_GetJavaClass) inform JRT
// of this class existence
//
JRIGlobalRef
Private_GetJavaClass(void)
{
jref clazz = NPP_GetJavaClass();
if (clazz) {
JRIEnv* env = NPN_GetJavaEnv();
return JRI_NewGlobalRef(env, clazz);
}
return NULL;
}
#endif /* OJI */
//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\.
////\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//.
// PLUGIN DLL entry points
//
// These are the Windows specific DLL entry points. They must be exoprted
//
// we need these to be global since we have to fill one of its field
// with a data (class) which requires knowlwdge of the navigator
// jump-table. This jump table is known at Initialize time (NP_Initialize)
// which is called after NP_GetEntryPoint
static NPPluginFuncs* g_pluginFuncs;
//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\.
////\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//.
// NP_GetEntryPoints
//
// fills in the func table used by Navigator to call entry points in
// plugin DLL. Note that these entry points ensure that DS is loaded
// by using the NP_LOADDS macro, when compiling for Win16
//
NPError WINAPI NP_EXPORT
NP_GetEntryPoints(NPPluginFuncs* pFuncs)
{
// trap a NULL ptr
if(pFuncs == NULL)
return NPERR_INVALID_FUNCTABLE_ERROR;
// if the plugin's function table is smaller than the plugin expects,
// then they are incompatible, and should return an error
pFuncs->version = (NP_VERSION_MAJOR << 8) | NP_VERSION_MINOR;
pFuncs->newp = NPP_New;
pFuncs->destroy = NPP_Destroy;
pFuncs->setwindow = NPP_SetWindow;
pFuncs->newstream = NPP_NewStream;
pFuncs->destroystream = NPP_DestroyStream;
pFuncs->asfile = NPP_StreamAsFile;
pFuncs->writeready = NPP_WriteReady;
pFuncs->write = NPP_Write;
pFuncs->print = NPP_Print;
pFuncs->event = 0; /// reserved
g_pluginFuncs = pFuncs;
return NPERR_NO_ERROR;
}
//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\.
////\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//.
// NP_Initialize
//
// called immediately after the plugin DLL is loaded
//
NPError WINAPI NP_EXPORT
NP_Initialize(NPNetscapeFuncs* pFuncs)
{
// trap a NULL ptr
if(pFuncs == NULL)
return NPERR_INVALID_FUNCTABLE_ERROR;
g_pNavigatorFuncs = pFuncs; // save it for future reference
// if the plugin's major ver level is lower than the Navigator's,
// then they are incompatible, and should return an error
if(HIBYTE(pFuncs->version) > NP_VERSION_MAJOR)
return NPERR_INCOMPATIBLE_VERSION_ERROR;
// We have to defer these assignments until g_pNavigatorFuncs is set
int navMinorVers = g_pNavigatorFuncs->version & 0xFF;
if( navMinorVers >= NPVERS_HAS_NOTIFICATION ) {
g_pluginFuncs->urlnotify = NPP_URLNotify;
}
#ifdef OJI
if( navMinorVers >= NPVERS_HAS_LIVECONNECT ) {
g_pluginFuncs->javaClass = Private_GetJavaClass();
}
#endif
return NPERR_NO_ERROR;
}
//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\.
////\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//.
// NP_Shutdown
//
// called immediately before the plugin DLL is unloaded.
// This functio shuold check for some ref count on the dll to see if it is
// unloadable or it needs to stay in memory.
//
void WINAPI NP_EXPORT
NP_Shutdown()
{
g_pNavigatorFuncs = NULL;
}
char * NP_GetMIMEDescription()
{
return NPP_GetMIMEDescription();
}
// END - PLUGIN DLL entry points
////\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//.
//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\.
/* NAVIGATOR Entry points */
/* These entry points expect to be called from within the plugin. The
noteworthy assumption is that DS has already been set to point to the
plugin's DLL data segment. Don't call these functions from outside
the plugin without ensuring DS is set to the DLLs data segment first,
typically using the NP_LOADDS macro
*/
/* returns the major/minor version numbers of the Plugin API for the plugin
and the Navigator
*/
void NPN_Version(int* plugin_major, int* plugin_minor, int* netscape_major, int* netscape_minor)
{
*plugin_major = NP_VERSION_MAJOR;
*plugin_minor = NP_VERSION_MINOR;
*netscape_major = HIBYTE(g_pNavigatorFuncs->version);
*netscape_minor = LOBYTE(g_pNavigatorFuncs->version);
}
NPError NPN_GetValue(NPP instance, NPNVariable variable, void *result)
{
return g_pNavigatorFuncs->getvalue(instance, variable, result);
}
/* causes the specified URL to be fetched and streamed in
*/
NPError NPN_GetURLNotify(NPP instance, const char *url, const char *target, void* notifyData)
{
int navMinorVers = g_pNavigatorFuncs->version & 0xFF;
NPError err;
if( navMinorVers >= NPVERS_HAS_NOTIFICATION ) {
err = g_pNavigatorFuncs->geturlnotify(instance, url, target, notifyData);
}
else {
err = NPERR_INCOMPATIBLE_VERSION_ERROR;
}
return err;
}
NPError NPN_GetURL(NPP instance, const char *url, const char *target)
{
return g_pNavigatorFuncs->geturl(instance, url, target);
}
NPError NPN_PostURLNotify(NPP instance, const char* url, const char* window, uint32_t len, const char* buf, NPBool file, void* notifyData)
{
int navMinorVers = g_pNavigatorFuncs->version & 0xFF;
NPError err;
if( navMinorVers >= NPVERS_HAS_NOTIFICATION ) {
err = g_pNavigatorFuncs->posturlnotify(instance, url, window, len, buf, file, notifyData);
}
else {
err = NPERR_INCOMPATIBLE_VERSION_ERROR;
}
return err;
}
NPError NPN_PostURL(NPP instance, const char* url, const char* window, uint32_t len, const char* buf, NPBool file)
{
return g_pNavigatorFuncs->posturl(instance, url, window, len, buf, file);
}
/* Requests that a number of bytes be provided on a stream. Typically
this would be used if a stream was in "pull" mode. An optional
position can be provided for streams which are seekable.
*/
NPError NPN_RequestRead(NPStream* stream, NPByteRange* rangeList)
{
return g_pNavigatorFuncs->requestread(stream, rangeList);
}
/* Creates a new stream of data from the plug-in to be interpreted
by Netscape in the current window.
*/
NPError NPN_NewStream(NPP instance, NPMIMEType type,
const char* target, NPStream** stream)
{
int navMinorVersion = g_pNavigatorFuncs->version & 0xFF;
NPError err;
if( navMinorVersion >= NPVERS_HAS_STREAMOUTPUT ) {
err = g_pNavigatorFuncs->newstream(instance, type, target, stream);
}
else {
err = NPERR_INCOMPATIBLE_VERSION_ERROR;
}
return err;
}
/* Provides len bytes of data.
*/
int32_t NPN_Write(NPP instance, NPStream *stream,
int32_t len, void *buffer)
{
int navMinorVersion = g_pNavigatorFuncs->version & 0xFF;
int32_t result;
if( navMinorVersion >= NPVERS_HAS_STREAMOUTPUT ) {
result = g_pNavigatorFuncs->write(instance, stream, len, buffer);
}
else {
result = -1;
}
return result;
}
/* Closes a stream object.
reason indicates why the stream was closed.
*/
NPError NPN_DestroyStream(NPP instance, NPStream* stream, NPError reason)
{
int navMinorVersion = g_pNavigatorFuncs->version & 0xFF;
NPError err;
if( navMinorVersion >= NPVERS_HAS_STREAMOUTPUT ) {
err = g_pNavigatorFuncs->destroystream(instance, stream, reason);
}
else {
err = NPERR_INCOMPATIBLE_VERSION_ERROR;
}
return err;
}
/* Provides a text status message in the Netscape client user interface
*/
void NPN_Status(NPP instance, const char *message)
{
g_pNavigatorFuncs->status(instance, message);
}
/* returns the user agent string of Navigator, which contains version info
*/
const char* NPN_UserAgent(NPP instance)
{
return g_pNavigatorFuncs->uagent(instance);
}
/* allocates memory from the Navigator's memory space. Necessary so that
saved instance data may be freed by Navigator when exiting.
*/
void* NPN_MemAlloc(uint32_t size)
{
return g_pNavigatorFuncs->memalloc(size);
}
/* reciprocal of MemAlloc() above
*/
void NPN_MemFree(void* ptr)
{
g_pNavigatorFuncs->memfree(ptr);
}
#ifdef OJI
/* private function to Netscape. do not use!
*/
void NPN_ReloadPlugins(NPBool reloadPages)
{
g_pNavigatorFuncs->reloadplugins(reloadPages);
}
JRIEnv* NPN_GetJavaEnv(void)
{
return g_pNavigatorFuncs->getJavaEnv();
}
jref NPN_GetJavaPeer(NPP instance)
{
return g_pNavigatorFuncs->getJavaPeer(instance);
}
#endif
} //end of extern "C"
<commit_msg>WaE: add horror cast to calm Windows tinderbox<commit_after>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: NPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Netscape Public License
* Version 1.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla Communicator client code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the NPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the NPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "npapi.h"
#include "npupp.h"
//\\// DEFINE
#define NP_EXPORT
//\\// GLOBAL DATA
NPNetscapeFuncs* g_pNavigatorFuncs = 0;
extern "C"
{
#ifdef OJI
JRIGlobalRef Private_GetJavaClass(void);
//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\.
////\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//.
// Private_GetJavaClass (global function)
//
// Given a Java class reference (thru NPP_GetJavaClass) inform JRT
// of this class existence
//
JRIGlobalRef
Private_GetJavaClass(void)
{
jref clazz = NPP_GetJavaClass();
if (clazz) {
JRIEnv* env = NPN_GetJavaEnv();
return JRI_NewGlobalRef(env, clazz);
}
return NULL;
}
#endif /* OJI */
//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\.
////\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//.
// PLUGIN DLL entry points
//
// These are the Windows specific DLL entry points. They must be exoprted
//
// we need these to be global since we have to fill one of its field
// with a data (class) which requires knowlwdge of the navigator
// jump-table. This jump table is known at Initialize time (NP_Initialize)
// which is called after NP_GetEntryPoint
static NPPluginFuncs* g_pluginFuncs;
//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\.
////\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//.
// NP_GetEntryPoints
//
// fills in the func table used by Navigator to call entry points in
// plugin DLL. Note that these entry points ensure that DS is loaded
// by using the NP_LOADDS macro, when compiling for Win16
//
NPError WINAPI NP_EXPORT
NP_GetEntryPoints(NPPluginFuncs* pFuncs)
{
// trap a NULL ptr
if(pFuncs == NULL)
return NPERR_INVALID_FUNCTABLE_ERROR;
// if the plugin's function table is smaller than the plugin expects,
// then they are incompatible, and should return an error
pFuncs->version = (NP_VERSION_MAJOR << 8) | NP_VERSION_MINOR;
pFuncs->newp = NPP_New;
pFuncs->destroy = NPP_Destroy;
pFuncs->setwindow = NPP_SetWindow;
pFuncs->newstream = NPP_NewStream;
pFuncs->destroystream = NPP_DestroyStream;
pFuncs->asfile = NPP_StreamAsFile;
pFuncs->writeready = NPP_WriteReady;
pFuncs->write = NPP_Write;
pFuncs->print = NPP_Print;
pFuncs->event = 0; /// reserved
g_pluginFuncs = pFuncs;
return NPERR_NO_ERROR;
}
//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\.
////\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//.
// NP_Initialize
//
// called immediately after the plugin DLL is loaded
//
NPError WINAPI NP_EXPORT
NP_Initialize(NPNetscapeFuncs* pFuncs)
{
// trap a NULL ptr
if(pFuncs == NULL)
return NPERR_INVALID_FUNCTABLE_ERROR;
g_pNavigatorFuncs = pFuncs; // save it for future reference
// if the plugin's major ver level is lower than the Navigator's,
// then they are incompatible, and should return an error
if(HIBYTE(pFuncs->version) > NP_VERSION_MAJOR)
return NPERR_INCOMPATIBLE_VERSION_ERROR;
// We have to defer these assignments until g_pNavigatorFuncs is set
int navMinorVers = g_pNavigatorFuncs->version & 0xFF;
if( navMinorVers >= NPVERS_HAS_NOTIFICATION ) {
g_pluginFuncs->urlnotify = NPP_URLNotify;
}
#ifdef OJI
if( navMinorVers >= NPVERS_HAS_LIVECONNECT ) {
g_pluginFuncs->javaClass = Private_GetJavaClass();
}
#endif
return NPERR_NO_ERROR;
}
//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\.
////\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//.
// NP_Shutdown
//
// called immediately before the plugin DLL is unloaded.
// This functio shuold check for some ref count on the dll to see if it is
// unloadable or it needs to stay in memory.
//
void WINAPI NP_EXPORT
NP_Shutdown()
{
g_pNavigatorFuncs = NULL;
}
char * NP_GetMIMEDescription()
{
return (char *)NPP_GetMIMEDescription();
}
// END - PLUGIN DLL entry points
////\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//.
//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\.
/* NAVIGATOR Entry points */
/* These entry points expect to be called from within the plugin. The
noteworthy assumption is that DS has already been set to point to the
plugin's DLL data segment. Don't call these functions from outside
the plugin without ensuring DS is set to the DLLs data segment first,
typically using the NP_LOADDS macro
*/
/* returns the major/minor version numbers of the Plugin API for the plugin
and the Navigator
*/
void NPN_Version(int* plugin_major, int* plugin_minor, int* netscape_major, int* netscape_minor)
{
*plugin_major = NP_VERSION_MAJOR;
*plugin_minor = NP_VERSION_MINOR;
*netscape_major = HIBYTE(g_pNavigatorFuncs->version);
*netscape_minor = LOBYTE(g_pNavigatorFuncs->version);
}
NPError NPN_GetValue(NPP instance, NPNVariable variable, void *result)
{
return g_pNavigatorFuncs->getvalue(instance, variable, result);
}
/* causes the specified URL to be fetched and streamed in
*/
NPError NPN_GetURLNotify(NPP instance, const char *url, const char *target, void* notifyData)
{
int navMinorVers = g_pNavigatorFuncs->version & 0xFF;
NPError err;
if( navMinorVers >= NPVERS_HAS_NOTIFICATION ) {
err = g_pNavigatorFuncs->geturlnotify(instance, url, target, notifyData);
}
else {
err = NPERR_INCOMPATIBLE_VERSION_ERROR;
}
return err;
}
NPError NPN_GetURL(NPP instance, const char *url, const char *target)
{
return g_pNavigatorFuncs->geturl(instance, url, target);
}
NPError NPN_PostURLNotify(NPP instance, const char* url, const char* window, uint32_t len, const char* buf, NPBool file, void* notifyData)
{
int navMinorVers = g_pNavigatorFuncs->version & 0xFF;
NPError err;
if( navMinorVers >= NPVERS_HAS_NOTIFICATION ) {
err = g_pNavigatorFuncs->posturlnotify(instance, url, window, len, buf, file, notifyData);
}
else {
err = NPERR_INCOMPATIBLE_VERSION_ERROR;
}
return err;
}
NPError NPN_PostURL(NPP instance, const char* url, const char* window, uint32_t len, const char* buf, NPBool file)
{
return g_pNavigatorFuncs->posturl(instance, url, window, len, buf, file);
}
/* Requests that a number of bytes be provided on a stream. Typically
this would be used if a stream was in "pull" mode. An optional
position can be provided for streams which are seekable.
*/
NPError NPN_RequestRead(NPStream* stream, NPByteRange* rangeList)
{
return g_pNavigatorFuncs->requestread(stream, rangeList);
}
/* Creates a new stream of data from the plug-in to be interpreted
by Netscape in the current window.
*/
NPError NPN_NewStream(NPP instance, NPMIMEType type,
const char* target, NPStream** stream)
{
int navMinorVersion = g_pNavigatorFuncs->version & 0xFF;
NPError err;
if( navMinorVersion >= NPVERS_HAS_STREAMOUTPUT ) {
err = g_pNavigatorFuncs->newstream(instance, type, target, stream);
}
else {
err = NPERR_INCOMPATIBLE_VERSION_ERROR;
}
return err;
}
/* Provides len bytes of data.
*/
int32_t NPN_Write(NPP instance, NPStream *stream,
int32_t len, void *buffer)
{
int navMinorVersion = g_pNavigatorFuncs->version & 0xFF;
int32_t result;
if( navMinorVersion >= NPVERS_HAS_STREAMOUTPUT ) {
result = g_pNavigatorFuncs->write(instance, stream, len, buffer);
}
else {
result = -1;
}
return result;
}
/* Closes a stream object.
reason indicates why the stream was closed.
*/
NPError NPN_DestroyStream(NPP instance, NPStream* stream, NPError reason)
{
int navMinorVersion = g_pNavigatorFuncs->version & 0xFF;
NPError err;
if( navMinorVersion >= NPVERS_HAS_STREAMOUTPUT ) {
err = g_pNavigatorFuncs->destroystream(instance, stream, reason);
}
else {
err = NPERR_INCOMPATIBLE_VERSION_ERROR;
}
return err;
}
/* Provides a text status message in the Netscape client user interface
*/
void NPN_Status(NPP instance, const char *message)
{
g_pNavigatorFuncs->status(instance, message);
}
/* returns the user agent string of Navigator, which contains version info
*/
const char* NPN_UserAgent(NPP instance)
{
return g_pNavigatorFuncs->uagent(instance);
}
/* allocates memory from the Navigator's memory space. Necessary so that
saved instance data may be freed by Navigator when exiting.
*/
void* NPN_MemAlloc(uint32_t size)
{
return g_pNavigatorFuncs->memalloc(size);
}
/* reciprocal of MemAlloc() above
*/
void NPN_MemFree(void* ptr)
{
g_pNavigatorFuncs->memfree(ptr);
}
#ifdef OJI
/* private function to Netscape. do not use!
*/
void NPN_ReloadPlugins(NPBool reloadPages)
{
g_pNavigatorFuncs->reloadplugins(reloadPages);
}
JRIEnv* NPN_GetJavaEnv(void)
{
return g_pNavigatorFuncs->getJavaEnv();
}
jref NPN_GetJavaPeer(NPP instance)
{
return g_pNavigatorFuncs->getJavaPeer(instance);
}
#endif
} //end of extern "C"
<|endoftext|>
|
<commit_before>
// =-=-=-=-=-=-=-
#include "apiHeaderAll.hpp"
#include "msParam.hpp"
#include "reGlobalsExtern.hpp"
#include "irods_ms_plugin.hpp"
// =-=-=-=-=-=-=-
// STL Includes
#include <string>
#include <iostream>
// =-=-=-=-=-=-=-
// cURL Includes
#include <curl/curl.h>
#include <curl/easy.h>
typedef struct writeData_t {
char path[MAX_NAME_LEN];
int desc;
rsComm_t *rsComm;
} writeData_t;
typedef struct readData_t {
char path[MAX_NAME_LEN];
FILE *fd;
} readData_t;
class irodsCurl {
private:
// iRODS serv, char *destPath er handle
rsComm_t *rsComm;
// cURL handle
CURL *curl;
public:
irodsCurl( rsComm_t *comm ) {
rsComm = comm;
curl = curl_easy_init();
if ( !curl ) {
rodsLog( LOG_ERROR, "irodsCurl: %s", curl_easy_strerror( CURLE_FAILED_INIT ) );
}
}
~irodsCurl() {
if ( curl ) {
curl_easy_cleanup( curl );
}
}
//Gets file name from a path
char *getName (const char *path) {
char tmpPath[strlen(path)]; //FIXME: does tmpPath do anything? why do we have this?
strcpy(tmpPath, path);
char* p;
char* outStr;
outStr = (char*)malloc(strlen(path));
p = strrchr (tmpPath, '/');
snprintf(outStr, strlen(path), "%s", p +1);
return outStr;
}
int get( char *url, char *sourcePath, char *destPath, char *ext) {
CURL *curl;
CURLcode res = CURLE_OK;
writeData_t writeData; // the "file descriptor" for our destination object
openedDataObjInp_t openedTarget; // for closing iRODS object after writing
readData_t readData;
int status;
struct curl_httppost *formpost=NULL;
struct curl_httppost *lastptr=NULL;
curl_global_init(CURL_GLOBAL_ALL);
/* Fill in the file upload field */
curl_formadd(&formpost,
&lastptr,
CURLFORM_COPYNAME, "output_format",
CURLFORM_COPYCONTENTS, ext,
CURLFORM_END);
/* Fill in the filename field */
curl_formadd(&formpost,
&lastptr,
CURLFORM_COPYNAME, "file",
CURLFORM_FILENAME, getName(sourcePath),
CURLFORM_STREAM, &readData,
CURLFORM_CONTENTSLENGTH, 100, //This needs to be the size of the upload
CURLFORM_CONTENTTYPE, "application/octet-stream",
CURLFORM_END);
// Zero fill openedDataObjInp
memset( &openedTarget, 0, sizeof( openedDataObjInp_t ) );
// Set up writeData
snprintf(writeData.path, MAX_NAME_LEN, "%s", destPath);
writeData.desc = 0; // the object is yet to be created
writeData.rsComm = rsComm;
// Set up writeDataInp
snprintf(readData.path, MAX_NAME_LEN, "%s", sourcePath);
readData.fd = 0; // the object is yet to be created
// Set up easy handler
curl = curl_easy_init();
/* what URL that receives this POST */
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_READFUNCTION, &irodsCurl::my_read_obj);
curl_easy_setopt(curl, CURLOPT_READDATA, &readData);
curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &irodsCurl::my_write_obj);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &writeData);
// CURL call
res = curl_easy_perform( curl );
// Some error logging
if ( res != CURLE_OK ) {
rodsLog( LOG_ERROR, "irodsCurl::get: cURL error: %s", curl_easy_strerror( res ) );
}
// close iRODS object
if (writeData.desc) {
openedTarget.l1descInx = writeData.desc;
status = rsDataObjClose(rsComm, &openedTarget);
if (status < 0) {
rodsLog(LOG_ERROR, "irodsCurl::get: rsDataObjClose failed for %s, status = %d",
writeData.path, status);
}
}
/* then cleanup the formpost chain */
curl_formfree(formpost);
return res;
}
static size_t my_read_obj(void *buffer, size_t size, size_t nmemb, void* userp) {
struct readData_t *readData = (struct readData_t *) userp;
if (!readData) {
return -11;
}
if (!readData->fd) {
readData->fd = fopen(readData->path, "r");
}
return fread(buffer, size, nmemb, readData->fd);
}
// Custom callback function for the curl handler, to write to an iRODS object
static size_t my_write_obj(void *buffer, size_t size, size_t nmemb, writeData_t *writeData) {
dataObjInp_t file; // input struct for rsDataObjCreate
openedDataObjInp_t openedFile; // input struct for rsDataObjWrite
bytesBuf_t bytesBuf; // input buffer for rsDataObjWrite
size_t written; // return value
int desc;
// Make sure we have something to write to
if (!writeData) {
rodsLog( LOG_ERROR, "my_write_obj: writeData is NULL, status = %d", SYS_INTERNAL_NULL_INPUT_ERR );
return SYS_INTERNAL_NULL_INPUT_ERR;
}
// Zero fill input structs
memset( &file, 0, sizeof( dataObjInp_t ) );
memset( &openedFile, 0, sizeof( openedDataObjInp_t ) );
// If this is the first call we need to create our data object before writing to it
if (!writeData->desc) {
strncpy(file.objPath, writeData->path, MAX_NAME_LEN);
// Overwrite existing file (for this tutorial only, in case the example has been run before)
addKeyVal(&file.condInput, FORCE_FLAG_KW, "");
writeData->desc = rsDataObjCreate(writeData->rsComm, &file);
// No create?
if ( writeData->desc <= 2 ) {
rodsLog( LOG_ERROR, "my_write_obj: rsDataObjCreate failed for %s, status = %d", file.objPath, writeData->desc);
return (writeData->desc);
}
}
// Set up input buffer for rsDataObjWrite
bytesBuf.len = (int)(size * nmemb);
bytesBuf.buf = buffer;
// Set up input struct for rsDataObjWrite
openedFile.l1descInx = writeData->desc;
openedFile.len = bytesBuf.len;
// Write to data object
written = rsDataObjWrite(writeData->rsComm, &openedFile, &bytesBuf);
return (written);
}
}; // class irodsCurl
extern "C" {
int irods_curl_get( msParam_t* url, msParam_t* source_obj, msParam_t* ext_obj,
msParam_t* dest_obj, ruleExecInfo_t* rei ) {
dataObjInp_t destObjInp, *myDestObjInp; /* for parsing input object */
// Sanity checks
if ( !rei || !rei->rsComm ) {
rodsLog( LOG_ERROR, "irods_curl_get: Input rei or rsComm is NULL." );
return ( SYS_INTERNAL_NULL_INPUT_ERR );
}
// get destination path from sourcePath and exten.
char *sourceStr = parseMspForStr(source_obj);
char *extStr = parseMspForStr(ext_obj);
char *source = "/tempZone/home/public/new.png";
char tmpSource[strlen(source) + 10];
strcpy(tmpSource, source);
char *lastdot = strrchr (tmpSource, '.');
char *lastsep = ('/' == 0) ? NULL : strrchr (tmpSource, '/');
if (lastdot != NULL)
{
// and it's before the extenstion separator.
if (lastsep != NULL)
{
if (lastsep < lastdot)
{
// then remove it.
*lastdot = '\0';
}
}
else
{
// Has extension separator with no path separator.
*lastdot = '\0';
}
}
char destStr[strlen(source)+10];
snprintf(destStr, strlen(source) + 10, "%s%s%s", tmpSource, ".", extStr);
fillStrInMsParam(dest_obj, destStr);
// Get path of destination object
rei->status = parseMspForDataObjInp( dest_obj, &destObjInp, &myDestObjInp, 0 );
if ( rei->status < 0 ) {
rodsLog( LOG_ERROR, "irods_curl_get: Input object error. status = %d", rei->status );
return ( rei->status );
}
// Create irodsCurl instance
irodsCurl myCurl( rei->rsComm );
// Call irodsCurl::get
rei->status = myCurl.get( parseMspForStr( url ), sourceStr, destObjInp.objPath, extStr);
// Done
return rei->status;
}
// =-=-=-=-=-=-=-
// 2. Create the plugin factory function which will return a microservice
// table entry
irods::ms_table_entry* plugin_factory() {
// =-=-=-=-=-=-=-
// 3. allocate a microservice plugin which takes the number of function
// params as a parameter to the constructor
irods::ms_table_entry* msvc = new irods::ms_table_entry( 4 );
// =-=-=-=-=-=-=-
// 4. add the microservice function as an operation to the plugin
// the first param is the name / key of the operation, the second
// is the name of the function which will be the microservice
msvc->add_operation( "irods_curl_get", "irods_curl_get" );
// =-=-=-=-=-=-=-
// 5. return the newly created microservice plugin
return msvc;
}
} // extern "C"
<commit_msg>Added FIXME message<commit_after>
// =-=-=-=-=-=-=-
#include "apiHeaderAll.hpp"
#include "msParam.hpp"
#include "reGlobalsExtern.hpp"
#include "irods_ms_plugin.hpp"
// =-=-=-=-=-=-=-
// STL Includes
#include <string>
#include <iostream>
// =-=-=-=-=-=-=-
// cURL Includes
#include <curl/curl.h>
#include <curl/easy.h>
typedef struct writeData_t {
char path[MAX_NAME_LEN];
int desc;
rsComm_t *rsComm;
} writeData_t;
typedef struct readData_t {
char path[MAX_NAME_LEN];
FILE *fd;
} readData_t;
class irodsCurl {
private:
// iRODS serv, char *destPath er handle
rsComm_t *rsComm;
// cURL handle
CURL *curl;
public:
irodsCurl( rsComm_t *comm ) {
rsComm = comm;
curl = curl_easy_init();
if ( !curl ) {
rodsLog( LOG_ERROR, "irodsCurl: %s", curl_easy_strerror( CURLE_FAILED_INIT ) );
}
}
~irodsCurl() {
if ( curl ) {
curl_easy_cleanup( curl );
}
}
//Gets file name from a path
char *getName (const char *path) {
char tmpPath[strlen(path)]; //FIXME: does tmpPath do anything? why do we have this?
strcpy(tmpPath, path);
char* p;
char* outStr;
outStr = (char*)malloc(strlen(path)); //FIXME: should this malloc one extra byte for the null terminator?
p = strrchr (tmpPath, '/');
snprintf(outStr, strlen(path), "%s", p +1);
return outStr;
}
int get( char *url, char *sourcePath, char *destPath, char *ext) {
CURL *curl;
CURLcode res = CURLE_OK;
writeData_t writeData; // the "file descriptor" for our destination object
openedDataObjInp_t openedTarget; // for closing iRODS object after writing
readData_t readData;
int status;
struct curl_httppost *formpost=NULL;
struct curl_httppost *lastptr=NULL;
curl_global_init(CURL_GLOBAL_ALL);
/* Fill in the file upload field */
curl_formadd(&formpost,
&lastptr,
CURLFORM_COPYNAME, "output_format",
CURLFORM_COPYCONTENTS, ext,
CURLFORM_END);
/* Fill in the filename field */
curl_formadd(&formpost,
&lastptr,
CURLFORM_COPYNAME, "file",
CURLFORM_FILENAME, getName(sourcePath),
CURLFORM_STREAM, &readData,
CURLFORM_CONTENTSLENGTH, 100, //This needs to be the size of the upload
CURLFORM_CONTENTTYPE, "application/octet-stream",
CURLFORM_END);
// Zero fill openedDataObjInp
memset( &openedTarget, 0, sizeof( openedDataObjInp_t ) );
// Set up writeData
snprintf(writeData.path, MAX_NAME_LEN, "%s", destPath);
writeData.desc = 0; // the object is yet to be created
writeData.rsComm = rsComm;
// Set up writeDataInp
snprintf(readData.path, MAX_NAME_LEN, "%s", sourcePath);
readData.fd = 0; // the object is yet to be created
// Set up easy handler
curl = curl_easy_init();
/* what URL that receives this POST */
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_READFUNCTION, &irodsCurl::my_read_obj);
curl_easy_setopt(curl, CURLOPT_READDATA, &readData);
curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &irodsCurl::my_write_obj);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &writeData);
// CURL call
res = curl_easy_perform( curl );
// Some error logging
if ( res != CURLE_OK ) {
rodsLog( LOG_ERROR, "irodsCurl::get: cURL error: %s", curl_easy_strerror( res ) );
}
// close iRODS object
if (writeData.desc) {
openedTarget.l1descInx = writeData.desc;
status = rsDataObjClose(rsComm, &openedTarget);
if (status < 0) {
rodsLog(LOG_ERROR, "irodsCurl::get: rsDataObjClose failed for %s, status = %d",
writeData.path, status);
}
}
/* then cleanup the formpost chain */
curl_formfree(formpost);
return res;
}
static size_t my_read_obj(void *buffer, size_t size, size_t nmemb, void* userp) {
struct readData_t *readData = (struct readData_t *) userp;
if (!readData) {
return -11;
}
if (!readData->fd) {
readData->fd = fopen(readData->path, "r");
}
return fread(buffer, size, nmemb, readData->fd);
}
// Custom callback function for the curl handler, to write to an iRODS object
static size_t my_write_obj(void *buffer, size_t size, size_t nmemb, writeData_t *writeData) {
dataObjInp_t file; // input struct for rsDataObjCreate
openedDataObjInp_t openedFile; // input struct for rsDataObjWrite
bytesBuf_t bytesBuf; // input buffer for rsDataObjWrite
size_t written; // return value
int desc;
// Make sure we have something to write to
if (!writeData) {
rodsLog( LOG_ERROR, "my_write_obj: writeData is NULL, status = %d", SYS_INTERNAL_NULL_INPUT_ERR );
return SYS_INTERNAL_NULL_INPUT_ERR;
}
// Zero fill input structs
memset( &file, 0, sizeof( dataObjInp_t ) );
memset( &openedFile, 0, sizeof( openedDataObjInp_t ) );
// If this is the first call we need to create our data object before writing to it
if (!writeData->desc) {
strncpy(file.objPath, writeData->path, MAX_NAME_LEN);
// Overwrite existing file (for this tutorial only, in case the example has been run before)
addKeyVal(&file.condInput, FORCE_FLAG_KW, "");
writeData->desc = rsDataObjCreate(writeData->rsComm, &file);
// No create?
if ( writeData->desc <= 2 ) {
rodsLog( LOG_ERROR, "my_write_obj: rsDataObjCreate failed for %s, status = %d", file.objPath, writeData->desc);
return (writeData->desc);
}
}
// Set up input buffer for rsDataObjWrite
bytesBuf.len = (int)(size * nmemb);
bytesBuf.buf = buffer;
// Set up input struct for rsDataObjWrite
openedFile.l1descInx = writeData->desc;
openedFile.len = bytesBuf.len;
// Write to data object
written = rsDataObjWrite(writeData->rsComm, &openedFile, &bytesBuf);
return (written);
}
}; // class irodsCurl
extern "C" {
int irods_curl_get( msParam_t* url, msParam_t* source_obj, msParam_t* ext_obj,
msParam_t* dest_obj, ruleExecInfo_t* rei ) {
dataObjInp_t destObjInp, *myDestObjInp; /* for parsing input object */
// Sanity checks
if ( !rei || !rei->rsComm ) {
rodsLog( LOG_ERROR, "irods_curl_get: Input rei or rsComm is NULL." );
return ( SYS_INTERNAL_NULL_INPUT_ERR );
}
// get destination path from sourcePath and exten.
char *sourceStr = parseMspForStr(source_obj);
char *extStr = parseMspForStr(ext_obj);
char *source = "/tempZone/home/public/new.png";
char tmpSource[strlen(source) + 10];
strcpy(tmpSource, source);
char *lastdot = strrchr (tmpSource, '.');
char *lastsep = ('/' == 0) ? NULL : strrchr (tmpSource, '/');
if (lastdot != NULL)
{
// and it's before the extenstion separator.
if (lastsep != NULL)
{
if (lastsep < lastdot)
{
// then remove it.
*lastdot = '\0';
}
}
else
{
// Has extension separator with no path separator.
*lastdot = '\0';
}
}
char destStr[strlen(source)+10];
snprintf(destStr, strlen(source) + 10, "%s%s%s", tmpSource, ".", extStr);
fillStrInMsParam(dest_obj, destStr);
// Get path of destination object
rei->status = parseMspForDataObjInp( dest_obj, &destObjInp, &myDestObjInp, 0 );
if ( rei->status < 0 ) {
rodsLog( LOG_ERROR, "irods_curl_get: Input object error. status = %d", rei->status );
return ( rei->status );
}
// Create irodsCurl instance
irodsCurl myCurl( rei->rsComm );
// Call irodsCurl::get
rei->status = myCurl.get( parseMspForStr( url ), sourceStr, destObjInp.objPath, extStr);
// Done
return rei->status;
}
// =-=-=-=-=-=-=-
// 2. Create the plugin factory function which will return a microservice
// table entry
irods::ms_table_entry* plugin_factory() {
// =-=-=-=-=-=-=-
// 3. allocate a microservice plugin which takes the number of function
// params as a parameter to the constructor
irods::ms_table_entry* msvc = new irods::ms_table_entry( 4 );
// =-=-=-=-=-=-=-
// 4. add the microservice function as an operation to the plugin
// the first param is the name / key of the operation, the second
// is the name of the function which will be the microservice
msvc->add_operation( "irods_curl_get", "irods_curl_get" );
// =-=-=-=-=-=-=-
// 5. return the newly created microservice plugin
return msvc;
}
} // extern "C"
<|endoftext|>
|
<commit_before><commit_msg>CloseSuperfluousFiles shouldn't close the directory it's reading from<commit_after><|endoftext|>
|
<commit_before>#include <iostream>
#include "game.hpp"
#include <SDL2/SDL.h>
#include <thread>
#include <chrono>
#include <atomic>
#ifdef _OPENMP
#include <omp.h>
#endif
// TODO: reorder header includes (std first)
// TODO: fix formatting
using namespace std::chrono;
milliseconds last_frame_time;
Scal last_frame_game_time;
milliseconds last_report_time;
std::atomic<Scal> next_game_time_target;
std::unique_ptr<game> G;
GLdouble width, height; /* window width and height */
std::atomic<bool> flag_display;
std::atomic<bool> quit;
std::atomic<bool> pause;
using std::cout;
using std::endl;
int frame_number;
void init()
{
width = 800.0; /* initial window width and height, */
height = 800.0; /* within which we draw. */
last_frame_game_time = 0.;
pause = false;
}
/* Callback functions for GLUT */
/* Draw the window - this is where all the GL actions are */
void display(void)
{
if(flag_display) return;
flag_display=true;
const Scal fps=30.0;
milliseconds current_time = duration_cast<milliseconds>(high_resolution_clock::now().time_since_epoch());
milliseconds time_past_from_last_frame = current_time-last_frame_time;
//if(time_past_from_last_frame<milliseconds(100)) return;
milliseconds frame_duration(int(1000.0/fps));
milliseconds time_residual=frame_duration-time_past_from_last_frame;
//cout<<"sleep for "<<time_residual.count()<<endl;
//std::this_thread::sleep_for(time_residual);
//std::this_thread::sleep_for(frame_duration);
auto new_frame_time = duration_cast<milliseconds>(high_resolution_clock::now().time_since_epoch());
auto new_frame_game_time = G->PS->GetTime();
const Scal frame_real_duration_s =
(new_frame_time - last_frame_time).count() / 1000.;
if ((new_frame_time - last_report_time).count() > 1000.) {
std::cout
<< "fps: " << 1. / frame_real_duration_s
<< ", game rate="
<< (new_frame_game_time -
last_frame_game_time) / frame_real_duration_s
<< ", particles="
<< G->PS->GetNumParticles()
//<< ", max_per_cell="
//<< G->PS->GetNumPerCell()
<< ", t="
<< G->PS->GetTime()
<< ", steps="
<< G->PS->GetNumSteps()
<< std::endl;
last_report_time = new_frame_time;
//G->PS->Blocks.print_status();
}
const Scal game_rate_target = 10.;
//const Scal game_rate_target = 1.;
if (!pause) {
next_game_time_target = new_frame_game_time + game_rate_target / fps;
}
last_frame_time = new_frame_time;
last_frame_game_time = new_frame_game_time;
//cout<<"Frame "<<frame_number++<<endl;
/* clear the screen to white */
glClear(GL_COLOR_BUFFER_BIT);
{
std::lock_guard<std::mutex> lg(G->PS->m_buffer_);
G->R->DrawAll();
G->PS->SetRendererReadyForNext(true);
}
glFlush();
//glutSwapBuffers();
flag_display=false;
}
void cycle()
{
//omp_set_dynamic(0);
//omp_set_nested(0);
//omp_set_num_threads(std::thread::hardware_concurrency());
#ifdef _OPENMP
omp_set_num_threads(2);
#endif
#pragma omp parallel
{
#pragma omp master
std::cout
<< "Computation started, "
#ifdef _OPENMP
<< "OpenMP with " << omp_get_num_threads() << " threads"
#else
<< "single-threaded"
#endif
<< std::endl;
}
while (!quit) {
G->PS->step(next_game_time_target, pause);
std::this_thread::sleep_for(milliseconds(50));
if (pause) {
std::this_thread::sleep_for(milliseconds(100));
}
}
std::cout << "Computation finished" << std::endl;
}
// TODO: detect motionless regions
vect GetDomainMousePosition(int x, int y) {
vect c;
vect A(-1.,-1.), B(-1 + 2. * width / 800, -1. + 2. * height / 800);
c.x = A.x + (B.x - A.x) * (x / width);
c.y = B.y + (A.y - B.y) * (y / height);
return c;
}
vect GetDomainMousePosition() {
int x, y;
SDL_GetMouseState(&x, &y);
return GetDomainMousePosition(x, y);
}
int main() {
if (SDL_Init(SDL_INIT_VIDEO) != 0) {
SDL_Log("Unable to initialize SDL: %s\n", SDL_GetError());
return 1;
}
init();
SDL_Window* window = SDL_CreateWindow(
"ptoy",
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
width,
height,
SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE
);
if (window == NULL) {
SDL_Log("Unable to create window: %s\n", SDL_GetError());
return 1;
}
SDL_GLContext glcontext = SDL_GL_CreateContext(window);
auto gray = 0.5;
glClearColor(gray, gray, gray, 0.0);
glClear(GL_COLOR_BUFFER_BIT);
SDL_GL_SwapWindow(window);
G = std::unique_ptr<game>(new game(width, height));
std::thread computation_thread(cycle);
G->PS->SetForce(vect(0., 0.), false);
//Main loop flag
quit = false;
//Event handler
SDL_Event e;
enum class MouseState {None, Force, Bonds, Pick, Freeze, Portal};
MouseState mouse_state = MouseState::Force;
//While application is running
while (!quit) {
while (SDL_PollEvent( &e ) != 0) {
if (e.type == SDL_QUIT) {
quit = true;
} else if (e.type == SDL_KEYDOWN) {
switch( e.key.keysym.sym ) {
case 'q':
quit = true;
break;
case 'n':
mouse_state = MouseState::None;
std::cout << "Mouse switched to None mode" << std::endl;
break;
case 'r':
mouse_state = MouseState::Force;
std::cout << "Mouse switched to Repulsive mode" << std::endl;
G->PS->SetForceAttractive(false);
break;
case 'f':
mouse_state = MouseState::Freeze;
std::cout << "Mouse switched to Freeze mode" << std::endl;
break;
case 'p':
mouse_state = MouseState::Pick;
std::cout << "Mouse switched to Pick mode" << std::endl;
break;
case 'a':
mouse_state = MouseState::Force;
std::cout << "Mouse switched to Attractive mode" << std::endl;
G->PS->SetForceAttractive(true);
break;
case 'b':
mouse_state = MouseState::Bonds;
std::cout << "Mouse switched to Bonds mode" << std::endl;
break;
case 'o':
mouse_state = MouseState::Portal;
std::cout << "Mouse switched to Portal mode" << std::endl;
break;
case 'i':
std::cout << "Remove last portal" << std::endl;
G->PS->RemoveLastPortal();
break;
case 'g':
G->PS->InvertGravity();
std::cout
<< (G->PS->GetGravity() ? "Gravity on" : "Gravity off")
<< std::endl;
break;
case ' ':
pause = !pause;
break;
}
} else if (e.type == SDL_MOUSEMOTION) {
switch (mouse_state) {
case MouseState::Force:
G->PS->SetForce(GetDomainMousePosition());
break;
case MouseState::Bonds:
G->PS->BondsMove(GetDomainMousePosition());
break;
case MouseState::Pick:
G->PS->PickMove(GetDomainMousePosition());
break;
case MouseState::Freeze:
G->PS->FreezeMove(GetDomainMousePosition());
break;
case MouseState::Portal:
G->PS->PortalMove(GetDomainMousePosition());
break;
case MouseState::None:
break;
}
} else if (e.type == SDL_MOUSEBUTTONDOWN) {
switch (mouse_state) {
case MouseState::Force:
G->PS->SetForce(GetDomainMousePosition(), true);
break;
case MouseState::Bonds:
G->PS->BondsStart(GetDomainMousePosition());
break;
case MouseState::Pick:
G->PS->PickStart(GetDomainMousePosition());
break;
case MouseState::Freeze:
G->PS->FreezeStart(GetDomainMousePosition());
break;
case MouseState::Portal:
G->PS->PortalStart(GetDomainMousePosition());
break;
case MouseState::None:
break;
}
} else if (e.type == SDL_MOUSEBUTTONUP) {
switch (mouse_state) {
case MouseState::Force:
G->PS->SetForce(false);
break;
case MouseState::Bonds:
G->PS->BondsStop(GetDomainMousePosition());
break;
case MouseState::Pick:
G->PS->PickStop(GetDomainMousePosition());
break;
case MouseState::Freeze:
G->PS->FreezeStop(GetDomainMousePosition());
break;
case MouseState::Portal:
G->PS->PortalStop(GetDomainMousePosition());
break;
case MouseState::None:
break;
}
} else if (e.type == SDL_WINDOWEVENT) {
switch (e.window.event) {
case SDL_WINDOWEVENT_RESIZED:
width = e.window.data1;
height = e.window.data2;
glViewport(0, 0, width, height);
G->SetWindowSize(width, height);
break;
}
}
}
display();
SDL_GL_SwapWindow(window);
SDL_Delay(30);
}
// Finalize
SDL_GL_DeleteContext(glcontext);
SDL_DestroyWindow(window);
SDL_Quit();
computation_thread.join();
return 0;
}
<commit_msg>Add quit counter: key q to press 3 times<commit_after>#include <iostream>
#include "game.hpp"
#include <SDL2/SDL.h>
#include <thread>
#include <chrono>
#include <atomic>
#ifdef _OPENMP
#include <omp.h>
#endif
// TODO: reorder header includes (std first)
// TODO: fix formatting
using namespace std::chrono;
milliseconds last_frame_time;
Scal last_frame_game_time;
milliseconds last_report_time;
std::atomic<Scal> next_game_time_target;
std::unique_ptr<game> G;
GLdouble width, height; /* window width and height */
std::atomic<bool> flag_display;
std::atomic<bool> quit;
std::atomic<bool> pause;
using std::cout;
using std::endl;
int frame_number;
void init()
{
width = 800.0; /* initial window width and height, */
height = 800.0; /* within which we draw. */
last_frame_game_time = 0.;
pause = false;
}
/* Callback functions for GLUT */
/* Draw the window - this is where all the GL actions are */
void display(void)
{
if(flag_display) return;
flag_display=true;
const Scal fps=30.0;
milliseconds current_time = duration_cast<milliseconds>(high_resolution_clock::now().time_since_epoch());
milliseconds time_past_from_last_frame = current_time-last_frame_time;
//if(time_past_from_last_frame<milliseconds(100)) return;
milliseconds frame_duration(int(1000.0/fps));
milliseconds time_residual=frame_duration-time_past_from_last_frame;
//cout<<"sleep for "<<time_residual.count()<<endl;
//std::this_thread::sleep_for(time_residual);
//std::this_thread::sleep_for(frame_duration);
auto new_frame_time = duration_cast<milliseconds>(high_resolution_clock::now().time_since_epoch());
auto new_frame_game_time = G->PS->GetTime();
const Scal frame_real_duration_s =
(new_frame_time - last_frame_time).count() / 1000.;
if ((new_frame_time - last_report_time).count() > 1000.) {
std::cout
<< "fps: " << 1. / frame_real_duration_s
<< ", game rate="
<< (new_frame_game_time -
last_frame_game_time) / frame_real_duration_s
<< ", particles="
<< G->PS->GetNumParticles()
//<< ", max_per_cell="
//<< G->PS->GetNumPerCell()
<< ", t="
<< G->PS->GetTime()
<< ", steps="
<< G->PS->GetNumSteps()
<< std::endl;
last_report_time = new_frame_time;
//G->PS->Blocks.print_status();
}
const Scal game_rate_target = 10.;
//const Scal game_rate_target = 1.;
if (!pause) {
next_game_time_target = new_frame_game_time + game_rate_target / fps;
}
last_frame_time = new_frame_time;
last_frame_game_time = new_frame_game_time;
//cout<<"Frame "<<frame_number++<<endl;
/* clear the screen to white */
glClear(GL_COLOR_BUFFER_BIT);
{
std::lock_guard<std::mutex> lg(G->PS->m_buffer_);
G->R->DrawAll();
G->PS->SetRendererReadyForNext(true);
}
glFlush();
//glutSwapBuffers();
flag_display=false;
}
void cycle()
{
//omp_set_dynamic(0);
//omp_set_nested(0);
//omp_set_num_threads(std::thread::hardware_concurrency());
#ifdef _OPENMP
omp_set_num_threads(2);
#endif
#pragma omp parallel
{
#pragma omp master
std::cout
<< "Computation started, "
#ifdef _OPENMP
<< "OpenMP with " << omp_get_num_threads() << " threads"
#else
<< "single-threaded"
#endif
<< std::endl;
}
while (!quit) {
G->PS->step(next_game_time_target, pause);
std::this_thread::sleep_for(milliseconds(50));
if (pause) {
std::this_thread::sleep_for(milliseconds(100));
}
}
std::cout << "Computation finished" << std::endl;
}
// TODO: detect motionless regions
vect GetDomainMousePosition(int x, int y) {
vect c;
vect A(-1.,-1.), B(-1 + 2. * width / 800, -1. + 2. * height / 800);
c.x = A.x + (B.x - A.x) * (x / width);
c.y = B.y + (A.y - B.y) * (y / height);
return c;
}
vect GetDomainMousePosition() {
int x, y;
SDL_GetMouseState(&x, &y);
return GetDomainMousePosition(x, y);
}
int main() {
if (SDL_Init(SDL_INIT_VIDEO) != 0) {
SDL_Log("Unable to initialize SDL: %s\n", SDL_GetError());
return 1;
}
init();
SDL_Window* window = SDL_CreateWindow(
"ptoy",
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
width,
height,
SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE
);
if (window == NULL) {
SDL_Log("Unable to create window: %s\n", SDL_GetError());
return 1;
}
SDL_GLContext glcontext = SDL_GL_CreateContext(window);
auto gray = 0.5;
glClearColor(gray, gray, gray, 0.0);
glClear(GL_COLOR_BUFFER_BIT);
SDL_GL_SwapWindow(window);
G = std::unique_ptr<game>(new game(width, height));
std::thread computation_thread(cycle);
G->PS->SetForce(vect(0., 0.), false);
//Main loop flag
quit = false;
//Event handler
SDL_Event e;
enum class MouseState {None, Force, Bonds, Pick, Freeze, Portal};
MouseState mouse_state = MouseState::Force;
size_t quit_count = 0;
//While application is running
while (!quit) {
while (SDL_PollEvent( &e ) != 0) {
if (e.type == SDL_QUIT) {
quit = true;
} else if (e.type == SDL_KEYDOWN) {
if (e.key.keysym.sym != 'q') {
quit_count = 0;
}
switch( e.key.keysym.sym ) {
case 'q':
if (++quit_count >= 3) {
quit = true;
} else {
std::cout << "Quit counter: "
<< quit_count << "/3" << std::endl;
}
break;
case 'n':
mouse_state = MouseState::None;
std::cout << "Mouse switched to None mode" << std::endl;
break;
case 'r':
mouse_state = MouseState::Force;
std::cout << "Mouse switched to Repulsive mode" << std::endl;
G->PS->SetForceAttractive(false);
break;
case 'f':
mouse_state = MouseState::Freeze;
std::cout << "Mouse switched to Freeze mode" << std::endl;
break;
case 'p':
mouse_state = MouseState::Pick;
std::cout << "Mouse switched to Pick mode" << std::endl;
break;
case 'a':
mouse_state = MouseState::Force;
std::cout << "Mouse switched to Attractive mode" << std::endl;
G->PS->SetForceAttractive(true);
break;
case 'b':
mouse_state = MouseState::Bonds;
std::cout << "Mouse switched to Bonds mode" << std::endl;
break;
case 'o':
mouse_state = MouseState::Portal;
std::cout << "Mouse switched to Portal mode" << std::endl;
break;
case 'i':
std::cout << "Remove last portal" << std::endl;
G->PS->RemoveLastPortal();
break;
case 'g':
G->PS->InvertGravity();
std::cout
<< (G->PS->GetGravity() ? "Gravity on" : "Gravity off")
<< std::endl;
break;
case ' ':
pause = !pause;
break;
}
} else if (e.type == SDL_MOUSEMOTION) {
switch (mouse_state) {
case MouseState::Force:
G->PS->SetForce(GetDomainMousePosition());
break;
case MouseState::Bonds:
G->PS->BondsMove(GetDomainMousePosition());
break;
case MouseState::Pick:
G->PS->PickMove(GetDomainMousePosition());
break;
case MouseState::Freeze:
G->PS->FreezeMove(GetDomainMousePosition());
break;
case MouseState::Portal:
G->PS->PortalMove(GetDomainMousePosition());
break;
case MouseState::None:
break;
}
} else if (e.type == SDL_MOUSEBUTTONDOWN) {
switch (mouse_state) {
case MouseState::Force:
G->PS->SetForce(GetDomainMousePosition(), true);
break;
case MouseState::Bonds:
G->PS->BondsStart(GetDomainMousePosition());
break;
case MouseState::Pick:
G->PS->PickStart(GetDomainMousePosition());
break;
case MouseState::Freeze:
G->PS->FreezeStart(GetDomainMousePosition());
break;
case MouseState::Portal:
G->PS->PortalStart(GetDomainMousePosition());
break;
case MouseState::None:
break;
}
} else if (e.type == SDL_MOUSEBUTTONUP) {
switch (mouse_state) {
case MouseState::Force:
G->PS->SetForce(false);
break;
case MouseState::Bonds:
G->PS->BondsStop(GetDomainMousePosition());
break;
case MouseState::Pick:
G->PS->PickStop(GetDomainMousePosition());
break;
case MouseState::Freeze:
G->PS->FreezeStop(GetDomainMousePosition());
break;
case MouseState::Portal:
G->PS->PortalStop(GetDomainMousePosition());
break;
case MouseState::None:
break;
}
} else if (e.type == SDL_WINDOWEVENT) {
switch (e.window.event) {
case SDL_WINDOWEVENT_RESIZED:
width = e.window.data1;
height = e.window.data2;
glViewport(0, 0, width, height);
G->SetWindowSize(width, height);
break;
}
}
}
display();
SDL_GL_SwapWindow(window);
SDL_Delay(30);
}
// Finalize
SDL_GL_DeleteContext(glcontext);
SDL_DestroyWindow(window);
SDL_Quit();
computation_thread.join();
return 0;
}
<|endoftext|>
|
<commit_before>#include <GarrysMod/Lua/Interface.h>
#include <lua.hpp>
extern "C" int luaopen_ssl_core( lua_State *state );
extern "C" int luaopen_ssl_context( lua_State *state );
extern "C" int luaopen_ssl_x509( lua_State *state );
GMOD_MODULE_OPEN( )
{
if( luaopen_ssl_core( LUA->state ) == 1 )
{
lua_replace( LUA->state, 1 );
lua_settop( LUA->state, 1 );
LUA->Push( -1 );
LUA->SetField( GarrysMod::Lua::INDEX_GLOBAL, "ssl" );
}
if( luaopen_ssl_context( LUA->state ) == 1 )
{
lua_replace( LUA->state, 2 );
lua_settop( LUA->state, 2 );
LUA->SetField( -2, "context" );
}
if( luaopen_ssl_x509( LUA->state ) == 1 )
{
lua_replace( LUA->state, 2 );
lua_settop( LUA->state, 2 );
LUA->SetField( -2, "x509" );
}
return 1;
}
GMOD_MODULE_CLOSE( )
{
LUA->PushNil( );
LUA->SetField( GarrysMod::Lua::INDEX_GLOBAL, "ssl" );
return 0;
}
<commit_msg>use const LUA->GetState() instead of private member state<commit_after>#include <GarrysMod/Lua/Interface.h>
#include <lua.hpp>
extern "C" int luaopen_ssl_core( lua_State *state );
extern "C" int luaopen_ssl_context( lua_State *state );
extern "C" int luaopen_ssl_x509( lua_State *state );
GMOD_MODULE_OPEN( )
{
if( luaopen_ssl_core( LUA->GetState( ) ) == 1 )
{
lua_replace( LUA->GetState( ), 1 );
lua_settop( LUA->GetState( ), 1 );
LUA->Push( -1 );
LUA->SetField( GarrysMod::Lua::INDEX_GLOBAL, "ssl" );
}
if( luaopen_ssl_context( LUA->GetState( ) ) == 1 )
{
lua_replace( LUA->GetState( ), 2 );
lua_settop( LUA->GetState( ), 2 );
LUA->SetField( -2, "context" );
}
if( luaopen_ssl_x509( LUA->GetState( ) ) == 1 )
{
lua_replace( LUA->GetState( ), 2 );
lua_settop( LUA->GetState( ), 2 );
LUA->SetField( -2, "x509" );
}
return 1;
}
GMOD_MODULE_CLOSE( )
{
LUA->PushNil( );
LUA->SetField( GarrysMod::Lua::INDEX_GLOBAL, "ssl" );
return 0;
}
<|endoftext|>
|
<commit_before>#include <3ds.h>
#include <stdio.h>
void shutdown3DS()
{
Handle ptmSysmHandle = 0;
Result result = srvGetServiceHandle(&ptmSysmHandle, "ns:s");
if (result != 0)
return;
// http://3dbrew.org/wiki/NSS:ShutdownAsync
u32 *commandBuffer = getThreadCommandBuffer();
commandBuffer[0] = 0x000E0000;
svcSendSyncRequest(ptmSysmHandle);
svcCloseHandle(ptmSysmHandle);
}
int main(int argc, char **argv) {
hidScanInput();
#ifndef ALWAYS_SHUTDOWN
// If any key is pressed, cancel the shutdown.
if (hidKeysDown() != 0)
goto done;
#endif
shutdown3DS();
done:
// Hack: the 3ds crashes ("An error has occcurred.") for some reason
// without one iteration of the main loop.
aptMainLoop();
return 0;
}
<commit_msg>Rename a variable due to using a different service.<commit_after>#include <3ds.h>
#include <stdio.h>
void shutdown3DS()
{
Handle nssHandle = 0;
Result result = srvGetServiceHandle(&nssHandle, "ns:s");
if (result != 0)
return;
// http://3dbrew.org/wiki/NSS:ShutdownAsync
u32 *commandBuffer = getThreadCommandBuffer();
commandBuffer[0] = 0x000E0000;
svcSendSyncRequest(nssHandle);
svcCloseHandle(nssHandle);
}
int main(int argc, char **argv) {
hidScanInput();
#ifndef ALWAYS_SHUTDOWN
// If any key is pressed, cancel the shutdown.
if (hidKeysDown() != 0)
goto done;
#endif
shutdown3DS();
done:
// Hack: the 3ds crashes ("An error has occcurred.") for some reason
// without one iteration of the main loop.
aptMainLoop();
return 0;
}
<|endoftext|>
|
<commit_before>#include <ctrcommon/app.hpp>
#include <ctrcommon/gpu.hpp>
#include <ctrcommon/input.hpp>
#include <ctrcommon/nor.hpp>
#include <ctrcommon/platform.hpp>
#include <ctrcommon/ui.hpp>
#include "rop.h"
#include <sys/errno.h>
#include <stdio.h>
#include <string.h>
#include <sstream>
#include <iomanip>
typedef enum {
INSTALL_CIA,
DELETE_CIA,
DELETE_TITLE,
LAUNCH_TITLE
} Mode;
int main(int argc, char **argv) {
if(!platformInit()) {
return 0;
}
bool ninjhax = platformIsNinjhax();
std::vector<std::string> extensions;
extensions.push_back("cia");
MediaType destination = SD;
Mode mode = INSTALL_CIA;
bool exit = false;
bool netInstall = false;
u64 freeSpace = fsGetFreeSpace(destination);
auto onLoop = [&]() {
if(ninjhax && inputIsPressed(BUTTON_START)) {
exit = true;
return true;
}
bool breakLoop = false;
if(inputIsPressed(BUTTON_L)) {
if(destination == SD) {
destination = NAND;
} else {
destination = SD;
}
freeSpace = fsGetFreeSpace(destination);
if(mode == DELETE_TITLE || mode == LAUNCH_TITLE) {
breakLoop = true;
}
}
if(inputIsPressed(BUTTON_R)) {
if(mode == INSTALL_CIA) {
mode = DELETE_CIA;
} else if(mode == DELETE_CIA) {
mode = DELETE_TITLE;
breakLoop = true;
} else if(mode == DELETE_TITLE) {
mode = LAUNCH_TITLE;
} else if(mode == LAUNCH_TITLE) {
mode = INSTALL_CIA;
breakLoop = true;
}
}
if(mode == INSTALL_CIA && inputIsPressed(BUTTON_Y)) {
netInstall = true;
breakLoop = true;
}
if(inputIsPressed(BUTTON_SELECT)) {
u32 selected = 0;
bool dirty = true;
while(platformIsRunning()) {
inputPoll();
if(inputIsPressed(BUTTON_B)) {
break;
}
if(inputIsPressed(BUTTON_A)) {
std::stringstream stream;
stream << "Install the selected ROP?" << "\n";
stream << ropNames[selected];
if(uiPrompt(TOP_SCREEN, stream.str(), true)) {
u16 userSettingsOffset = 0;
bool result = norRead(0x20, &userSettingsOffset, 2) && norWrite(userSettingsOffset << 3, rops[selected], ROP_SIZE);
std::stringstream resultMsg;
resultMsg << "ROP installation ";
if(result) {
resultMsg << "succeeded!";
} else {
resultMsg << "failed!" << "\n";
resultMsg << platformGetErrorString(platformGetError());
}
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
break;
}
}
if(inputIsPressed(BUTTON_LEFT)) {
if(selected == 0) {
selected = ROP_COUNT - 1;
} else {
selected--;
}
dirty = true;
}
if(inputIsPressed(BUTTON_RIGHT)) {
if(selected >= ROP_COUNT - 1) {
selected = 0;
} else {
selected++;
}
dirty = true;
}
if(dirty) {
std::stringstream stream;
stream << "Select a ROP to install." << "\n";
stream << "< " << ropNames[selected] << " >" << "\n";
stream << "Press A to install, B to cancel.";
uiDisplayMessage(TOP_SCREEN, stream.str());
}
}
}
std::stringstream stream;
stream << "Battery: ";
if(platformIsBatteryCharging()) {
stream << "Charging";
} else {
for(u32 i = 0; i < platformGetBatteryLevel(); i++) {
stream << "|";
}
}
stream << ", WiFi: ";
if(!platformIsWifiConnected()) {
stream << "Disconnected";
} else {
for(u32 i = 0; i < platformGetWifiLevel(); i++) {
stream << "|";
}
}
stream << "\n";
stream << "Free Space: " << freeSpace << " bytes (" << std::fixed << std::setprecision(2) << freeSpace / 1024.0f / 1024.0f << "MB)" << "\n";
stream << "Destination: " << (destination == NAND ? "NAND" : "SD") << ", Mode: " << (mode == INSTALL_CIA ? "Install CIA" : mode == DELETE_CIA ? "Delete CIA" : mode == DELETE_TITLE ? "Delete Title" : "Launch Title") << "\n";
stream << "L - Switch Destination, R - Switch Mode" << "\n";
if(mode == INSTALL_CIA) {
stream << "X - Install all CIAs in the current directory" << "\n";
stream << "Y - Receive an app over the network" << "\n";
} else if(mode == DELETE_CIA) {
stream << "X - Delete all CIAs in the current directory" << "\n";
}
stream << "SELECT - Install MSET ROP";
if(ninjhax) {
stream << "\n" << "START - Exit to launcher";
}
std::string str = stream.str();
const std::string title = "FBI v1.4";
gputDrawString(title, (gpuGetViewportWidth() - gputGetStringWidth(title, 16)) / 2, (gpuGetViewportHeight() - gputGetStringHeight(title, 16) + gputGetStringHeight(str, 8)) / 2, 16, 16);
gputDrawString(str, (gpuGetViewportWidth() - gputGetStringWidth(str, 8)) / 2, 4, 8, 8);
return breakLoop;
};
std::string batchInfo = "";
int prevProgress = -1;
auto onProgress = [&](u64 pos, u64 totalSize) {
u32 progress = (u32) ((pos * 100) / totalSize);
if(prevProgress != (int) progress) {
prevProgress = (int) progress;
std::stringstream details;
details << batchInfo;
details << "Press B to cancel.";
uiDisplayProgress(TOP_SCREEN, "Installing", details.str(), true, progress);
}
inputPoll();
return !inputIsPressed(BUTTON_B);
};
bool showNetworkPrompts = true;
while(platformIsRunning()) {
std::string fileTarget;
App appTarget;
if(mode == INSTALL_CIA || mode == DELETE_CIA) {
if(netInstall && !exit) {
gpuClearScreens();
RemoteFile file = uiAcceptRemoteFile(TOP_SCREEN, [&](std::stringstream& infoStream) {
if(inputIsPressed(BUTTON_A)) {
showNetworkPrompts = !showNetworkPrompts;
}
infoStream << "\n";
infoStream << "Prompts: " << (showNetworkPrompts ? "Enabled" : "Disabled") << "\n";
infoStream << "Press A to toggle prompts.";
});
if(file.fd == NULL) {
netInstall = false;
continue;
}
std::stringstream confirmStream;
confirmStream << "Install the received application?" << "\n";
confirmStream << "Size: " << file.fileSize << " bytes (" << std::fixed << std::setprecision(2) << file.fileSize / 1024.0f / 1024.0f << "MB)";
if(!showNetworkPrompts || uiPrompt(TOP_SCREEN, confirmStream.str(), true)) {
AppResult ret = appInstall(destination, file.fd, file.fileSize, onProgress);
prevProgress = -1;
if(showNetworkPrompts || ret != APP_SUCCESS) {
std::stringstream resultMsg;
resultMsg << "Install ";
if(ret == APP_SUCCESS) {
resultMsg << "succeeded!";
} else {
resultMsg << "failed!" << "\n";
resultMsg << appGetResultString(ret);
}
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
}
}
fclose(file.fd);
continue;
}
uiSelectFile(&fileTarget, "/", extensions, [&](const std::string currDirectory, bool inRoot, bool &updateList) {
if(inputIsPressed(BUTTON_X)) {
std::stringstream confirmMsg;
if(mode == INSTALL_CIA) {
confirmMsg << "Install ";
} else {
confirmMsg << "Delete ";
}
confirmMsg << "all CIAs in the current directory?";
if(uiPrompt(TOP_SCREEN, confirmMsg.str(), true)) {
bool failed = false;
std::vector<FileInfo> contents = fsGetDirectoryContents(currDirectory);
u32 currItem = 0;
for(std::vector<FileInfo>::iterator it = contents.begin(); it != contents.end(); it++) {
std::string path = (*it).path;
if(!fsIsDirectory(path) && fsHasExtensions(path, extensions)) {
std::string displayFileName = (*it).name;
if(displayFileName.length() > 40) {
displayFileName.resize(40);
displayFileName += "...";
}
if(mode == INSTALL_CIA) {
std::stringstream batchInstallStream;
batchInstallStream << displayFileName << " (" << currItem << ")" << "\n";
batchInfo = batchInstallStream.str();
AppResult ret = appInstallFile(destination, path, onProgress);
prevProgress = -1;
batchInfo = "";
if(ret != APP_SUCCESS) {
Error error = platformGetError();
platformSetError(error);
std::stringstream resultMsg;
resultMsg << "Install failed!" << "\n";
resultMsg << displayFileName << "\n";
resultMsg << appGetResultString(ret);
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
if(error.module != MODULE_NN_AM || error.description != DESCRIPTION_ALREADY_EXISTS) {
failed = true;
break;
}
}
} else {
std::stringstream deleteStream;
deleteStream << "Deleting CIA..." << "\n";
deleteStream << displayFileName << " (" << currItem << ")";
uiDisplayMessage(TOP_SCREEN, deleteStream.str());
if(remove(path.c_str()) != 0) {
std::stringstream resultMsg;
resultMsg << "Delete failed!" << "\n";
resultMsg << displayFileName << "\n";
resultMsg << strerror(errno);
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
failed = true;
break;
} else {
updateList = true;
}
}
}
currItem++;
}
if(!failed) {
uiPrompt(TOP_SCREEN, "Install succeeded!\n", false);
}
freeSpace = fsGetFreeSpace(destination);
}
}
return onLoop();
}, [&](const std::string path, bool &updateList) {
std::stringstream confirmMsg;
if(mode == INSTALL_CIA) {
confirmMsg << "Install ";
} else {
confirmMsg << "Delete ";
}
confirmMsg << "the selected CIA?";
if(uiPrompt(TOP_SCREEN, confirmMsg.str(), true)) {
std::stringstream resultMsg;
if(mode == INSTALL_CIA) {
resultMsg << "Install ";
} else {
resultMsg << "Delete ";
}
if(mode == INSTALL_CIA) {
AppResult ret = appInstallFile(destination, path, onProgress);
prevProgress = -1;
if(ret == APP_SUCCESS) {
resultMsg << "succeeded!";
} else {
resultMsg << "failed!" << "\n";
resultMsg << appGetResultString(ret);
}
} else {
uiDisplayMessage(TOP_SCREEN, "Deleting CIA...");
if(remove(path.c_str()) != 0) {
updateList = true;
resultMsg << "succeeded!";
} else {
resultMsg << "failed!" << "\n";
resultMsg << strerror(errno);
}
}
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
freeSpace = fsGetFreeSpace(destination);
}
return false;
});
} else if(mode == DELETE_TITLE || mode == LAUNCH_TITLE) {
uiDisplayMessage(BOTTOM_SCREEN, "Loading title list...");
uiSelectApp(&appTarget, destination, [&](bool &updateList) {
return onLoop();
}, [&](App app, bool &updateList) {
if(mode == DELETE_TITLE) {
if(uiPrompt(TOP_SCREEN, "Delete the selected title?", true) && (destination != NAND || uiPrompt(TOP_SCREEN, "You are about to delete a title from the NAND.\nTHIS HAS THE POTENTIAL TO BRICK YOUR 3DS!\nAre you sure you wish to continue?", true))) {
updateList = true;
uiDisplayMessage(TOP_SCREEN, "Deleting title...");
AppResult ret = appDelete(app);
std::stringstream resultMsg;
resultMsg << "Delete ";
if(ret == APP_SUCCESS) {
resultMsg << "succeeded!";
} else {
resultMsg << "failed!" << "\n";
resultMsg << appGetResultString(ret);
}
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
freeSpace = fsGetFreeSpace(destination);
}
} else if(mode == LAUNCH_TITLE) {
if(uiPrompt(TOP_SCREEN, "Launch the selected title?", true)) {
updateList = true;
uiDisplayMessage(TOP_SCREEN, "Launching title...");
AppResult ret = appLaunch(app);
if(ret != APP_SUCCESS) {
std::stringstream resultMsg;
resultMsg << "Launch failed!" << "\n";
resultMsg << appGetResultString(ret);
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
} else {
while(true) {
}
}
}
}
return false;
});
}
if(exit) {
break;
}
}
platformCleanup();
return 0;
}
<commit_msg>Add file list loading screen, move network installation code into loop to avoid reloading lists.<commit_after>#include <ctrcommon/app.hpp>
#include <ctrcommon/gpu.hpp>
#include <ctrcommon/input.hpp>
#include <ctrcommon/nor.hpp>
#include <ctrcommon/platform.hpp>
#include <ctrcommon/ui.hpp>
#include "rop.h"
#include <sys/errno.h>
#include <stdio.h>
#include <string.h>
#include <sstream>
#include <iomanip>
typedef enum {
INSTALL_CIA,
DELETE_CIA,
DELETE_TITLE,
LAUNCH_TITLE
} Mode;
int main(int argc, char **argv) {
if(!platformInit()) {
return 0;
}
bool ninjhax = platformIsNinjhax();
std::vector<std::string> extensions;
extensions.push_back("cia");
MediaType destination = SD;
Mode mode = INSTALL_CIA;
bool exit = false;
bool showNetworkPrompts = true;
u64 freeSpace = fsGetFreeSpace(destination);
std::string batchInfo = "";
int prevProgress = -1;
auto onProgress = [&](u64 pos, u64 totalSize) {
u32 progress = (u32) ((pos * 100) / totalSize);
if(prevProgress != (int) progress) {
prevProgress = (int) progress;
std::stringstream details;
details << batchInfo;
details << "Press B to cancel.";
uiDisplayProgress(TOP_SCREEN, "Installing", details.str(), true, progress);
}
inputPoll();
return !inputIsPressed(BUTTON_B);
};
auto onLoop = [&]() {
if(ninjhax && inputIsPressed(BUTTON_START)) {
exit = true;
return true;
}
bool breakLoop = false;
if(inputIsPressed(BUTTON_L)) {
if(destination == SD) {
destination = NAND;
} else {
destination = SD;
}
freeSpace = fsGetFreeSpace(destination);
if(mode == DELETE_TITLE || mode == LAUNCH_TITLE) {
breakLoop = true;
}
}
if(inputIsPressed(BUTTON_R)) {
if(mode == INSTALL_CIA) {
mode = DELETE_CIA;
} else if(mode == DELETE_CIA) {
mode = DELETE_TITLE;
breakLoop = true;
} else if(mode == DELETE_TITLE) {
mode = LAUNCH_TITLE;
} else if(mode == LAUNCH_TITLE) {
mode = INSTALL_CIA;
breakLoop = true;
}
}
if(mode == INSTALL_CIA && inputIsPressed(BUTTON_Y)) {
while(platformIsRunning()) {
gpuClearScreens();
RemoteFile file = uiAcceptRemoteFile(TOP_SCREEN, [&](std::stringstream& infoStream) {
if(inputIsPressed(BUTTON_A)) {
showNetworkPrompts = !showNetworkPrompts;
}
infoStream << "\n";
infoStream << "Prompts: " << (showNetworkPrompts ? "Enabled" : "Disabled") << "\n";
infoStream << "Press A to toggle prompts.";
});
if(file.fd == NULL) {
break;
}
std::stringstream confirmStream;
confirmStream << "Install the received application?" << "\n";
confirmStream << "Size: " << file.fileSize << " bytes (" << std::fixed << std::setprecision(2) << file.fileSize / 1024.0f / 1024.0f << "MB)";
if(!showNetworkPrompts || uiPrompt(TOP_SCREEN, confirmStream.str(), true)) {
AppResult ret = appInstall(destination, file.fd, file.fileSize, onProgress);
prevProgress = -1;
if(showNetworkPrompts || ret != APP_SUCCESS) {
std::stringstream resultMsg;
resultMsg << "Install ";
if(ret == APP_SUCCESS) {
resultMsg << "succeeded!";
} else {
resultMsg << "failed!" << "\n";
resultMsg << appGetResultString(ret);
}
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
}
}
fclose(file.fd);
}
}
if(inputIsPressed(BUTTON_SELECT)) {
u32 selected = 0;
bool dirty = true;
while(platformIsRunning()) {
inputPoll();
if(inputIsPressed(BUTTON_B)) {
break;
}
if(inputIsPressed(BUTTON_A)) {
std::stringstream stream;
stream << "Install the selected ROP?" << "\n";
stream << ropNames[selected];
if(uiPrompt(TOP_SCREEN, stream.str(), true)) {
u16 userSettingsOffset = 0;
bool result = norRead(0x20, &userSettingsOffset, 2) && norWrite(userSettingsOffset << 3, rops[selected], ROP_SIZE);
std::stringstream resultMsg;
resultMsg << "ROP installation ";
if(result) {
resultMsg << "succeeded!";
} else {
resultMsg << "failed!" << "\n";
resultMsg << platformGetErrorString(platformGetError());
}
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
}
dirty = true;
}
if(inputIsPressed(BUTTON_LEFT)) {
if(selected == 0) {
selected = ROP_COUNT - 1;
} else {
selected--;
}
dirty = true;
}
if(inputIsPressed(BUTTON_RIGHT)) {
if(selected >= ROP_COUNT - 1) {
selected = 0;
} else {
selected++;
}
dirty = true;
}
if(dirty) {
std::stringstream stream;
stream << "Select a ROP to install." << "\n";
stream << "< " << ropNames[selected] << " >" << "\n";
stream << "Press A to install, B to cancel.";
uiDisplayMessage(TOP_SCREEN, stream.str());
}
}
}
std::stringstream stream;
stream << "Battery: ";
if(platformIsBatteryCharging()) {
stream << "Charging";
} else {
for(u32 i = 0; i < platformGetBatteryLevel(); i++) {
stream << "|";
}
}
stream << ", WiFi: ";
if(!platformIsWifiConnected()) {
stream << "Disconnected";
} else {
for(u32 i = 0; i < platformGetWifiLevel(); i++) {
stream << "|";
}
}
stream << "\n";
stream << "Free Space: " << freeSpace << " bytes (" << std::fixed << std::setprecision(2) << freeSpace / 1024.0f / 1024.0f << "MB)" << "\n";
stream << "Destination: " << (destination == NAND ? "NAND" : "SD") << ", Mode: " << (mode == INSTALL_CIA ? "Install CIA" : mode == DELETE_CIA ? "Delete CIA" : mode == DELETE_TITLE ? "Delete Title" : "Launch Title") << "\n";
stream << "L - Switch Destination, R - Switch Mode" << "\n";
if(mode == INSTALL_CIA) {
stream << "X - Install all CIAs in the current directory" << "\n";
stream << "Y - Receive an app over the network" << "\n";
} else if(mode == DELETE_CIA) {
stream << "X - Delete all CIAs in the current directory" << "\n";
}
stream << "SELECT - Install MSET ROP";
if(ninjhax) {
stream << "\n" << "START - Exit to launcher";
}
std::string str = stream.str();
const std::string title = "FBI v1.4.1";
gputDrawString(title, (gpuGetViewportWidth() - gputGetStringWidth(title, 16)) / 2, (gpuGetViewportHeight() - gputGetStringHeight(title, 16) + gputGetStringHeight(str, 8)) / 2, 16, 16);
gputDrawString(str, (gpuGetViewportWidth() - gputGetStringWidth(str, 8)) / 2, 4, 8, 8);
return breakLoop;
};
while(platformIsRunning()) {
if(mode == INSTALL_CIA || mode == DELETE_CIA) {
uiDisplayMessage(BOTTOM_SCREEN, "Loading file list...");
std::string fileTarget;
uiSelectFile(&fileTarget, "/", extensions, [&](const std::string currDirectory, bool inRoot, bool &updateList) {
if(inputIsPressed(BUTTON_X)) {
std::stringstream confirmMsg;
if(mode == INSTALL_CIA) {
confirmMsg << "Install ";
} else {
confirmMsg << "Delete ";
}
confirmMsg << "all CIAs in the current directory?";
if(uiPrompt(TOP_SCREEN, confirmMsg.str(), true)) {
bool failed = false;
std::vector<FileInfo> contents = fsGetDirectoryContents(currDirectory);
u32 currItem = 0;
for(std::vector<FileInfo>::iterator it = contents.begin(); it != contents.end(); it++) {
std::string path = (*it).path;
if(!fsIsDirectory(path) && fsHasExtensions(path, extensions)) {
std::string displayFileName = (*it).name;
if(displayFileName.length() > 40) {
displayFileName.resize(40);
displayFileName += "...";
}
if(mode == INSTALL_CIA) {
std::stringstream batchInstallStream;
batchInstallStream << displayFileName << " (" << currItem << ")" << "\n";
batchInfo = batchInstallStream.str();
AppResult ret = appInstallFile(destination, path, onProgress);
prevProgress = -1;
batchInfo = "";
if(ret != APP_SUCCESS) {
Error error = platformGetError();
platformSetError(error);
std::stringstream resultMsg;
resultMsg << "Install failed!" << "\n";
resultMsg << displayFileName << "\n";
resultMsg << appGetResultString(ret);
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
if(error.module != MODULE_NN_AM || error.description != DESCRIPTION_ALREADY_EXISTS) {
failed = true;
break;
}
}
} else {
std::stringstream deleteStream;
deleteStream << "Deleting CIA..." << "\n";
deleteStream << displayFileName << " (" << currItem << ")";
uiDisplayMessage(TOP_SCREEN, deleteStream.str());
if(remove(path.c_str()) != 0) {
std::stringstream resultMsg;
resultMsg << "Delete failed!" << "\n";
resultMsg << displayFileName << "\n";
resultMsg << strerror(errno);
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
failed = true;
break;
} else {
updateList = true;
}
}
}
currItem++;
}
if(!failed) {
uiPrompt(TOP_SCREEN, "Install succeeded!\n", false);
}
freeSpace = fsGetFreeSpace(destination);
}
}
return onLoop();
}, [&](const std::string path, bool &updateList) {
std::stringstream confirmMsg;
if(mode == INSTALL_CIA) {
confirmMsg << "Install ";
} else {
confirmMsg << "Delete ";
}
confirmMsg << "the selected CIA?";
if(uiPrompt(TOP_SCREEN, confirmMsg.str(), true)) {
std::stringstream resultMsg;
if(mode == INSTALL_CIA) {
resultMsg << "Install ";
} else {
resultMsg << "Delete ";
}
if(mode == INSTALL_CIA) {
AppResult ret = appInstallFile(destination, path, onProgress);
prevProgress = -1;
if(ret == APP_SUCCESS) {
resultMsg << "succeeded!";
} else {
resultMsg << "failed!" << "\n";
resultMsg << appGetResultString(ret);
}
} else {
uiDisplayMessage(TOP_SCREEN, "Deleting CIA...");
if(remove(path.c_str()) != 0) {
updateList = true;
resultMsg << "succeeded!";
} else {
resultMsg << "failed!" << "\n";
resultMsg << strerror(errno);
}
}
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
freeSpace = fsGetFreeSpace(destination);
}
return false;
});
} else if(mode == DELETE_TITLE || mode == LAUNCH_TITLE) {
uiDisplayMessage(BOTTOM_SCREEN, "Loading title list...");
App appTarget;
uiSelectApp(&appTarget, destination, [&](bool &updateList) {
return onLoop();
}, [&](App app, bool &updateList) {
if(mode == DELETE_TITLE) {
if(uiPrompt(TOP_SCREEN, "Delete the selected title?", true) && (destination != NAND || uiPrompt(TOP_SCREEN, "You are about to delete a title from the NAND.\nTHIS HAS THE POTENTIAL TO BRICK YOUR 3DS!\nAre you sure you wish to continue?", true))) {
updateList = true;
uiDisplayMessage(TOP_SCREEN, "Deleting title...");
AppResult ret = appDelete(app);
std::stringstream resultMsg;
resultMsg << "Delete ";
if(ret == APP_SUCCESS) {
resultMsg << "succeeded!";
} else {
resultMsg << "failed!" << "\n";
resultMsg << appGetResultString(ret);
}
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
freeSpace = fsGetFreeSpace(destination);
}
} else if(mode == LAUNCH_TITLE) {
if(uiPrompt(TOP_SCREEN, "Launch the selected title?", true)) {
updateList = true;
uiDisplayMessage(TOP_SCREEN, "Launching title...");
AppResult ret = appLaunch(app);
if(ret != APP_SUCCESS) {
std::stringstream resultMsg;
resultMsg << "Launch failed!" << "\n";
resultMsg << appGetResultString(ret);
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
} else {
while(true) {
}
}
}
}
return false;
});
}
if(exit) {
break;
}
}
platformCleanup();
return 0;
}
<|endoftext|>
|
<commit_before>#include "CLIParser.h"
namespace ros2_components
{
CLIParser::CLIParser(char *argv[], int argc, std::string _programDescription)
{
for(int i=0; i < argc;i++)
{
this->arguments.push_back(std::string(argv[i]));
}
//0 arg is the program name
this->baseVerb = std::make_shared<CLIVerb>(arguments[0], _programDescription,nullptr);
this->baseVerb->addArgument(std::make_shared<CLIArgument>("help", "Print this help", &helpFound ));
}
void CLIParser::parse()
{
arguments.erase(arguments.begin());
this->baseVerb->parse(arguments);
if(helpFound)
{
printHelp(this->helpString);
}
}
void CLIParser::addVerb(CLIVerb::SharedPtr verb)
{
this->baseVerb->addVerb(verb);
}
void CLIParser::addArgument(CLIArgument::SharedPtr arg)
{
this->baseVerb->addArgument(arg);
}
void CLIParser::printHelp(std::string additionalInformation)
{
int depth = 0;
std::cout << additionalInformation << std::endl;
std::function<void(CLIVerb::SharedPtr)> func = [&](CLIVerb::SharedPtr verb)
{
if(!verb)
return;
for(int i = 0; i < depth; i++)
std::cout << " ";
std::cout << printInColor(verb->getName(),ConsoleColor::FG_BLUE) << std::endl;
for(int i = 0; i < depth+4; i++)
std::cout << " ";
std::cout << verb->getDescription() << std::endl << std::endl;
if(verb->getAllCliParameter().size() > 0)
{
for(int i = 0; i < depth+2; i++)
std::cout << " ";
std::cout << "Needed parameters: " << std::endl;
}
for(auto cliParam : verb->getAllCliParameter())
{
for(int i = 0; i < depth+4; i++)
std::cout << " ";
std::string output = cliParam->getName() + " ";
output.insert(20, cliParam->getDescription());
std::cout << output << std::endl;
}
for(auto cliArg : verb->getAllCliArguments())
{
for(int i = 0; i < depth+4; i++)
std::cout << " ";
std::string output = " --" + cliArg->getName() + " ";
output.insert(20, cliArg->getDescription());
std::cout << output << std::endl;
}
depth = depth+2;
for(auto subVerbEntry : verb->getChildVerbs())
{
CLIVerb::SharedPtr subVerb = subVerbEntry.second;
func(subVerb);
}
depth = depth-2;
};
func(this->baseVerb);
}
bool CLIParser::getHelpFound() const
{
return helpFound;
}
CLIVerb::SharedPtr CLIParser::getBaseVerb() const
{
return baseVerb;
}
}
<commit_msg>fixed bug<commit_after>#include "CLIParser.h"
namespace ros2_components
{
CLIParser::CLIParser(char *argv[], int argc, std::string _programDescription)
{
for(int i=0; i < argc;i++)
{
this->arguments.push_back(std::string(argv[i]));
}
//0 arg is the program name
this->baseVerb = std::make_shared<CLIVerb>(arguments[0], _programDescription,nullptr);
this->baseVerb->addArgument(std::make_shared<CLIArgument>("help", "Print this help", &helpFound ));
}
void CLIParser::parse()
{
if(arguments.size() <= 0)
return;
arguments.erase(arguments.begin());
this->baseVerb->parse(arguments);
if(helpFound)
{
printHelp(this->helpString);
}
}
void CLIParser::addVerb(CLIVerb::SharedPtr verb)
{
this->baseVerb->addVerb(verb);
}
void CLIParser::addArgument(CLIArgument::SharedPtr arg)
{
this->baseVerb->addArgument(arg);
}
void CLIParser::printHelp(std::string additionalInformation)
{
int depth = 0;
std::cout << additionalInformation << std::endl;
std::function<void(CLIVerb::SharedPtr)> func = [&](CLIVerb::SharedPtr verb)
{
if(!verb)
return;
for(int i = 0; i < depth; i++)
std::cout << " ";
std::cout << printInColor(verb->getName(),ConsoleColor::FG_BLUE) << std::endl;
for(int i = 0; i < depth+4; i++)
std::cout << " ";
std::cout << verb->getDescription() << std::endl << std::endl;
if(verb->getAllCliParameter().size() > 0)
{
for(int i = 0; i < depth+2; i++)
std::cout << " ";
std::cout << "Needed parameters: " << std::endl;
}
for(auto cliParam : verb->getAllCliParameter())
{
for(int i = 0; i < depth+4; i++)
std::cout << " ";
std::string output = cliParam->getName() + " ";
output.insert(20, cliParam->getDescription());
std::cout << output << std::endl;
}
for(auto cliArg : verb->getAllCliArguments())
{
for(int i = 0; i < depth+4; i++)
std::cout << " ";
std::string output = " --" + cliArg->getName() + " ";
output.insert(20, cliArg->getDescription());
std::cout << output << std::endl;
}
depth = depth+2;
for(auto subVerbEntry : verb->getChildVerbs())
{
CLIVerb::SharedPtr subVerb = subVerbEntry.second;
func(subVerb);
}
depth = depth-2;
};
func(this->baseVerb);
}
bool CLIParser::getHelpFound() const
{
return helpFound;
}
CLIVerb::SharedPtr CLIParser::getBaseVerb() const
{
return baseVerb;
}
}
<|endoftext|>
|
<commit_before>#include <QApplication>
#include "mainwindow.h"
#include <QtWidgets>
#include <QWebFrame>
#include <QWebInspector>
/*
* Utility:
* ./exectuable pageAddress width height decoration (BOTTOM_MOST)
*
* - pageAddress: the html file path or url
* - width: integer that represent the width of the window
* - height: integer that represent the height of the window
* - decoration: if it is "UNDECORATED" the window will be undecorated (it will not have
* borders and the window buttons
*
* */
QWebView *webView;
bool debugMode = false;
QStringList applicationArguments;
/*
* Javascript functions (Public API)
* */
class JohnnysWebviewJavaScriptOperations : public QObject {
Q_OBJECT
public:
/*
* Close window
* $API.closeWindow();
*
**/
Q_INVOKABLE void closeWindow () {
if (debugMode) {
qDebug() << "[INFO] Closing window.";
}
webView->close();
}
/*
* Resize
* $API.resize(width, height);
*
**/
Q_INVOKABLE void resize (int width, int height) {
if (debugMode) {
qDebug() << "[INFO] Resizing window: width=" << width << "px; height=" << height << "px." ;
}
webView->resize(width, height);
}
/*
* Set window flags
* $API.setWindowFlags (type)
* - UNDECORATED
*
* */
Q_INVOKABLE void setWindowFlags (QString type) {
if (debugMode) {
qDebug() << "[INFO] Setting window flag: " << type;
}
QStringList options;
options << "UNDECORATED"
<< "BOTTOM_MOST"
<< "TOP_MOST"
<< "REMOVE_MINIMIZE"
<< "REMOVE_MAXIMIZE"
<< "REMOVE_CLOSE";
switch (options.indexOf(type)) {
case 0:
webView->setWindowFlags(Qt::FramelessWindowHint | webView->windowFlags());
webView->show();
break;
case 1:
webView->setWindowFlags(Qt::WindowStaysOnBottomHint | webView->windowFlags());
webView->show();
break;
case 2:
webView->setWindowFlags(Qt::WindowStaysOnTopHint | webView->windowFlags());
webView->show();
break;
case 3:
webView->setWindowFlags(webView->windowFlags() & ~Qt::WindowMinimizeButtonHint);
webView->show();
break;
case 4:
webView->setWindowFlags(webView->windowFlags() & ~Qt::WindowMaximizeButtonHint);
webView->show();
break;
case 5:
webView->setWindowFlags(webView->windowFlags() & ~Qt::WindowCloseButtonHint);
webView->show();
break;
// TODO Other cases
}
}
/*
* Set window state
* $API.setWindowState (value)
* - MAXIMIZED
* - MINIMIZED
* - FULLSCREEN
* - ACTIVE
* */
Q_INVOKABLE void setWindowState (QString type) {
if (debugMode) {
qDebug() << "[INFO] Setting window state: " << type;
}
QStringList options;
options << "MAXIMIZED" << "MINIMIZED" << "FULLSCREEN" << "ACTIVATE" << "RESTORED";
switch (options.indexOf(type)) {
case 0:
webView->setWindowState(Qt::WindowMaximized);
break;
case 1:
webView->setWindowState(Qt::WindowMinimized);
break;
case 2:
webView->setWindowState(Qt::WindowFullScreen);
break;
case 3:
webView->setWindowState(Qt::WindowActive);
break;
case 4:
webView->setWindowState(Qt::WindowNoState);
break;
}
}
/*
* Get window size
* $API.getWindowSize ()
* */
Q_INVOKABLE QObject *getWindowSize () {
if (debugMode) {
qDebug() << "[INFO] Getting the window size.";
}
QObject *size = new QObject();
QSize winSize = webView->size();
size->setProperty("width", winSize.width());
size->setProperty("height", winSize.height());
return size;
}
/*
* Get screen size
* $API.getScreenSize ()
*
* */
Q_INVOKABLE QObject *getScreenSize () {
if (debugMode) {
qDebug() << "[INFO] Getting screen size.";
}
QObject *size = new QObject();
QSize screenSize = qApp->primaryScreen()->size();
size->setProperty("width", screenSize.width());
size->setProperty("height", screenSize.height());
return size;
}
/*
* Set window position
* $API.setWindowPosition (left, top)
* */
Q_INVOKABLE void setWindowPosition (int left, int top) {
if (debugMode) {
qDebug() << "[INFO] Setting the window position: left=" << left << "px; top=" << top << "px.";
}
webView->move(left, top);
}
/*
* Get window position
* $API.getWindowPosition (left, top)
* */
Q_INVOKABLE QObject *getWindowPosition () {
if (debugMode) {
qDebug() << "[INFO] Getting the window position.";
}
QObject *position = new QObject();
QPoint point = webView->pos();
position->setProperty("left", point.x());
position->setProperty("top", point.y());
return position;
}
/*
* Get mouse position
* $API.getMousePosition()
*
* */
Q_INVOKABLE QObject *getMousePosition () {
if (debugMode) {
qDebug() << "[INFO] Getting the mouse position.";
}
QObject *position = new QObject();
QPoint point = QCursor::pos();
position->setProperty("left", point.x());
position->setProperty("top", point.y());
return position;
}
/*
* Set mouse position
* $API.setMousePosition()
*
* */
Q_INVOKABLE void setMousePosition (int x, int y) {
if (debugMode) {
qDebug() << "[INFO] Setting the mouse position: x=" << x << "px; y=" << y << "px.";
}
QCursor::setPos(x, y);
}
/*
* Creates a new window
* $API.newWindow(options);
* */
// TODO Is this really needed?
// Q_INVOKABLE void newWindow () {
// QWindow newWindow = new QWindow();
// newWindow.show();
// }
/*
* Sets the title of the current window
* $API.setWindowTitle(newTitle)
*
* */
Q_INVOKABLE void setWindowTitle (QString newTitle) {
if (debugMode) {
qDebug() << "[INFO] Setting the window title: " << newTitle;
}
webView->setWindowTitle(newTitle);
}
/*
* Writes content to file
* $API.writeFile (path, content);
*
* */
Q_INVOKABLE void writeFile (QString path, QString content) {
if (debugMode) {
qDebug() << "[INFO] Writting to file: " << path;
}
QFile file(path);
if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
if (debugMode) {
qDebug() << "[WARNING] Cannot write file.";
}
return;
}
QTextStream out(&file);
out << content;
}
/*
* Returns the content content of a file
* $API.readFile (path);
*
* */
Q_INVOKABLE QString readFile (QString path) {
if (debugMode) {
qDebug() << "[INFO] Reading from file: " << path;
}
QFile file(path);
if(!file.open(QIODevice::ReadOnly)) {
if (debugMode) {
qDebug() << "[WARNING] Cannot open file.";
}
return "";
}
QTextStream in(&file);
QString fileContent = in.readAll();
return fileContent;
}
/*
* Debug
* $API.debug(message)
*
* */
Q_INVOKABLE void debug (QString message) {
// if (debugMode) {
// qDebug() << "[INFO] Printing debug message: " << message;
// }
qDebug() << message;
}
/*
* Insepct element
* $API.inspectElement()
*
* */
Q_INVOKABLE void inspectElement () {
if (debugMode) {
qDebug() << "[INFO] Activating inspect element.";
}
webView->page()->settings()->setAttribute(QWebSettings::DeveloperExtrasEnabled, true);
QWebInspector inspector;
inspector.setPage(webView->page());
inspector.setVisible(true);
}
/*
* Run bash commands
* $API.debug(command)
*
* */
Q_INVOKABLE QObject *runBash (QString command) {
if (debugMode) {
qDebug() << "[INFO] Running bash command: " << command;
}
QObject *bashOutput = new QObject();
QProcess process;
process.start(command);
// will wait forever until finished
process.waitForFinished(-1);
QString stdout = process.readAllStandardOutput();
QString stderr = process.readAllStandardError();
bashOutput->setProperty("stdout", stdout);
bashOutput->setProperty("stderr", stderr);
return bashOutput;
}
/*
* Get application arguments
* $API.argv()
*
* */
Q_INVOKABLE QStringList argv () {
if (debugMode) {
qDebug() << "[INFO] Getting application arguments.";
}
return applicationArguments;
}
/*
* Enable/Disable debug mode
* $API.setDebugMode(true/false)
*
* */
Q_INVOKABLE void setDebugMode (bool debug) {
if (debugMode) {
qDebug() << "[INFO] Setting debug mode: " << debug;
}
debugMode = debug;
}
/*
* Get debug mode
* $API.getDebugMode(true/false)
*
* */
Q_INVOKABLE bool getDebugMode () {
if (debugMode) {
qDebug() << "[INFO] Getting debug mode.";
}
return debugMode;
}
/*
* Get dirname
* $API.getDirname()
*
* */
Q_INVOKABLE QString getDirname () {
if (debugMode) {
qDebug() << "[INFO] Getting directory name.";
}
return QDir::current().absolutePath();
}
};
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
// build the web view
QWebView *view = new QWebView();
// enable local storage
QWebSettings *settings = view->settings();
settings->setAttribute(QWebSettings::LocalStorageEnabled, true);
settings->setLocalStoragePath("/tmp");
webView = view;
// get the html path
QString HTML_PATH = QString(argv[1]);
// the path is NOT a web site url
if (!HTML_PATH.startsWith("http"))
{
// if it's NOT an absolute file path
if (!HTML_PATH.startsWith("/")) {
// get the absolute path from the local machine
HTML_PATH = "file://" + QDir::current().absolutePath() + QDir::separator() + HTML_PATH;
} else {
// we have an absolute path
HTML_PATH = "file://" + HTML_PATH;
}
}
// set window width and height
int WINDOW_WIDTH = QString(argv[2]).toInt();
int WINDOW_HEIGHT = QString(argv[3]).toInt();
// handle "UNDECORATED" flag
if (QString(argv[4]) == "UNDECORATED") {
// set background transparent for webview
QPalette pal = view->palette();
pal.setBrush(QPalette::Base, Qt::transparent);
view->page()->setPalette(pal);
view->setAttribute(Qt::WA_TranslucentBackground);
view->setWindowFlags(Qt::FramelessWindowHint | view->windowFlags());
}
QStringList appArgv = applicationArguments = app.arguments();
if (appArgv.contains("--debug")) {
qDebug() << " * Debug mode.";
debugMode = true;
view->page()->settings()->setAttribute(QWebSettings::DeveloperExtrasEnabled, true);
QWebInspector inspector;
inspector.setPage(view->page());
inspector.setVisible(true);
}
if (QString(argv[5]) == "BOTTOM_MOST") {
view->setWindowFlags(Qt::WindowStaysOnBottomHint | view->windowFlags());
} else if (QString(argv[5]) == "TOP_MOST") {
view->setWindowFlags(Qt::WindowStaysOnTopHint | view->windowFlags());
}
// add the public api functions
view->page()->mainFrame()->addToJavaScriptWindowObject("$API", new JohnnysWebviewJavaScriptOperations);
// resize the window
view->resize(WINDOW_WIDTH, WINDOW_HEIGHT);
// load that HTML file or website
view->load(QUrl(HTML_PATH));
// show the web view
view->show();
// if --exit was provided
if (appArgv.contains("--exit")) {
qDebug() << "Exiting...";
QApplication::quit();
}
return app.exec();
}
#include "main.moc"
<commit_msg>Renamed JohnnysWebview object into Bat<commit_after>#include <QApplication>
#include "mainwindow.h"
#include <QtWidgets>
#include <QWebFrame>
#include <QWebInspector>
/*
* Utility:
* ./exectuable pageAddress width height decoration (BOTTOM_MOST)
*
* - pageAddress: the html file path or url
* - width: integer that represent the width of the window
* - height: integer that represent the height of the window
* - decoration: if it is "UNDECORATED" the window will be undecorated (it will not have
* borders and the window buttons
*
* */
QWebView *webView;
bool debugMode = false;
QStringList applicationArguments;
/*
* Javascript functions (Public API)
* */
class BatJavaScriptOperations : public QObject {
Q_OBJECT
public:
/*
* Close window
* $API.closeWindow();
*
**/
Q_INVOKABLE void closeWindow () {
if (debugMode) {
qDebug() << "[INFO] Closing window.";
}
webView->close();
}
/*
* Resize
* $API.resize(width, height);
*
**/
Q_INVOKABLE void resize (int width, int height) {
if (debugMode) {
qDebug() << "[INFO] Resizing window: width=" << width << "px; height=" << height << "px." ;
}
webView->resize(width, height);
}
/*
* Set window flags
* $API.setWindowFlags (type)
* - UNDECORATED
*
* */
Q_INVOKABLE void setWindowFlags (QString type) {
if (debugMode) {
qDebug() << "[INFO] Setting window flag: " << type;
}
QStringList options;
options << "UNDECORATED"
<< "BOTTOM_MOST"
<< "TOP_MOST"
<< "REMOVE_MINIMIZE"
<< "REMOVE_MAXIMIZE"
<< "REMOVE_CLOSE";
switch (options.indexOf(type)) {
case 0:
webView->setWindowFlags(Qt::FramelessWindowHint | webView->windowFlags());
webView->show();
break;
case 1:
webView->setWindowFlags(Qt::WindowStaysOnBottomHint | webView->windowFlags());
webView->show();
break;
case 2:
webView->setWindowFlags(Qt::WindowStaysOnTopHint | webView->windowFlags());
webView->show();
break;
case 3:
webView->setWindowFlags(webView->windowFlags() & ~Qt::WindowMinimizeButtonHint);
webView->show();
break;
case 4:
webView->setWindowFlags(webView->windowFlags() & ~Qt::WindowMaximizeButtonHint);
webView->show();
break;
case 5:
webView->setWindowFlags(webView->windowFlags() & ~Qt::WindowCloseButtonHint);
webView->show();
break;
// TODO Other cases
}
}
/*
* Set window state
* $API.setWindowState (value)
* - MAXIMIZED
* - MINIMIZED
* - FULLSCREEN
* - ACTIVE
* */
Q_INVOKABLE void setWindowState (QString type) {
if (debugMode) {
qDebug() << "[INFO] Setting window state: " << type;
}
QStringList options;
options << "MAXIMIZED" << "MINIMIZED" << "FULLSCREEN" << "ACTIVATE" << "RESTORED";
switch (options.indexOf(type)) {
case 0:
webView->setWindowState(Qt::WindowMaximized);
break;
case 1:
webView->setWindowState(Qt::WindowMinimized);
break;
case 2:
webView->setWindowState(Qt::WindowFullScreen);
break;
case 3:
webView->setWindowState(Qt::WindowActive);
break;
case 4:
webView->setWindowState(Qt::WindowNoState);
break;
}
}
/*
* Get window size
* $API.getWindowSize ()
* */
Q_INVOKABLE QObject *getWindowSize () {
if (debugMode) {
qDebug() << "[INFO] Getting the window size.";
}
QObject *size = new QObject();
QSize winSize = webView->size();
size->setProperty("width", winSize.width());
size->setProperty("height", winSize.height());
return size;
}
/*
* Get screen size
* $API.getScreenSize ()
*
* */
Q_INVOKABLE QObject *getScreenSize () {
if (debugMode) {
qDebug() << "[INFO] Getting screen size.";
}
QObject *size = new QObject();
QSize screenSize = qApp->primaryScreen()->size();
size->setProperty("width", screenSize.width());
size->setProperty("height", screenSize.height());
return size;
}
/*
* Set window position
* $API.setWindowPosition (left, top)
* */
Q_INVOKABLE void setWindowPosition (int left, int top) {
if (debugMode) {
qDebug() << "[INFO] Setting the window position: left=" << left << "px; top=" << top << "px.";
}
webView->move(left, top);
}
/*
* Get window position
* $API.getWindowPosition (left, top)
* */
Q_INVOKABLE QObject *getWindowPosition () {
if (debugMode) {
qDebug() << "[INFO] Getting the window position.";
}
QObject *position = new QObject();
QPoint point = webView->pos();
position->setProperty("left", point.x());
position->setProperty("top", point.y());
return position;
}
/*
* Get mouse position
* $API.getMousePosition()
*
* */
Q_INVOKABLE QObject *getMousePosition () {
if (debugMode) {
qDebug() << "[INFO] Getting the mouse position.";
}
QObject *position = new QObject();
QPoint point = QCursor::pos();
position->setProperty("left", point.x());
position->setProperty("top", point.y());
return position;
}
/*
* Set mouse position
* $API.setMousePosition()
*
* */
Q_INVOKABLE void setMousePosition (int x, int y) {
if (debugMode) {
qDebug() << "[INFO] Setting the mouse position: x=" << x << "px; y=" << y << "px.";
}
QCursor::setPos(x, y);
}
/*
* Creates a new window
* $API.newWindow(options);
* */
// TODO Is this really needed?
// Q_INVOKABLE void newWindow () {
// QWindow newWindow = new QWindow();
// newWindow.show();
// }
/*
* Sets the title of the current window
* $API.setWindowTitle(newTitle)
*
* */
Q_INVOKABLE void setWindowTitle (QString newTitle) {
if (debugMode) {
qDebug() << "[INFO] Setting the window title: " << newTitle;
}
webView->setWindowTitle(newTitle);
}
/*
* Writes content to file
* $API.writeFile (path, content);
*
* */
Q_INVOKABLE void writeFile (QString path, QString content) {
if (debugMode) {
qDebug() << "[INFO] Writting to file: " << path;
}
QFile file(path);
if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
if (debugMode) {
qDebug() << "[WARNING] Cannot write file.";
}
return;
}
QTextStream out(&file);
out << content;
}
/*
* Returns the content content of a file
* $API.readFile (path);
*
* */
Q_INVOKABLE QString readFile (QString path) {
if (debugMode) {
qDebug() << "[INFO] Reading from file: " << path;
}
QFile file(path);
if(!file.open(QIODevice::ReadOnly)) {
if (debugMode) {
qDebug() << "[WARNING] Cannot open file.";
}
return "";
}
QTextStream in(&file);
QString fileContent = in.readAll();
return fileContent;
}
/*
* Debug
* $API.debug(message)
*
* */
Q_INVOKABLE void debug (QString message) {
// if (debugMode) {
// qDebug() << "[INFO] Printing debug message: " << message;
// }
qDebug() << message;
}
/*
* Insepct element
* $API.inspectElement()
*
* */
Q_INVOKABLE void inspectElement () {
if (debugMode) {
qDebug() << "[INFO] Activating inspect element.";
}
webView->page()->settings()->setAttribute(QWebSettings::DeveloperExtrasEnabled, true);
QWebInspector inspector;
inspector.setPage(webView->page());
inspector.setVisible(true);
}
/*
* Run bash commands
* $API.debug(command)
*
* */
Q_INVOKABLE QObject *runBash (QString command) {
if (debugMode) {
qDebug() << "[INFO] Running bash command: " << command;
}
QObject *bashOutput = new QObject();
QProcess process;
process.start(command);
// will wait forever until finished
process.waitForFinished(-1);
QString stdout = process.readAllStandardOutput();
QString stderr = process.readAllStandardError();
bashOutput->setProperty("stdout", stdout);
bashOutput->setProperty("stderr", stderr);
return bashOutput;
}
/*
* Get application arguments
* $API.argv()
*
* */
Q_INVOKABLE QStringList argv () {
if (debugMode) {
qDebug() << "[INFO] Getting application arguments.";
}
return applicationArguments;
}
/*
* Enable/Disable debug mode
* $API.setDebugMode(true/false)
*
* */
Q_INVOKABLE void setDebugMode (bool debug) {
if (debugMode) {
qDebug() << "[INFO] Setting debug mode: " << debug;
}
debugMode = debug;
}
/*
* Get debug mode
* $API.getDebugMode(true/false)
*
* */
Q_INVOKABLE bool getDebugMode () {
if (debugMode) {
qDebug() << "[INFO] Getting debug mode.";
}
return debugMode;
}
/*
* Get dirname
* $API.getDirname()
*
* */
Q_INVOKABLE QString getDirname () {
if (debugMode) {
qDebug() << "[INFO] Getting directory name.";
}
return QDir::current().absolutePath();
}
};
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
// build the web view
QWebView *view = new QWebView();
// enable local storage
QWebSettings *settings = view->settings();
settings->setAttribute(QWebSettings::LocalStorageEnabled, true);
settings->setLocalStoragePath("/tmp");
webView = view;
// get the html path
QString HTML_PATH = QString(argv[1]);
// the path is NOT a web site url
if (!HTML_PATH.startsWith("http"))
{
// if it's NOT an absolute file path
if (!HTML_PATH.startsWith("/")) {
// get the absolute path from the local machine
HTML_PATH = "file://" + QDir::current().absolutePath() + QDir::separator() + HTML_PATH;
} else {
// we have an absolute path
HTML_PATH = "file://" + HTML_PATH;
}
}
// set window width and height
int WINDOW_WIDTH = QString(argv[2]).toInt();
int WINDOW_HEIGHT = QString(argv[3]).toInt();
// handle "UNDECORATED" flag
if (QString(argv[4]) == "UNDECORATED") {
// set background transparent for webview
QPalette pal = view->palette();
pal.setBrush(QPalette::Base, Qt::transparent);
view->page()->setPalette(pal);
view->setAttribute(Qt::WA_TranslucentBackground);
view->setWindowFlags(Qt::FramelessWindowHint | view->windowFlags());
}
QStringList appArgv = applicationArguments = app.arguments();
if (appArgv.contains("--debug")) {
qDebug() << " * Debug mode.";
debugMode = true;
view->page()->settings()->setAttribute(QWebSettings::DeveloperExtrasEnabled, true);
QWebInspector inspector;
inspector.setPage(view->page());
inspector.setVisible(true);
}
if (QString(argv[5]) == "BOTTOM_MOST") {
view->setWindowFlags(Qt::WindowStaysOnBottomHint | view->windowFlags());
} else if (QString(argv[5]) == "TOP_MOST") {
view->setWindowFlags(Qt::WindowStaysOnTopHint | view->windowFlags());
}
// add the public api functions
view->page()->mainFrame()->addToJavaScriptWindowObject("$API", new BatJavaScriptOperations);
// resize the window
view->resize(WINDOW_WIDTH, WINDOW_HEIGHT);
// load that HTML file or website
view->load(QUrl(HTML_PATH));
// show the web view
view->show();
// if --exit was provided
if (appArgv.contains("--exit")) {
qDebug() << "Exiting...";
QApplication::quit();
}
return app.exec();
}
#include "main.moc"
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2012, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <boost/algorithm/string/erase.hpp>
#include <boost/foreach.hpp>
#include <boost/shared_ptr.hpp>
#include <pluginlib/class_loader.hpp>
#include <image_transport/subscriber_plugin.h>
#include "rviz/validate_floats.h"
#include "rviz/image/image_display_base.h"
namespace rviz
{
ImageDisplayBase::ImageDisplayBase() :
Display()
, sub_()
, tf_filter_()
, messages_received_(0)
{
topic_property_ = new RosTopicProperty("Image Topic", "",
QString::fromStdString(ros::message_traits::datatype<sensor_msgs::Image>()),
"sensor_msgs::Image topic to subscribe to.", this, SLOT( updateTopic() ));
transport_property_ = new EnumProperty("Transport Hint", "raw", "Preferred method of sending images.", this,
SLOT( updateTopic() ));
connect(transport_property_, SIGNAL( requestOptions( EnumProperty* )), this,
SLOT( fillTransportOptionList( EnumProperty* )));
queue_size_property_ = new IntProperty( "Queue Size", 2,
"Advanced: set the size of the incoming message queue. Increasing this "
"is useful if your incoming TF data is delayed significantly from your"
" image data, but it can greatly increase memory usage if the messages are big.",
this, SLOT( updateQueueSize() ));
queue_size_property_->setMin( 1 );
transport_property_->setStdString("raw");
unreliable_property_ = new BoolProperty( "Unreliable", false,
"Prefer UDP topic transport",
this,
SLOT( updateTopic() ));
}
ImageDisplayBase::~ImageDisplayBase()
{
unsubscribe();
}
void ImageDisplayBase::onInitialize()
{
it_.reset( new image_transport::ImageTransport( update_nh_ ));
scanForTransportSubscriberPlugins();
}
void ImageDisplayBase::setTopic( const QString &topic, const QString &datatype )
{
if ( datatype == ros::message_traits::datatype<sensor_msgs::Image>() )
{
transport_property_->setStdString( "raw" );
topic_property_->setString( topic );
}
else
{
int index = topic.lastIndexOf("/");
if ( index == -1 )
{
ROS_WARN("ImageDisplayBase::setTopic() Invalid topic name: %s",
topic.toStdString().c_str());
return;
}
QString transport = topic.mid(index + 1);
QString base_topic = topic.mid(0, index);
transport_property_->setString( transport );
topic_property_->setString( base_topic );
}
}
void ImageDisplayBase::incomingMessage(const sensor_msgs::Image::ConstPtr& msg)
{
if (!msg || context_->getFrameManager()->getPause() )
{
return;
}
++messages_received_;
setStatus(StatusProperty::Ok, "Image", QString::number(messages_received_) + " images received");
emitTimeSignal( msg->header.stamp );
processMessage(msg);
}
void ImageDisplayBase::reset()
{
Display::reset();
if (tf_filter_)
tf_filter_->clear();
messages_received_ = 0;
setStatus(StatusProperty::Warn, "Image", "No Image received");
}
void ImageDisplayBase::updateQueueSize()
{
uint32_t size = queue_size_property_->getInt();
if (tf_filter_)
tf_filter_->setQueueSize(size);
}
void ImageDisplayBase::subscribe()
{
if (!isEnabled())
{
return;
}
try
{
tf_filter_.reset();
sub_.reset(new image_transport::SubscriberFilter());
if (!topic_property_->getTopicStd().empty() && !transport_property_->getStdString().empty() )
{
// Determine UDP vs TCP transport for user selection.
if (unreliable_property_->getBool())
{
sub_->subscribe(*it_, topic_property_->getTopicStd(), (uint32_t)queue_size_property_->getInt(),
image_transport::TransportHints(transport_property_->getStdString(), ros::TransportHints().unreliable()));
}
else{
sub_->subscribe(*it_, topic_property_->getTopicStd(), (uint32_t)queue_size_property_->getInt(),
image_transport::TransportHints(transport_property_->getStdString()));
}
if (targetFrame_.empty())
{
sub_->registerCallback(boost::bind(&ImageDisplayBase::incomingMessage, this, _1));
}
else
{
tf_filter_.reset(new tf2_ros::MessageFilter<sensor_msgs::Image>(
*sub_,
*context_->getTF2BufferPtr(),
targetFrame_,
queue_size_property_->getInt(),
update_nh_
));
tf_filter_->registerCallback(boost::bind(&ImageDisplayBase::incomingMessage, this, _1));
// TODO: also register failureCallback to report about frame-resolving issues (now: "no images received")
}
}
setStatus(StatusProperty::Ok, "Topic", "OK");
}
catch (ros::Exception& e)
{
setStatus(StatusProperty::Error, "Topic", QString("Error subscribing: ") + e.what());
}
catch (image_transport::Exception& e)
{
setStatus( StatusProperty::Error, "Topic", QString("Error subscribing: ") + e.what());
}
}
void ImageDisplayBase::unsubscribe()
{
// Quick fix for #1372. Can be removed if https://github.com/ros/geometry2/pull/402 is released
if (tf_filter_)
update_nh_.getCallbackQueue()->removeByID((uint64_t)tf_filter_.get());
tf_filter_.reset();
sub_.reset();
}
void ImageDisplayBase::fixedFrameChanged()
{
if (tf_filter_)
{
tf_filter_->setTargetFrame(fixed_frame_.toStdString());
reset();
}
}
void ImageDisplayBase::scanForTransportSubscriberPlugins()
{
pluginlib::ClassLoader<image_transport::SubscriberPlugin> sub_loader("image_transport",
"image_transport::SubscriberPlugin");
BOOST_FOREACH( const std::string& lookup_name, sub_loader.getDeclaredClasses() )
{
// lookup_name is formatted as "pkg/transport_sub", for instance
// "image_transport/compressed_sub" for the "compressed"
// transport. This code removes the "_sub" from the tail and
// everything up to and including the "/" from the head, leaving
// "compressed" (for example) in transport_name.
std::string transport_name = boost::erase_last_copy(lookup_name, "_sub");
transport_name = transport_name.substr(lookup_name.find('/') + 1);
// If the plugin loads without throwing an exception, add its
// transport name to the list of valid plugins, otherwise ignore
// it.
try
{
boost::shared_ptr<image_transport::SubscriberPlugin> sub = sub_loader.createInstance(lookup_name);
transport_plugin_types_.insert(transport_name);
}
catch (const pluginlib::LibraryLoadException& e)
{
}
catch (const pluginlib::CreateClassException& e)
{
}
}
}
void ImageDisplayBase::updateTopic()
{
unsubscribe();
reset();
subscribe();
context_->queueRender();
}
void ImageDisplayBase::fillTransportOptionList(EnumProperty* property)
{
property->clearOptions();
std::vector<std::string> choices;
choices.push_back("raw");
// Loop over all current ROS topic names
ros::master::V_TopicInfo topics;
ros::master::getTopics(topics);
ros::master::V_TopicInfo::iterator it = topics.begin();
ros::master::V_TopicInfo::iterator end = topics.end();
for (; it != end; ++it)
{
// If the beginning of this topic name is the same as topic_,
// and the whole string is not the same,
// and the next character is /
// and there are no further slashes from there to the end,
// then consider this a possible transport topic.
const ros::master::TopicInfo& ti = *it;
const std::string& topic_name = ti.name;
const std::string& topic = topic_property_->getStdString();
if (topic_name.find(topic) == 0 && topic_name != topic && topic_name[topic.size()] == '/'
&& topic_name.find('/', topic.size() + 1) == std::string::npos)
{
std::string transport_type = topic_name.substr(topic.size() + 1);
// If the transport type string found above is in the set of
// supported transport type plugins, add it to the list.
if (transport_plugin_types_.find(transport_type) != transport_plugin_types_.end())
{
choices.push_back(transport_type);
}
}
}
for (size_t i = 0; i < choices.size(); i++)
{
property->addOptionStd(choices[i]);
}
}
} // end namespace rviz
<commit_msg>fixup! QuickFix #1372: remove pending callbacks<commit_after>/*
* Copyright (c) 2012, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <boost/algorithm/string/erase.hpp>
#include <boost/foreach.hpp>
#include <boost/shared_ptr.hpp>
#include <pluginlib/class_loader.hpp>
#include <image_transport/subscriber_plugin.h>
#include "rviz/validate_floats.h"
#include "rviz/image/image_display_base.h"
namespace rviz
{
ImageDisplayBase::ImageDisplayBase() :
Display()
, sub_()
, tf_filter_()
, messages_received_(0)
{
topic_property_ = new RosTopicProperty("Image Topic", "",
QString::fromStdString(ros::message_traits::datatype<sensor_msgs::Image>()),
"sensor_msgs::Image topic to subscribe to.", this, SLOT( updateTopic() ));
transport_property_ = new EnumProperty("Transport Hint", "raw", "Preferred method of sending images.", this,
SLOT( updateTopic() ));
connect(transport_property_, SIGNAL( requestOptions( EnumProperty* )), this,
SLOT( fillTransportOptionList( EnumProperty* )));
queue_size_property_ = new IntProperty( "Queue Size", 2,
"Advanced: set the size of the incoming message queue. Increasing this "
"is useful if your incoming TF data is delayed significantly from your"
" image data, but it can greatly increase memory usage if the messages are big.",
this, SLOT( updateQueueSize() ));
queue_size_property_->setMin( 1 );
transport_property_->setStdString("raw");
unreliable_property_ = new BoolProperty( "Unreliable", false,
"Prefer UDP topic transport",
this,
SLOT( updateTopic() ));
}
ImageDisplayBase::~ImageDisplayBase()
{
unsubscribe();
}
void ImageDisplayBase::onInitialize()
{
it_.reset( new image_transport::ImageTransport( update_nh_ ));
scanForTransportSubscriberPlugins();
}
void ImageDisplayBase::setTopic( const QString &topic, const QString &datatype )
{
if ( datatype == ros::message_traits::datatype<sensor_msgs::Image>() )
{
transport_property_->setStdString( "raw" );
topic_property_->setString( topic );
}
else
{
int index = topic.lastIndexOf("/");
if ( index == -1 )
{
ROS_WARN("ImageDisplayBase::setTopic() Invalid topic name: %s",
topic.toStdString().c_str());
return;
}
QString transport = topic.mid(index + 1);
QString base_topic = topic.mid(0, index);
transport_property_->setString( transport );
topic_property_->setString( base_topic );
}
}
void ImageDisplayBase::incomingMessage(const sensor_msgs::Image::ConstPtr& msg)
{
if (!msg || context_->getFrameManager()->getPause() )
{
return;
}
++messages_received_;
setStatus(StatusProperty::Ok, "Image", QString::number(messages_received_) + " images received");
emitTimeSignal( msg->header.stamp );
processMessage(msg);
}
void ImageDisplayBase::reset()
{
Display::reset();
if (tf_filter_)
{
tf_filter_->clear();
update_nh_.getCallbackQueue()->removeByID((uint64_t)tf_filter_.get());
}
messages_received_ = 0;
setStatus(StatusProperty::Warn, "Image", "No Image received");
}
void ImageDisplayBase::updateQueueSize()
{
uint32_t size = queue_size_property_->getInt();
if (tf_filter_)
tf_filter_->setQueueSize(size);
}
void ImageDisplayBase::subscribe()
{
if (!isEnabled())
{
return;
}
try
{
tf_filter_.reset();
sub_.reset(new image_transport::SubscriberFilter());
if (!topic_property_->getTopicStd().empty() && !transport_property_->getStdString().empty() )
{
// Determine UDP vs TCP transport for user selection.
if (unreliable_property_->getBool())
{
sub_->subscribe(*it_, topic_property_->getTopicStd(), (uint32_t)queue_size_property_->getInt(),
image_transport::TransportHints(transport_property_->getStdString(), ros::TransportHints().unreliable()));
}
else{
sub_->subscribe(*it_, topic_property_->getTopicStd(), (uint32_t)queue_size_property_->getInt(),
image_transport::TransportHints(transport_property_->getStdString()));
}
if (targetFrame_.empty())
{
sub_->registerCallback(boost::bind(&ImageDisplayBase::incomingMessage, this, _1));
}
else
{
tf_filter_.reset(new tf2_ros::MessageFilter<sensor_msgs::Image>(
*sub_,
*context_->getTF2BufferPtr(),
targetFrame_,
queue_size_property_->getInt(),
update_nh_
));
tf_filter_->registerCallback(boost::bind(&ImageDisplayBase::incomingMessage, this, _1));
// TODO: also register failureCallback to report about frame-resolving issues (now: "no images received")
}
}
setStatus(StatusProperty::Ok, "Topic", "OK");
}
catch (ros::Exception& e)
{
setStatus(StatusProperty::Error, "Topic", QString("Error subscribing: ") + e.what());
}
catch (image_transport::Exception& e)
{
setStatus( StatusProperty::Error, "Topic", QString("Error subscribing: ") + e.what());
}
}
void ImageDisplayBase::unsubscribe()
{
// Quick fix for #1372. Can be removed if https://github.com/ros/geometry2/pull/402 is released
if (tf_filter_)
update_nh_.getCallbackQueue()->removeByID((uint64_t)tf_filter_.get());
tf_filter_.reset();
sub_.reset();
}
void ImageDisplayBase::fixedFrameChanged()
{
if (tf_filter_)
{
tf_filter_->setTargetFrame(fixed_frame_.toStdString());
reset();
}
}
void ImageDisplayBase::scanForTransportSubscriberPlugins()
{
pluginlib::ClassLoader<image_transport::SubscriberPlugin> sub_loader("image_transport",
"image_transport::SubscriberPlugin");
BOOST_FOREACH( const std::string& lookup_name, sub_loader.getDeclaredClasses() )
{
// lookup_name is formatted as "pkg/transport_sub", for instance
// "image_transport/compressed_sub" for the "compressed"
// transport. This code removes the "_sub" from the tail and
// everything up to and including the "/" from the head, leaving
// "compressed" (for example) in transport_name.
std::string transport_name = boost::erase_last_copy(lookup_name, "_sub");
transport_name = transport_name.substr(lookup_name.find('/') + 1);
// If the plugin loads without throwing an exception, add its
// transport name to the list of valid plugins, otherwise ignore
// it.
try
{
boost::shared_ptr<image_transport::SubscriberPlugin> sub = sub_loader.createInstance(lookup_name);
transport_plugin_types_.insert(transport_name);
}
catch (const pluginlib::LibraryLoadException& e)
{
}
catch (const pluginlib::CreateClassException& e)
{
}
}
}
void ImageDisplayBase::updateTopic()
{
unsubscribe();
reset();
subscribe();
context_->queueRender();
}
void ImageDisplayBase::fillTransportOptionList(EnumProperty* property)
{
property->clearOptions();
std::vector<std::string> choices;
choices.push_back("raw");
// Loop over all current ROS topic names
ros::master::V_TopicInfo topics;
ros::master::getTopics(topics);
ros::master::V_TopicInfo::iterator it = topics.begin();
ros::master::V_TopicInfo::iterator end = topics.end();
for (; it != end; ++it)
{
// If the beginning of this topic name is the same as topic_,
// and the whole string is not the same,
// and the next character is /
// and there are no further slashes from there to the end,
// then consider this a possible transport topic.
const ros::master::TopicInfo& ti = *it;
const std::string& topic_name = ti.name;
const std::string& topic = topic_property_->getStdString();
if (topic_name.find(topic) == 0 && topic_name != topic && topic_name[topic.size()] == '/'
&& topic_name.find('/', topic.size() + 1) == std::string::npos)
{
std::string transport_type = topic_name.substr(topic.size() + 1);
// If the transport type string found above is in the set of
// supported transport type plugins, add it to the list.
if (transport_plugin_types_.find(transport_type) != transport_plugin_types_.end())
{
choices.push_back(transport_type);
}
}
}
for (size_t i = 0; i < choices.size(); i++)
{
property->addOptionStd(choices[i]);
}
}
} // end namespace rviz
<|endoftext|>
|
<commit_before>#include "disassembler.h"
#include "util.h"
#include "symtab.h"
using namespace std;
enum ByteTypeGuess {
UNINITIALIZED,
UNKNOWN,
CHAR_DATA,
UNINITIALIZED_CHAR_DATA,
WORD_DATA,
UNINITIALIZED_WORD_DATA,
CODE,
};
struct program {
ByteTypeGuess byte_type_guess[65536];
char memory[65536];
bool is_labelled[65536];
string name;
string starting_address;
int length_of_program;
string first_executable_instruction;
program() {
for ( int i = 0 ; i < 65536 ; i++ ) {
byte_type_guess[i] = UNINITIALIZED;
memory[i] = 0;
is_labelled[i] = false;
}
name = "";
starting_address = "";
length_of_program = 0;
first_executable_instruction = "";
}
};
bool read_record(ifstream &ifile, string &record);
void record_to_memory(const string record, program &p);
void analyze_code_data(program &p);
void write_assembly(const program &p, ofstream &ofile);
bool disassemble(ifstream &ifile, ofstream &ofile) {
string record;
program p;
while ( read_record(ifile, record) ) {
record_to_memory(record, p);
}
status("Done reading records");
analyze_code_data(p);
status("Done analyzing program for code and data");
write_assembly(p, ofile);
status("Done writing output file");
}
string read_hex_columns(ifstream &ifile, int col_begin, int col_end, char record_type = 'a') { // inclusive of both
string ret;
char t;
for ( int col = col_begin ; col <= col_end ; col++ ) {
t = ifile.get();
if ( t == EOF ) {
fatal("Unexpected end of " + record_type + string(" record"));
} else if ( !is_hex_digit(t) ) {
fatal("Unexpected character " + t + string(" in ") + record_type + string(" record"));
}
ret += t;
}
return ret;
}
bool read_record(ifstream &ifile, string &record) {
int temp_int;
string temp_str;
char t;
do {
t = ifile.get();
if ( t == EOF ) {
return false;
}
} while ( t == '\n' || t == ' ' );
record = "";
record += t;
switch (t) {
case 'H': // Header
record += read_hex_columns(ifile,2,19,'H');
break;
case 'T': // Text
record += read_hex_columns(ifile,2,7,'T');
temp_str = read_hex_columns(ifile,8,9,'T');
temp_int = hex2int(temp_str);
record += temp_str;
record += read_hex_columns(ifile,10,9+2*temp_int,'T');
break;
case 'E': // End
record += read_hex_columns(ifile,2,7,'E');
break;
default:
fatal("Unknown record type " + t);
}
return true;
}
void record_to_memory(const string record, program &p) {
const char * c_record = record.c_str();
switch (*c_record) {
case 'H': // Header
if ( p.name.length() != 0 ) {
fatal("Multiple H records");
}
p.name = record.substr(1,6);
p.starting_address = record.substr(7,6);
p.length_of_program = hex2int(record.substr(13,6));
break;
case 'T': // Text
{
int text_start = hex2int(record.substr(1,6));
int bit_length = hex2int(record.substr(7,2));
for ( int i = 0 ; i < bit_length ; i++ ) {
p.memory[i+text_start] = hex2int(record.substr(9+2*i,2));
p.byte_type_guess[i+text_start] = UNKNOWN;
}
}
break;
case 'E': // End
if ( p.first_executable_instruction.length() != 0 ) {
fatal("Multiple E records");
}
p.first_executable_instruction = record.substr(1,6);
break;
default:
fatal("Unknown record type " + *c_record);
}
}
void mark_code_data(program &p, int location, ByteTypeGuess btg) {
if ( location >= hex2int(p.starting_address) + p.length_of_program ) {
return;
}
switch (btg) {
case UNINITIALIZED:
case UNKNOWN:
break;
case CHAR_DATA:
case UNINITIALIZED_CHAR_DATA:
{
if ( p.byte_type_guess[location] == UNINITIALIZED )
btg = UNINITIALIZED_CHAR_DATA;
p.byte_type_guess[location] = btg;
break;
}
case WORD_DATA:
case UNINITIALIZED_WORD_DATA:
{
if ( p.byte_type_guess[location] == UNINITIALIZED )
btg = UNINITIALIZED_WORD_DATA;
p.byte_type_guess[location+0] = btg;
p.byte_type_guess[location+1] = btg;
p.byte_type_guess[location+2] = btg;
break;
}
case CODE:
{
if ( p.byte_type_guess[location] == UNINITIALIZED ) {
fatal("Attempting to use uninitialized section as code");
}
if ( p.byte_type_guess[location] == CODE ) {
break;
}
p.byte_type_guess[location+0] = btg;
p.byte_type_guess[location+1] = btg;
p.byte_type_guess[location+2] = btg;
string opcode_val = byte2hex(p.memory[location]);
string opcode;
string operand = byte2hex(p.memory[location+1])+byte2hex(p.memory[location+2]);
operand = int2hex(hex2int(operand)&0x7FFF); // remove index flag
if ( ! find_from_symtab(opcode,opcode_val) ) {
fatal("Unknown opcode " + opcode_val + " at location " + int2hex(location));
}
if ( opcode == "ADD" ||
opcode == "AND" ||
opcode == "COMP" ||
opcode == "DIV" ||
opcode == "LDA" ||
opcode == "LDL" ||
opcode == "LDX" ||
opcode == "MUL" ||
opcode == "OR" ||
opcode == "STA" ||
opcode == "STL" ||
opcode == "STX" ||
opcode == "SUB" ||
opcode == "TIX" ) {
give_label(operand);
p.is_labelled[hex2int(operand)] = true;
mark_code_data(p,hex2int(operand),WORD_DATA);
}
if ( opcode == "LDCH" ||
opcode == "STCH" ) {
give_label(operand);
p.is_labelled[hex2int(operand)] = true;
mark_code_data(p,hex2int(operand),CHAR_DATA);
}
if ( opcode == "J" ||
opcode == "JEQ" ||
opcode == "JGT" ||
opcode == "JLT" ||
opcode == "JSUB" ||
opcode == "RSUB" ) {
give_label(operand);
p.is_labelled[hex2int(operand)] = true;
mark_code_data(p,hex2int(operand),CODE);
}
if ( opcode != "J" &&
opcode != "RSUB" ) {
mark_code_data(p,location+3,btg);
}
break;
}
}
}
void analyze_code_data(program &p) {
if ( p.name.length() == 0 ) {
fatal("No Header record");
}
if ( p.first_executable_instruction.length() == 0 ) {
fatal("No End record");
}
initialize_symtab();
add_to_symtab("FIRST",p.first_executable_instruction);
p.is_labelled[hex2int(p.first_executable_instruction)] = true;
mark_code_data(p,hex2int(p.first_executable_instruction),CODE);
}
string asm_to_line(string label, string opcode, string operand, bool is_indexed) {
const int labellength = 8;
const int opcodelength = 6;
string ret = "";
ret += label + string(labellength-label.length(),' ');
ret += opcode + string(opcodelength-opcode.length(),' ');
ret += operand;
if ( is_indexed ) {
ret += ",X";
}
ret += '\n';
return ret;
}
void write_assembly(const program &p, ofstream &ofile) {
// TODO
}<commit_msg>Add START and END lines to assembly code<commit_after>#include "disassembler.h"
#include "util.h"
#include "symtab.h"
using namespace std;
enum ByteTypeGuess {
UNINITIALIZED,
UNKNOWN,
CHAR_DATA,
UNINITIALIZED_CHAR_DATA,
WORD_DATA,
UNINITIALIZED_WORD_DATA,
CODE,
};
struct program {
ByteTypeGuess byte_type_guess[65536];
char memory[65536];
bool is_labelled[65536];
string name;
string starting_address;
int length_of_program;
string first_executable_instruction;
program() {
for ( int i = 0 ; i < 65536 ; i++ ) {
byte_type_guess[i] = UNINITIALIZED;
memory[i] = 0;
is_labelled[i] = false;
}
name = "";
starting_address = "";
length_of_program = 0;
first_executable_instruction = "";
}
};
bool read_record(ifstream &ifile, string &record);
void record_to_memory(const string record, program &p);
void analyze_code_data(program &p);
void write_assembly(const program &p, ofstream &ofile);
bool disassemble(ifstream &ifile, ofstream &ofile) {
string record;
program p;
while ( read_record(ifile, record) ) {
record_to_memory(record, p);
}
status("Done reading records");
analyze_code_data(p);
status("Done analyzing program for code and data");
write_assembly(p, ofile);
status("Done writing output file");
}
string read_hex_columns(ifstream &ifile, int col_begin, int col_end, char record_type = 'a') { // inclusive of both
string ret;
char t;
for ( int col = col_begin ; col <= col_end ; col++ ) {
t = ifile.get();
if ( t == EOF ) {
fatal("Unexpected end of " + record_type + string(" record"));
} else if ( !is_hex_digit(t) ) {
fatal("Unexpected character " + t + string(" in ") + record_type + string(" record"));
}
ret += t;
}
return ret;
}
bool read_record(ifstream &ifile, string &record) {
int temp_int;
string temp_str;
char t;
do {
t = ifile.get();
if ( t == EOF ) {
return false;
}
} while ( t == '\n' || t == ' ' );
record = "";
record += t;
switch (t) {
case 'H': // Header
record += read_hex_columns(ifile,2,19,'H');
break;
case 'T': // Text
record += read_hex_columns(ifile,2,7,'T');
temp_str = read_hex_columns(ifile,8,9,'T');
temp_int = hex2int(temp_str);
record += temp_str;
record += read_hex_columns(ifile,10,9+2*temp_int,'T');
break;
case 'E': // End
record += read_hex_columns(ifile,2,7,'E');
break;
default:
fatal("Unknown record type " + t);
}
return true;
}
void record_to_memory(const string record, program &p) {
const char * c_record = record.c_str();
switch (*c_record) {
case 'H': // Header
if ( p.name.length() != 0 ) {
fatal("Multiple H records");
}
p.name = record.substr(1,6);
p.starting_address = record.substr(7,6);
p.length_of_program = hex2int(record.substr(13,6));
break;
case 'T': // Text
{
int text_start = hex2int(record.substr(1,6));
int bit_length = hex2int(record.substr(7,2));
for ( int i = 0 ; i < bit_length ; i++ ) {
p.memory[i+text_start] = hex2int(record.substr(9+2*i,2));
p.byte_type_guess[i+text_start] = UNKNOWN;
}
}
break;
case 'E': // End
if ( p.first_executable_instruction.length() != 0 ) {
fatal("Multiple E records");
}
p.first_executable_instruction = record.substr(1,6);
break;
default:
fatal("Unknown record type " + *c_record);
}
}
void mark_code_data(program &p, int location, ByteTypeGuess btg) {
if ( location >= hex2int(p.starting_address) + p.length_of_program ) {
return;
}
switch (btg) {
case UNINITIALIZED:
case UNKNOWN:
break;
case CHAR_DATA:
case UNINITIALIZED_CHAR_DATA:
{
if ( p.byte_type_guess[location] == UNINITIALIZED )
btg = UNINITIALIZED_CHAR_DATA;
p.byte_type_guess[location] = btg;
break;
}
case WORD_DATA:
case UNINITIALIZED_WORD_DATA:
{
if ( p.byte_type_guess[location] == UNINITIALIZED )
btg = UNINITIALIZED_WORD_DATA;
p.byte_type_guess[location+0] = btg;
p.byte_type_guess[location+1] = btg;
p.byte_type_guess[location+2] = btg;
break;
}
case CODE:
{
if ( p.byte_type_guess[location] == UNINITIALIZED ) {
fatal("Attempting to use uninitialized section as code");
}
if ( p.byte_type_guess[location] == CODE ) {
break;
}
p.byte_type_guess[location+0] = btg;
p.byte_type_guess[location+1] = btg;
p.byte_type_guess[location+2] = btg;
string opcode_val = byte2hex(p.memory[location]);
string opcode;
string operand = byte2hex(p.memory[location+1])+byte2hex(p.memory[location+2]);
operand = int2hex(hex2int(operand)&0x7FFF); // remove index flag
if ( ! find_from_symtab(opcode,opcode_val) ) {
fatal("Unknown opcode " + opcode_val + " at location " + int2hex(location));
}
if ( opcode == "ADD" ||
opcode == "AND" ||
opcode == "COMP" ||
opcode == "DIV" ||
opcode == "LDA" ||
opcode == "LDL" ||
opcode == "LDX" ||
opcode == "MUL" ||
opcode == "OR" ||
opcode == "STA" ||
opcode == "STL" ||
opcode == "STX" ||
opcode == "SUB" ||
opcode == "TIX" ) {
give_label(operand);
p.is_labelled[hex2int(operand)] = true;
mark_code_data(p,hex2int(operand),WORD_DATA);
}
if ( opcode == "LDCH" ||
opcode == "STCH" ) {
give_label(operand);
p.is_labelled[hex2int(operand)] = true;
mark_code_data(p,hex2int(operand),CHAR_DATA);
}
if ( opcode == "J" ||
opcode == "JEQ" ||
opcode == "JGT" ||
opcode == "JLT" ||
opcode == "JSUB" ||
opcode == "RSUB" ) {
give_label(operand);
p.is_labelled[hex2int(operand)] = true;
mark_code_data(p,hex2int(operand),CODE);
}
if ( opcode != "J" &&
opcode != "RSUB" ) {
mark_code_data(p,location+3,btg);
}
break;
}
}
}
void analyze_code_data(program &p) {
if ( p.name.length() == 0 ) {
fatal("No Header record");
}
if ( p.first_executable_instruction.length() == 0 ) {
fatal("No End record");
}
initialize_symtab();
add_to_symtab("FIRST",p.first_executable_instruction);
p.is_labelled[hex2int(p.first_executable_instruction)] = true;
mark_code_data(p,hex2int(p.first_executable_instruction),CODE);
}
string asm_to_line(string label, string opcode, string operand, bool is_indexed) {
const int labellength = 8;
const int opcodelength = 6;
string ret = "";
ret += label + string(labellength-label.length(),' ');
ret += opcode + string(opcodelength-opcode.length(),' ');
ret += operand;
if ( is_indexed ) {
ret += ",X";
}
ret += '\n';
return ret;
}
void write_assembly(const program &p, ofstream &ofile) {
ofile << asm_to_line(p.name,"START",p.starting_address,false);
int start_of_program = hex2int(p.starting_address);
int end_of_program = start_of_program + p.length_of_program;
for ( int locctr = start_of_program ; locctr < end_of_program ; locctr++ ) {
// TODO
}
ofile << asm_to_line("","END","FIRST",false);
}<|endoftext|>
|
<commit_before>#include <gobject-introspection-1.0/girepository.h>
#include <node.h>
#include <nan.h>
#include "async_call_environment.h"
#include "boxed.h"
#include "debug.h"
#include "function.h"
#include "gi.h"
#include "gobject.h"
#include "loop.h"
#include "macros.h"
#include "type.h"
#include "util.h"
#include "value.h"
#include "modules/system.h"
#include "modules/cairo/cairo.h"
using namespace v8;
using GNodeJS::BaseInfo;
namespace GNodeJS {
G_DEFINE_QUARK(gnode_js_object, object);
G_DEFINE_QUARK(gnode_js_template, template);
G_DEFINE_QUARK(gnode_js_constructor, constructor);
G_DEFINE_QUARK(gnode_js_function, function);
Nan::Persistent<Object> moduleCache(Nan::New<Object>());
Local<Object> GetModuleCache() {
return Nan::New<Object>(GNodeJS::moduleCache);
}
}
static void DefineFunction(Isolate *isolate, Local<Object> module_obj, GIBaseInfo *info) {
const char *function_name = g_base_info_get_name ((GIBaseInfo *) info);
Local<Function> fn = GNodeJS::MakeFunction (info);
Nan::Set(module_obj, UTF8(function_name), fn);
}
static void DefineFunction(Isolate *isolate, Local<Object> module_obj, GIBaseInfo *info, const char *base_name) {
Local<Function> fn = GNodeJS::MakeFunction (info);
char *function_name = g_strdup_printf ("%s_%s", base_name, g_base_info_get_name(info));
Nan::Set(module_obj, UTF8(function_name), fn);
g_free (function_name);
}
static void DefineObjectFunctions(Isolate *isolate, Local<Object> module_obj, GIBaseInfo *info) {
const char *object_name = g_base_info_get_name ((GIBaseInfo *) info);
int n_methods = g_object_info_get_n_methods (info);
for (int i = 0; i < n_methods; i++) {
GIFunctionInfo *meth_info = g_object_info_get_method (info, i);
DefineFunction (isolate, module_obj, meth_info, object_name);
g_base_info_unref ((GIBaseInfo *) meth_info);
}
}
static void DefineBoxedFunctions(Isolate *isolate, Local<Object> module_obj, GIBaseInfo *info) {
const char *object_name = g_base_info_get_name ((GIBaseInfo *) info);
int n_methods = g_struct_info_get_n_methods (info);
for (int i = 0; i < n_methods; i++) {
GIFunctionInfo *meth_info = g_struct_info_get_method (info, i);
DefineFunction (isolate, module_obj, meth_info, object_name);
g_base_info_unref ((GIBaseInfo *) meth_info);
}
}
static void DefineBootstrapInfo(Isolate *isolate, Local<Object> module_obj, GIBaseInfo *info) {
GIInfoType type = g_base_info_get_type (info);
switch (type) {
case GI_INFO_TYPE_FUNCTION:
DefineFunction (isolate, module_obj, info);
break;
case GI_INFO_TYPE_OBJECT:
DefineObjectFunctions (isolate, module_obj, info);
break;
case GI_INFO_TYPE_BOXED:
case GI_INFO_TYPE_STRUCT:
DefineBoxedFunctions (isolate, module_obj, info);
break;
default:
break;
}
}
NAN_METHOD(Bootstrap) {
Isolate *isolate = info.GetIsolate();
GIRepository *repo = g_irepository_get_default ();
GError *error = NULL;
const char *ns = "GIRepository";
g_irepository_require (repo, ns, NULL, (GIRepositoryLoadFlags) 0, &error);
if (error) {
Nan::ThrowError( error->message );
return;
}
Local<Object> module_obj = Object::New (isolate);
int n = g_irepository_get_n_infos (repo, ns);
for (int i = 0; i < n; i++) {
BaseInfo baseInfo(g_irepository_get_info(repo, ns, i));
DefineBootstrapInfo(isolate, module_obj, baseInfo.info());
}
info.GetReturnValue().Set(module_obj);
}
NAN_METHOD(GetConstantValue) {
GIBaseInfo *gi_info = (GIBaseInfo *) GNodeJS::PointerFromWrapper (info[0]);
GITypeInfo *type = g_constant_info_get_type ((GIConstantInfo *) gi_info);
if (type == NULL) {
info.GetReturnValue().SetNull();
return;
}
GIArgument gi_arg;
gint size = g_constant_info_get_value((GIConstantInfo *) gi_info, &gi_arg);
// Catches an invalid case for Granite.options
if (size != 0)
info.GetReturnValue().Set(GNodeJS::GIArgumentToV8 (type, &gi_arg));
else
WARN("Couldn't load %s.%s: invalid constant size: %i",
g_base_info_get_namespace (gi_info),
g_base_info_get_name (gi_info),
size);
g_constant_info_free_value(gi_info, &gi_arg);
g_base_info_unref(type);
}
NAN_METHOD(MakeFunction) {
BaseInfo gi_info(info[0]);
Local<Function> fn = GNodeJS::MakeFunction(*gi_info);
info.GetReturnValue().Set(fn);
}
NAN_METHOD(MakeVirtualFunction) {
if (info.Length() < 2 || !info[0]->IsObject() || !info[1]->IsNumber()) {
Nan::ThrowTypeError("Incorrect arguments. Expecting (GIBaseInfo, GType)");
return;
}
BaseInfo gi_info(info[0]);
GType implementor = (gulong) Nan::To<int64_t> (info[1]).ToChecked();
MaybeLocal<Function> maybeFn = GNodeJS::MakeVirtualFunction(*gi_info, implementor);
if (maybeFn.IsEmpty())
return;
info.GetReturnValue().Set(maybeFn.ToLocalChecked());
}
NAN_METHOD(MakeObjectClass) {
BaseInfo gi_info(info[0]);
auto klass = GNodeJS::MakeClass(*gi_info);
if (!klass.IsEmpty())
info.GetReturnValue().Set(klass.ToLocalChecked());
}
NAN_METHOD(MakeBoxedClass) {
BaseInfo gi_info(info[0]);
info.GetReturnValue().Set(GNodeJS::MakeBoxedClass(*gi_info));
}
NAN_METHOD(ObjectPropertyGetter) {
GObject *gobject = GNodeJS::GObjectFromWrapper (info[0]);
g_assert(gobject != NULL);
Nan::Utf8String prop_name_v (TO_STRING (info[1]));
const char *prop_name = *prop_name_v;
RETURN(GNodeJS::GetGObjectProperty(gobject, prop_name));
}
NAN_METHOD(ObjectPropertySetter) {
GObject* gobject = GNodeJS::GObjectFromWrapper(info[0]);
Nan::Utf8String prop_name_v (TO_STRING (info[1]));
const char *prop_name = *prop_name_v;
if (gobject == NULL) {
WARN("ObjectPropertySetter: null GObject; cant get %s", prop_name);
RETURN(Nan::False());
}
RETURN(GNodeJS::SetGObjectProperty(gobject, prop_name, info[2]));
}
NAN_METHOD(StructFieldSetter) {
Local<Object> boxedWrapper = info[0].As<Object>();
Local<Object> fieldInfo = info[1].As<Object>();
Local<Value> value = info[2];
void *boxed = GNodeJS::PointerFromWrapper(boxedWrapper);
GIFieldInfo *field = (GIFieldInfo *) GNodeJS::PointerFromWrapper(fieldInfo);
GITypeInfo *field_type = g_field_info_get_type(field);
g_assert(boxed);
g_assert(field);
g_assert(field_type);
GIArgument arg;
if (!GNodeJS::V8ToGIArgument(field_type, &arg, value, true)) {
char *message = g_strdup_printf("Couldn't convert value for field '%s'",
g_base_info_get_name(field));
Nan::ThrowTypeError (message);
g_free(message);
RETURN (Nan::Undefined());
} else {
if (g_field_info_set_field(field, boxed, &arg) == FALSE) {
Nan::ThrowError("Unable to set field (complex types not allowed)");
RETURN (Nan::Undefined());
}
/*
* g_field_info_set_field:
* This only handles fields of simple C types. It will fail for a field of
* a composite type like a nested structure or union even if that is actually
* writable. Note also that that it will refuse to write fields where memory
* management would by required. A field with a type such as 'char *' must be
* set with a setter function.
* Therefore, no need to free GIArgument.
*/
}
g_base_info_unref (field_type);
}
NAN_METHOD(StructFieldGetter) {
Local<Object> boxedWrapper = info[0].As<Object>();
Local<Object> fieldInfo = info[1].As<Object>();
if (boxedWrapper->InternalFieldCount() == 0) {
Nan::ThrowError("StructFieldGetter: instance is not a boxed");
return;
}
if (fieldInfo->InternalFieldCount() == 0) {
Nan::ThrowError("StructFieldGetter: field info is invalid");
return;
}
void *boxed = GNodeJS::PointerFromWrapper(boxedWrapper);
GIFieldInfo *field = (GIFieldInfo *) GNodeJS::PointerFromWrapper(fieldInfo);
if (boxed == NULL) {
Nan::ThrowError("StructFieldGetter: instance is NULL");
return;
}
if (field == NULL) {
Nan::ThrowError("StructFieldGetter: field info is NULL");
return;
}
GIArgument value;
if (!g_field_info_get_field(field, boxed, &value)) {
Nan::ThrowError("Unable to get field (complex types not allowed)");
return;
}
GITypeInfo *field_type = g_field_info_get_type(field);
RETURN(GNodeJS::GIArgumentToV8(field_type, &value));
g_base_info_unref (field_type);
}
NAN_METHOD(StartLoop) {
GNodeJS::StartLoop ();
}
NAN_METHOD(GetBaseClass) {
auto tpl = GNodeJS::GetBaseClassTemplate ();
auto fn = Nan::GetFunction (tpl).ToLocalChecked();
info.GetReturnValue().Set(fn);
}
NAN_METHOD(GetTypeSize) {
GITypeInfo *gi_info = (GITypeInfo *) GNodeJS::PointerFromWrapper (info[0]);
auto size = GNodeJS::GetTypeSize (gi_info);
info.GetReturnValue().Set(Nan::New<Number>(size));
}
NAN_METHOD(GetLoopStack) {
auto stack = GNodeJS::GetLoopStack();
info.GetReturnValue().Set(stack);
}
NAN_METHOD(GetModuleCache) {
info.GetReturnValue().Set(Nan::New<Object>(GNodeJS::moduleCache));
}
void InitModule(Local<Object> exports, Local<Value> module, void *priv) {
GNodeJS::AsyncCallEnvironment::Initialize();
NAN_EXPORT(exports, Bootstrap);
NAN_EXPORT(exports, GetModuleCache);
NAN_EXPORT(exports, GetConstantValue);
NAN_EXPORT(exports, MakeBoxedClass);
NAN_EXPORT(exports, MakeObjectClass);
NAN_EXPORT(exports, MakeFunction);
NAN_EXPORT(exports, MakeVirtualFunction);
NAN_EXPORT(exports, StructFieldGetter);
NAN_EXPORT(exports, StructFieldSetter);
NAN_EXPORT(exports, ObjectPropertyGetter);
NAN_EXPORT(exports, ObjectPropertySetter);
NAN_EXPORT(exports, StartLoop);
NAN_EXPORT(exports, GetBaseClass);
NAN_EXPORT(exports, GetTypeSize);
NAN_EXPORT(exports, GetLoopStack);
Nan::Set(exports, UTF8("System"), GNodeJS::System::GetModule());
Nan::Set(exports, UTF8("Cairo"), GNodeJS::Cairo::GetModule());
}
NODE_MODULE(node_gtk, InitModule)
<commit_msg>fix: use size from g_constant_info_get_value (closes #234)<commit_after>#include <gobject-introspection-1.0/girepository.h>
#include <node.h>
#include <nan.h>
#include "async_call_environment.h"
#include "boxed.h"
#include "debug.h"
#include "function.h"
#include "gi.h"
#include "gobject.h"
#include "loop.h"
#include "macros.h"
#include "type.h"
#include "util.h"
#include "value.h"
#include "modules/system.h"
#include "modules/cairo/cairo.h"
using namespace v8;
using GNodeJS::BaseInfo;
namespace GNodeJS {
G_DEFINE_QUARK(gnode_js_object, object);
G_DEFINE_QUARK(gnode_js_template, template);
G_DEFINE_QUARK(gnode_js_constructor, constructor);
G_DEFINE_QUARK(gnode_js_function, function);
Nan::Persistent<Object> moduleCache(Nan::New<Object>());
Local<Object> GetModuleCache() {
return Nan::New<Object>(GNodeJS::moduleCache);
}
}
static void DefineFunction(Isolate *isolate, Local<Object> module_obj, GIBaseInfo *info) {
const char *function_name = g_base_info_get_name ((GIBaseInfo *) info);
Local<Function> fn = GNodeJS::MakeFunction (info);
Nan::Set(module_obj, UTF8(function_name), fn);
}
static void DefineFunction(Isolate *isolate, Local<Object> module_obj, GIBaseInfo *info, const char *base_name) {
Local<Function> fn = GNodeJS::MakeFunction (info);
char *function_name = g_strdup_printf ("%s_%s", base_name, g_base_info_get_name(info));
Nan::Set(module_obj, UTF8(function_name), fn);
g_free (function_name);
}
static void DefineObjectFunctions(Isolate *isolate, Local<Object> module_obj, GIBaseInfo *info) {
const char *object_name = g_base_info_get_name ((GIBaseInfo *) info);
int n_methods = g_object_info_get_n_methods (info);
for (int i = 0; i < n_methods; i++) {
GIFunctionInfo *meth_info = g_object_info_get_method (info, i);
DefineFunction (isolate, module_obj, meth_info, object_name);
g_base_info_unref ((GIBaseInfo *) meth_info);
}
}
static void DefineBoxedFunctions(Isolate *isolate, Local<Object> module_obj, GIBaseInfo *info) {
const char *object_name = g_base_info_get_name ((GIBaseInfo *) info);
int n_methods = g_struct_info_get_n_methods (info);
for (int i = 0; i < n_methods; i++) {
GIFunctionInfo *meth_info = g_struct_info_get_method (info, i);
DefineFunction (isolate, module_obj, meth_info, object_name);
g_base_info_unref ((GIBaseInfo *) meth_info);
}
}
static void DefineBootstrapInfo(Isolate *isolate, Local<Object> module_obj, GIBaseInfo *info) {
GIInfoType type = g_base_info_get_type (info);
switch (type) {
case GI_INFO_TYPE_FUNCTION:
DefineFunction (isolate, module_obj, info);
break;
case GI_INFO_TYPE_OBJECT:
DefineObjectFunctions (isolate, module_obj, info);
break;
case GI_INFO_TYPE_BOXED:
case GI_INFO_TYPE_STRUCT:
DefineBoxedFunctions (isolate, module_obj, info);
break;
default:
break;
}
}
NAN_METHOD(Bootstrap) {
Isolate *isolate = info.GetIsolate();
GIRepository *repo = g_irepository_get_default ();
GError *error = NULL;
const char *ns = "GIRepository";
g_irepository_require (repo, ns, NULL, (GIRepositoryLoadFlags) 0, &error);
if (error) {
Nan::ThrowError( error->message );
return;
}
Local<Object> module_obj = Object::New (isolate);
int n = g_irepository_get_n_infos (repo, ns);
for (int i = 0; i < n; i++) {
BaseInfo baseInfo(g_irepository_get_info(repo, ns, i));
DefineBootstrapInfo(isolate, module_obj, baseInfo.info());
}
info.GetReturnValue().Set(module_obj);
}
NAN_METHOD(GetConstantValue) {
GIBaseInfo *gi_info = (GIBaseInfo *) GNodeJS::PointerFromWrapper (info[0]);
GITypeInfo *type = g_constant_info_get_type(gi_info);
if (type == NULL) {
info.GetReturnValue().SetNull();
return;
}
GIArgument gi_arg;
gint size = g_constant_info_get_value(gi_info, &gi_arg);
if (size < 0) {
WARN("Couldn't load %s.%s: invalid constant size: %i",
g_base_info_get_namespace (gi_info),
g_base_info_get_name (gi_info),
size);
}
else {
info.GetReturnValue().Set(GNodeJS::GIArgumentToV8 (type, &gi_arg, size));
}
g_constant_info_free_value(gi_info, &gi_arg);
g_base_info_unref(type);
}
NAN_METHOD(MakeFunction) {
BaseInfo gi_info(info[0]);
Local<Function> fn = GNodeJS::MakeFunction(*gi_info);
info.GetReturnValue().Set(fn);
}
NAN_METHOD(MakeVirtualFunction) {
if (info.Length() < 2 || !info[0]->IsObject() || !info[1]->IsNumber()) {
Nan::ThrowTypeError("Incorrect arguments. Expecting (GIBaseInfo, GType)");
return;
}
BaseInfo gi_info(info[0]);
GType implementor = (gulong) Nan::To<int64_t> (info[1]).ToChecked();
MaybeLocal<Function> maybeFn = GNodeJS::MakeVirtualFunction(*gi_info, implementor);
if (maybeFn.IsEmpty())
return;
info.GetReturnValue().Set(maybeFn.ToLocalChecked());
}
NAN_METHOD(MakeObjectClass) {
BaseInfo gi_info(info[0]);
auto klass = GNodeJS::MakeClass(*gi_info);
if (!klass.IsEmpty())
info.GetReturnValue().Set(klass.ToLocalChecked());
}
NAN_METHOD(MakeBoxedClass) {
BaseInfo gi_info(info[0]);
info.GetReturnValue().Set(GNodeJS::MakeBoxedClass(*gi_info));
}
NAN_METHOD(ObjectPropertyGetter) {
GObject *gobject = GNodeJS::GObjectFromWrapper (info[0]);
g_assert(gobject != NULL);
Nan::Utf8String prop_name_v (TO_STRING (info[1]));
const char *prop_name = *prop_name_v;
RETURN(GNodeJS::GetGObjectProperty(gobject, prop_name));
}
NAN_METHOD(ObjectPropertySetter) {
GObject* gobject = GNodeJS::GObjectFromWrapper(info[0]);
Nan::Utf8String prop_name_v (TO_STRING (info[1]));
const char *prop_name = *prop_name_v;
if (gobject == NULL) {
WARN("ObjectPropertySetter: null GObject; cant get %s", prop_name);
RETURN(Nan::False());
}
RETURN(GNodeJS::SetGObjectProperty(gobject, prop_name, info[2]));
}
NAN_METHOD(StructFieldSetter) {
Local<Object> boxedWrapper = info[0].As<Object>();
Local<Object> fieldInfo = info[1].As<Object>();
Local<Value> value = info[2];
void *boxed = GNodeJS::PointerFromWrapper(boxedWrapper);
GIFieldInfo *field = (GIFieldInfo *) GNodeJS::PointerFromWrapper(fieldInfo);
GITypeInfo *field_type = g_field_info_get_type(field);
g_assert(boxed);
g_assert(field);
g_assert(field_type);
GIArgument arg;
if (!GNodeJS::V8ToGIArgument(field_type, &arg, value, true)) {
char *message = g_strdup_printf("Couldn't convert value for field '%s'",
g_base_info_get_name(field));
Nan::ThrowTypeError (message);
g_free(message);
RETURN (Nan::Undefined());
} else {
if (g_field_info_set_field(field, boxed, &arg) == FALSE) {
Nan::ThrowError("Unable to set field (complex types not allowed)");
RETURN (Nan::Undefined());
}
/*
* g_field_info_set_field:
* This only handles fields of simple C types. It will fail for a field of
* a composite type like a nested structure or union even if that is actually
* writable. Note also that that it will refuse to write fields where memory
* management would by required. A field with a type such as 'char *' must be
* set with a setter function.
* Therefore, no need to free GIArgument.
*/
}
g_base_info_unref (field_type);
}
NAN_METHOD(StructFieldGetter) {
Local<Object> boxedWrapper = info[0].As<Object>();
Local<Object> fieldInfo = info[1].As<Object>();
if (boxedWrapper->InternalFieldCount() == 0) {
Nan::ThrowError("StructFieldGetter: instance is not a boxed");
return;
}
if (fieldInfo->InternalFieldCount() == 0) {
Nan::ThrowError("StructFieldGetter: field info is invalid");
return;
}
void *boxed = GNodeJS::PointerFromWrapper(boxedWrapper);
GIFieldInfo *field = (GIFieldInfo *) GNodeJS::PointerFromWrapper(fieldInfo);
if (boxed == NULL) {
Nan::ThrowError("StructFieldGetter: instance is NULL");
return;
}
if (field == NULL) {
Nan::ThrowError("StructFieldGetter: field info is NULL");
return;
}
GIArgument value;
if (!g_field_info_get_field(field, boxed, &value)) {
Nan::ThrowError("Unable to get field (complex types not allowed)");
return;
}
GITypeInfo *field_type = g_field_info_get_type(field);
RETURN(GNodeJS::GIArgumentToV8(field_type, &value));
g_base_info_unref (field_type);
}
NAN_METHOD(StartLoop) {
GNodeJS::StartLoop ();
}
NAN_METHOD(GetBaseClass) {
auto tpl = GNodeJS::GetBaseClassTemplate ();
auto fn = Nan::GetFunction (tpl).ToLocalChecked();
info.GetReturnValue().Set(fn);
}
NAN_METHOD(GetTypeSize) {
GITypeInfo *gi_info = (GITypeInfo *) GNodeJS::PointerFromWrapper (info[0]);
auto size = GNodeJS::GetTypeSize (gi_info);
info.GetReturnValue().Set(Nan::New<Number>(size));
}
NAN_METHOD(GetLoopStack) {
auto stack = GNodeJS::GetLoopStack();
info.GetReturnValue().Set(stack);
}
NAN_METHOD(GetModuleCache) {
info.GetReturnValue().Set(Nan::New<Object>(GNodeJS::moduleCache));
}
void InitModule(Local<Object> exports, Local<Value> module, void *priv) {
GNodeJS::AsyncCallEnvironment::Initialize();
NAN_EXPORT(exports, Bootstrap);
NAN_EXPORT(exports, GetModuleCache);
NAN_EXPORT(exports, GetConstantValue);
NAN_EXPORT(exports, MakeBoxedClass);
NAN_EXPORT(exports, MakeObjectClass);
NAN_EXPORT(exports, MakeFunction);
NAN_EXPORT(exports, MakeVirtualFunction);
NAN_EXPORT(exports, StructFieldGetter);
NAN_EXPORT(exports, StructFieldSetter);
NAN_EXPORT(exports, ObjectPropertyGetter);
NAN_EXPORT(exports, ObjectPropertySetter);
NAN_EXPORT(exports, StartLoop);
NAN_EXPORT(exports, GetBaseClass);
NAN_EXPORT(exports, GetTypeSize);
NAN_EXPORT(exports, GetLoopStack);
Nan::Set(exports, UTF8("System"), GNodeJS::System::GetModule());
Nan::Set(exports, UTF8("Cairo"), GNodeJS::Cairo::GetModule());
}
NODE_MODULE(node_gtk, InitModule)
<|endoftext|>
|
<commit_before>/******************************************************************************
* _ _____ __________ *
* | | / / _ | / __/_ __/ Visibility *
* | |/ / __ |_\ \ / / Across *
* |___/_/ |_/___/ /_/ Space and Time *
* *
* This file is part of VAST. It is subject to the license terms in the *
* LICENSE file found in the top-level directory of this distribution and at *
* http://vast.io/license. No part of VAST, including this file, may be *
* copied, modified, propagated, or distributed except according to the terms *
* contained in the LICENSE file. *
******************************************************************************/
#include "vast/expression.hpp"
#include "vast/expression_visitors.hpp"
#include "vast/detail/assert.hpp"
#include "vast/detail/overload.hpp"
namespace vast {
// -- attribute_extractor ------------------------------------------------------
attribute_extractor::attribute_extractor(caf::atom_value str) : attr{str} {
// nop
}
bool operator==(const attribute_extractor& x, const attribute_extractor& y) {
return x.attr == y.attr;
}
bool operator<(const attribute_extractor& x, const attribute_extractor& y) {
return x.attr < y.attr;
}
// -- key_extractor ------------------------------------------------------------
key_extractor::key_extractor(std::string k) : key{std::move(k)} {
}
bool operator==(const key_extractor& x, const key_extractor& y) {
return x.key == y.key;
}
bool operator<(const key_extractor& x, const key_extractor& y) {
return x.key < y.key;
}
// -- type_extractor -----------------------------------------------------------
type_extractor::type_extractor(vast::type t) : type{std::move(t)} {
}
bool operator==(const type_extractor& x, const type_extractor& y) {
return x.type == y.type;
}
bool operator<(const type_extractor& x, const type_extractor& y) {
return x.type < y.type;
}
// -- data_extractor -----------------------------------------------------------
data_extractor::data_extractor(vast::type t, vast::offset o)
: type{std::move(t)}, offset{std::move(o)} {
}
bool operator==(const data_extractor& x, const data_extractor& y) {
return x.type == y.type && x.offset == y.offset;
}
bool operator<(const data_extractor& x, const data_extractor& y) {
return std::tie(x.type, x.offset) < std::tie(y.type, y.offset);
}
// -- predicate ----------------------------------------------------------------
predicate::predicate(operand l, relational_operator o, operand r)
: lhs{std::move(l)}, op{o}, rhs{std::move(r)} {
}
bool operator==(const predicate& x, const predicate& y) {
return x.lhs == y.lhs && x.op == y.op && x.rhs == y.rhs;
}
bool operator<(const predicate& x, const predicate& y) {
return std::tie(x.lhs, x.op, x.rhs)
< std::tie(y.lhs, y.op, y.rhs);
}
// -- negation -----------------------------------------------------------------
negation::negation()
: expr_{std::make_unique<expression>()} {
}
negation::negation(expression expr)
: expr_{std::make_unique<expression>(std::move(expr))} {
}
negation::negation(const negation& other)
: expr_{std::make_unique<expression>(*other.expr_)} {
}
negation::negation(negation&& other) noexcept
: expr_{std::move(other.expr_)} {
}
negation& negation::operator=(const negation& other) {
*expr_ = *other.expr_;
return *this;
}
negation& negation::operator=(negation&& other) noexcept {
expr_ = std::move(other.expr_);
return *this;
}
const expression& negation::expr() const {
return *expr_;
}
expression& negation::expr() {
return *expr_;
}
bool operator==(const negation& x, const negation& y) {
return x.expr() == y.expr();
}
bool operator<(const negation& x, const negation& y) {
return x.expr() < y.expr();
}
// -- expression ---------------------------------------------------------------
const expression::node& expression::get_data() const {
return node_;
}
expression::node& expression::get_data() {
return node_;
}
bool operator==(const expression& x, const expression& y) {
return x.get_data() == y.get_data();
}
bool operator<(const expression& x, const expression& y) {
return x.get_data() < y.get_data();
}
// -- free functions -----------------------------------------------------------
expression normalize(const expression& expr) {
expression r;
r = caf::visit(hoister{}, expr);
r = caf::visit(aligner{}, r);
r = caf::visit(denegator{}, r);
r = caf::visit(deduplicator{}, r);
r = caf::visit(hoister{}, r);
return r;
}
expected<expression> normalize_and_validate(const expression& expr) {
auto normalized = normalize(expr);
auto result = caf::visit(validator{}, normalized);
if (!result)
return result.error();
return normalized;
}
expected<expression> tailor(const expression& expr, const type& t) {
if (caf::holds_alternative<caf::none_t>(expr))
return make_error(ec::unspecified, "invalid expression");
auto x = caf::visit(type_resolver{t}, expr);
if (!x)
return x.error();
*x = caf::visit(type_pruner{t}, *x);
VAST_ASSERT(!caf::holds_alternative<caf::none_t>(*x));
return std::move(*x);
}
namespace {
// Helper function to lookup an expression at a particular offset
const expression* at(const expression* expr, offset::value_type i) {
VAST_ASSERT(expr != nullptr);
return caf::visit(detail::overload(
[&](const conjunction& xs) -> const expression* {
return i < xs.size() ? &xs[i] : nullptr;
},
[&](const disjunction& xs) -> const expression* {
return i < xs.size() ? &xs[i] : nullptr;
},
[&](const negation& x) -> const expression* {
return i == 0 ? &x.expr() : nullptr;
},
[&](const auto&) -> const expression* {
return nullptr;
}
), *expr);
}
} // namespace <anonymous>
const expression* at(const expression& expr, const offset& o) {
if (o.empty())
return nullptr; // empty offsets are invalid
if (o.size() == 1)
return o[0] == 0 ? &expr : nullptr; // the root has always offset [0]
auto ptr = &expr;
for (size_t i = 1; i < o.size(); ++i) {
ptr = at(ptr, o[i]);
if (ptr == nullptr)
break;
}
return ptr;
}
namespace {
bool resolve(std::vector<std::pair<offset, predicate>>& result,
const expression& expr, const type& t, offset& o) {
return caf::visit(detail::overload(
[&](const auto& xs) { // conjunction or disjunction
o.emplace_back(0);
if (!xs.empty()) {
if (!resolve(result, xs[0], t, o))
return false;
for (size_t i = 1; i < xs.size(); ++i) {
o.back() += 1;
if (!resolve(result, xs[i], t, o))
return false;
}
}
o.pop_back();
return true;
},
[&](const negation& x) {
o.emplace_back(0);
if (!resolve(result, x.expr(), t, o))
return false;
o.pop_back();
return true;
},
[&](const predicate& x) {
auto resolved = type_resolver{t}(x);
// Abort on first type error and return a default-constructed vector.
if (!resolved)
return false;
for (auto& pred : caf::visit(predicatizer{}, *resolved))
result.emplace_back(o, std::move(pred));
return true;
},
[&](caf::none_t) {
VAST_ASSERT(!"invalid expression node");
return false;
}
), expr);
}
} // namespace <anonymous>
std::vector<std::pair<offset, predicate>> resolve(const expression& expr,
const type& t) {
std::vector<std::pair<offset, predicate>> result;
offset o{0};
if (resolve(result, expr, t, o))
return result;
return {};
}
} // namespace vast
<commit_msg>Add _impl suffix to private function<commit_after>/******************************************************************************
* _ _____ __________ *
* | | / / _ | / __/_ __/ Visibility *
* | |/ / __ |_\ \ / / Across *
* |___/_/ |_/___/ /_/ Space and Time *
* *
* This file is part of VAST. It is subject to the license terms in the *
* LICENSE file found in the top-level directory of this distribution and at *
* http://vast.io/license. No part of VAST, including this file, may be *
* copied, modified, propagated, or distributed except according to the terms *
* contained in the LICENSE file. *
******************************************************************************/
#include "vast/expression.hpp"
#include "vast/expression_visitors.hpp"
#include "vast/detail/assert.hpp"
#include "vast/detail/overload.hpp"
namespace vast {
// -- attribute_extractor ------------------------------------------------------
attribute_extractor::attribute_extractor(caf::atom_value str) : attr{str} {
// nop
}
bool operator==(const attribute_extractor& x, const attribute_extractor& y) {
return x.attr == y.attr;
}
bool operator<(const attribute_extractor& x, const attribute_extractor& y) {
return x.attr < y.attr;
}
// -- key_extractor ------------------------------------------------------------
key_extractor::key_extractor(std::string k) : key{std::move(k)} {
}
bool operator==(const key_extractor& x, const key_extractor& y) {
return x.key == y.key;
}
bool operator<(const key_extractor& x, const key_extractor& y) {
return x.key < y.key;
}
// -- type_extractor -----------------------------------------------------------
type_extractor::type_extractor(vast::type t) : type{std::move(t)} {
}
bool operator==(const type_extractor& x, const type_extractor& y) {
return x.type == y.type;
}
bool operator<(const type_extractor& x, const type_extractor& y) {
return x.type < y.type;
}
// -- data_extractor -----------------------------------------------------------
data_extractor::data_extractor(vast::type t, vast::offset o)
: type{std::move(t)}, offset{std::move(o)} {
}
bool operator==(const data_extractor& x, const data_extractor& y) {
return x.type == y.type && x.offset == y.offset;
}
bool operator<(const data_extractor& x, const data_extractor& y) {
return std::tie(x.type, x.offset) < std::tie(y.type, y.offset);
}
// -- predicate ----------------------------------------------------------------
predicate::predicate(operand l, relational_operator o, operand r)
: lhs{std::move(l)}, op{o}, rhs{std::move(r)} {
}
bool operator==(const predicate& x, const predicate& y) {
return x.lhs == y.lhs && x.op == y.op && x.rhs == y.rhs;
}
bool operator<(const predicate& x, const predicate& y) {
return std::tie(x.lhs, x.op, x.rhs)
< std::tie(y.lhs, y.op, y.rhs);
}
// -- negation -----------------------------------------------------------------
negation::negation()
: expr_{std::make_unique<expression>()} {
}
negation::negation(expression expr)
: expr_{std::make_unique<expression>(std::move(expr))} {
}
negation::negation(const negation& other)
: expr_{std::make_unique<expression>(*other.expr_)} {
}
negation::negation(negation&& other) noexcept
: expr_{std::move(other.expr_)} {
}
negation& negation::operator=(const negation& other) {
*expr_ = *other.expr_;
return *this;
}
negation& negation::operator=(negation&& other) noexcept {
expr_ = std::move(other.expr_);
return *this;
}
const expression& negation::expr() const {
return *expr_;
}
expression& negation::expr() {
return *expr_;
}
bool operator==(const negation& x, const negation& y) {
return x.expr() == y.expr();
}
bool operator<(const negation& x, const negation& y) {
return x.expr() < y.expr();
}
// -- expression ---------------------------------------------------------------
const expression::node& expression::get_data() const {
return node_;
}
expression::node& expression::get_data() {
return node_;
}
bool operator==(const expression& x, const expression& y) {
return x.get_data() == y.get_data();
}
bool operator<(const expression& x, const expression& y) {
return x.get_data() < y.get_data();
}
// -- free functions -----------------------------------------------------------
expression normalize(const expression& expr) {
expression r;
r = caf::visit(hoister{}, expr);
r = caf::visit(aligner{}, r);
r = caf::visit(denegator{}, r);
r = caf::visit(deduplicator{}, r);
r = caf::visit(hoister{}, r);
return r;
}
expected<expression> normalize_and_validate(const expression& expr) {
auto normalized = normalize(expr);
auto result = caf::visit(validator{}, normalized);
if (!result)
return result.error();
return normalized;
}
expected<expression> tailor(const expression& expr, const type& t) {
if (caf::holds_alternative<caf::none_t>(expr))
return make_error(ec::unspecified, "invalid expression");
auto x = caf::visit(type_resolver{t}, expr);
if (!x)
return x.error();
*x = caf::visit(type_pruner{t}, *x);
VAST_ASSERT(!caf::holds_alternative<caf::none_t>(*x));
return std::move(*x);
}
namespace {
// Helper function to lookup an expression at a particular offset
const expression* at(const expression* expr, offset::value_type i) {
VAST_ASSERT(expr != nullptr);
return caf::visit(detail::overload(
[&](const conjunction& xs) -> const expression* {
return i < xs.size() ? &xs[i] : nullptr;
},
[&](const disjunction& xs) -> const expression* {
return i < xs.size() ? &xs[i] : nullptr;
},
[&](const negation& x) -> const expression* {
return i == 0 ? &x.expr() : nullptr;
},
[&](const auto&) -> const expression* {
return nullptr;
}
), *expr);
}
} // namespace <anonymous>
const expression* at(const expression& expr, const offset& o) {
if (o.empty())
return nullptr; // empty offsets are invalid
if (o.size() == 1)
return o[0] == 0 ? &expr : nullptr; // the root has always offset [0]
auto ptr = &expr;
for (size_t i = 1; i < o.size(); ++i) {
ptr = at(ptr, o[i]);
if (ptr == nullptr)
break;
}
return ptr;
}
namespace {
bool resolve_impl(std::vector<std::pair<offset, predicate>>& result,
const expression& expr, const type& t, offset& o) {
return caf::visit(detail::overload(
[&](const auto& xs) { // conjunction or disjunction
o.emplace_back(0);
if (!xs.empty()) {
if (!resolve_impl(result, xs[0], t, o))
return false;
for (size_t i = 1; i < xs.size(); ++i) {
o.back() += 1;
if (!resolve_impl(result, xs[i], t, o))
return false;
}
}
o.pop_back();
return true;
},
[&](const negation& x) {
o.emplace_back(0);
if (!resolve_impl(result, x.expr(), t, o))
return false;
o.pop_back();
return true;
},
[&](const predicate& x) {
auto resolved = type_resolver{t}(x);
// Abort on first type error and return a default-constructed vector.
if (!resolved)
return false;
for (auto& pred : caf::visit(predicatizer{}, *resolved))
result.emplace_back(o, std::move(pred));
return true;
},
[&](caf::none_t) {
VAST_ASSERT(!"invalid expression node");
return false;
}
), expr);
}
} // namespace <anonymous>
std::vector<std::pair<offset, predicate>> resolve(const expression& expr,
const type& t) {
std::vector<std::pair<offset, predicate>> result;
offset o{0};
if (resolve_impl(result, expr, t, o))
return result;
return {};
}
} // namespace vast
<|endoftext|>
|
<commit_before>#include "disassembler.h"
#include "util.h"
#include "symtab.h"
#include <vector>
#include <cctype>
using namespace std;
enum ByteTypeGuess {
UNINITIALIZED,
UNKNOWN,
CHAR_DATA,
UNINITIALIZED_CHAR_DATA,
WORD_DATA,
UNINITIALIZED_WORD_DATA,
CODE,
};
struct program {
ByteTypeGuess byte_type_guess[65536];
char memory[65536];
bool is_labelled[65536];
string name;
string starting_address;
int length_of_program;
string first_executable_instruction;
program() {
for ( int i = 0 ; i < 65536 ; i++ ) {
byte_type_guess[i] = UNINITIALIZED;
memory[i] = 0;
is_labelled[i] = false;
}
name = "";
starting_address = "";
length_of_program = 0;
first_executable_instruction = "";
}
};
bool read_record(ifstream &ifile, string &record);
void record_to_memory(const string record, program &p);
void analyze_code_data(program &p);
void write_assembly(const program &p, ofstream &ofile);
bool disassemble(ifstream &ifile, ofstream &ofile) {
string record;
program p;
while ( read_record(ifile, record) ) {
record_to_memory(record, p);
}
status("Done reading records");
analyze_code_data(p);
status("Done analyzing program for code and data");
write_assembly(p, ofile);
status("Done writing output file");
return true;
}
string read_columns(ifstream &ifile, int col_begin, int col_end, char record_type = 'a') { // inclusive of both
string ret;
char t;
for ( int col = col_begin ; col <= col_end ; col++ ) {
t = ifile.get();
if ( t == EOF || t == '\n' ) {
string errstr;
errstr += "Unexpected end of ";
errstr += record_type;
errstr += " record";
fatal(errstr);
}
ret += t;
}
return ret;
}
string read_hex_columns(ifstream &ifile, int col_begin, int col_end, char record_type = 'a') { // inclusive of both
string ret;
ret = read_columns(ifile,col_begin,col_end,record_type);
make_upper_case(ret);
if ( !is_hex_string(ret) ) {
string errstr;
errstr += "Unexpected non-hexadecimal character found in ";
errstr += record_type;
errstr += " record";
fatal(errstr);
}
return ret;
}
bool read_record(ifstream &ifile, string &record) {
int temp_int;
string temp_str;
char t;
do {
t = ifile.get();
if ( t == EOF ) {
return false;
}
} while ( t == '\n' || t == ' ' );
record = "";
record += t;
switch (t) {
case 'H': // Header
record += read_columns(ifile,2,7,'H');
record += read_hex_columns(ifile,8,19,'H');
break;
case 'T': // Text
record += read_hex_columns(ifile,2,7,'T');
temp_str = read_hex_columns(ifile,8,9,'T');
temp_int = hex2int(temp_str);
record += temp_str;
record += read_hex_columns(ifile,10,9+2*temp_int,'T');
break;
case 'E': // End
record += read_hex_columns(ifile,2,7,'E');
break;
default:
{
string errstr = "Unknown record type ";
errstr += t;
fatal(errstr);
}
}
return true;
}
void record_to_memory(const string record, program &p) {
const char * c_record = record.c_str();
switch (*c_record) {
case 'H': // Header
if ( p.name.length() != 0 ) {
fatal("Multiple H records");
}
p.name = record.substr(1,6);
p.starting_address = record.substr(7,6);
p.length_of_program = hex2int(record.substr(13,6));
break;
case 'T': // Text
{
int text_start = hex2int(record.substr(1,6));
int bit_length = hex2int(record.substr(7,2));
for ( int i = 0 ; i < bit_length ; i++ ) {
p.memory[i+text_start] = hex2int(record.substr(9+2*i,2));
p.byte_type_guess[i+text_start] = UNKNOWN;
}
}
break;
case 'E': // End
if ( p.first_executable_instruction.length() != 0 ) {
fatal("Multiple E records");
}
p.first_executable_instruction = record.substr(1,6);
break;
default:
{
string errstr;
errstr += "Unknown record type ";
errstr += *c_record;
fatal(errstr);
}
}
}
void mark_code_data(program &p, int location, ByteTypeGuess btg) {
if ( location >= hex2int(p.starting_address) + p.length_of_program ) {
return;
}
switch (btg) {
case UNINITIALIZED:
case UNKNOWN:
break;
case CHAR_DATA:
case UNINITIALIZED_CHAR_DATA:
{
if ( p.byte_type_guess[location] != UNKNOWN &&
p.byte_type_guess[location] != UNINITIALIZED ) {
break;
}
if ( p.byte_type_guess[location] == UNINITIALIZED )
btg = UNINITIALIZED_CHAR_DATA;
p.byte_type_guess[location] = btg;
break;
}
case WORD_DATA:
case UNINITIALIZED_WORD_DATA:
{
if ( p.byte_type_guess[location] != UNKNOWN &&
p.byte_type_guess[location] != UNINITIALIZED ) {
break;
}
if ( p.byte_type_guess[location] == UNINITIALIZED )
btg = UNINITIALIZED_WORD_DATA;
p.byte_type_guess[location+0] = btg;
p.byte_type_guess[location+1] = btg;
p.byte_type_guess[location+2] = btg;
break;
}
case CODE:
{
if ( p.byte_type_guess[location] == UNINITIALIZED ) {
fatal("Attempting to use uninitialized section as code");
}
if ( p.byte_type_guess[location] == CODE ) {
break;
}
p.byte_type_guess[location+0] = btg;
p.byte_type_guess[location+1] = btg;
p.byte_type_guess[location+2] = btg;
string opcode_val = byte2hex(p.memory[location]);
string opcode;
string operand = byte2hex(p.memory[location+1])+byte2hex(p.memory[location+2]);
operand = int2hex(hex2int(operand)&0x7FFF); // remove index flag
if ( ! find_from_symtab(opcode,opcode_val) ) {
string errstr;
errstr += "Unknown opcode ";
errstr += opcode_val;
errstr += " at location ";
errstr += int2hex(location);
fatal(errstr);
}
if ( opcode == "ADD" ||
opcode == "AND" ||
opcode == "COMP" ||
opcode == "DIV" ||
opcode == "LDA" ||
opcode == "LDL" ||
opcode == "LDX" ||
opcode == "MUL" ||
opcode == "OR" ||
opcode == "STA" ||
opcode == "STL" ||
opcode == "STX" ||
opcode == "SUB" ||
opcode == "TIX" ) {
give_label(operand);
p.is_labelled[hex2int(operand)] = true;
mark_code_data(p,hex2int(operand),WORD_DATA);
}
if ( opcode == "LDCH" ||
opcode == "STCH" ) {
give_label(operand);
p.is_labelled[hex2int(operand)] = true;
mark_code_data(p,hex2int(operand),CHAR_DATA);
}
if ( opcode == "J" ||
opcode == "JEQ" ||
opcode == "JGT" ||
opcode == "JLT" ||
opcode == "JSUB" ||
opcode == "RSUB" ) {
give_label(operand);
p.is_labelled[hex2int(operand)] = true;
mark_code_data(p,hex2int(operand),CODE);
}
if ( opcode != "J" &&
opcode != "RSUB" ) {
mark_code_data(p,location+3,btg);
}
break;
}
}
}
void analyze_code_data(program &p) {
if ( p.name.length() == 0 ) {
fatal("No Header record");
}
if ( p.first_executable_instruction.length() == 0 ) {
fatal("No End record");
}
initialize_symtab();
add_to_symtab("FIRST",p.first_executable_instruction);
p.is_labelled[hex2int(p.first_executable_instruction)] = true;
mark_code_data(p,hex2int(p.first_executable_instruction),CODE);
}
string asm_to_line(string label, string opcode, string operand, bool is_indexed) {
const int labellength = 8;
const int opcodelength = 6;
string ret = "";
ret += label + string(labellength-label.length(),' ');
ret += opcode + string(opcodelength-opcode.length(),' ');
ret += operand;
if ( is_indexed ) {
ret += ",X";
}
ret += '\n';
return ret;
}
void write_assembly(const program &p, ofstream &ofile) {
ofile << asm_to_line(p.name,"START",p.starting_address,false);
int start_of_program = hex2int(p.starting_address);
int end_of_program = start_of_program + p.length_of_program;
for ( int locctr = start_of_program ; locctr < end_of_program ; ) {
string label = "";
string opcode = "";
string operand = "";
bool is_indexed = false;
if ( p.is_labelled[locctr] ) {
if ( !find_from_symtab(label,int2hex(locctr)) ) {
string errstr;
errstr += "Label not created for location ";
errstr += int2hex(locctr);
error(errstr);
}
}
if ( p.byte_type_guess[locctr] == CODE ) {
if ( ! find_from_symtab(opcode,byte2hex(p.memory[locctr])) ) {
string errstr;
errstr += "Unknown opcode ";
errstr += opcode;
errstr += " at location ";
errstr += int2hex(locctr);
fatal(errstr);
}
operand = byte2hex(p.memory[locctr+1])+byte2hex(p.memory[locctr+2]);
is_indexed = (hex2int(operand)&0x8000);
operand = int2hex(hex2int(operand)&0x7FFF); // remove index flag
if ( opcode != "RD" &&
opcode != "TD" &&
opcode != "WD" &&
opcode != "RSUB" ) {
if ( !find_from_symtab(operand,operand) ) {
string errstr;
errstr += "Label not created for operand ";
errstr += operand;
error(errstr);
}
}
if ( opcode == "RSUB" ) {
operand = "";
}
locctr += 3;
} else if ( p.byte_type_guess[locctr] == CHAR_DATA ||
p.byte_type_guess[locctr] == UNKNOWN ) {
if ( p.byte_type_guess[locctr] == UNKNOWN ) {
label = "UNUSED"; // This should not happen in a well written code
}
vector<char> byte_list;
bool type_c = true;
do {
byte_list.push_back(p.memory[locctr]);
if ( !isprint(p.memory[locctr]) ) {
type_c = false;
}
locctr++;
} while ( p.byte_type_guess[locctr] == CHAR_DATA && !p.is_labelled[locctr] );
opcode = "CHAR";
operand += (type_c?"C":"X");
operand += "'";
for ( int i = 0 ; i < (int)byte_list.size() ; i++ ) {
if ( type_c ) {
operand += byte_list[i];
} else {
operand += byte2hex(byte_list[i]);
}
}
operand += "'";
} else if ( p.byte_type_guess[locctr] == WORD_DATA ) {
opcode = "WORD";
operand = int2str(
p.memory[locctr+0]*256*256+
p.memory[locctr+1]*256+
p.memory[locctr+2]
);
locctr += 3;
} else if ( p.byte_type_guess[locctr] == UNINITIALIZED_CHAR_DATA ||
p.byte_type_guess[locctr] == UNINITIALIZED ) {
opcode = "RESB";
int buf_size = 0;
do {
buf_size++;
locctr++;
} while ( (p.byte_type_guess[locctr] == UNINITIALIZED_CHAR_DATA
|| p.byte_type_guess[locctr] == UNINITIALIZED)
&& !p.is_labelled[locctr]
&& locctr < end_of_program);
if ( locctr >= end_of_program ) {
buf_size--;
}
operand = int2str(buf_size);
} else if ( p.byte_type_guess[locctr] == UNINITIALIZED_WORD_DATA ) {
opcode = "RESW";
int buf_size = 0;
do {
buf_size++;
locctr+=3;
} while ( (p.byte_type_guess[locctr] == UNINITIALIZED_WORD_DATA
|| p.byte_type_guess[locctr] == UNINITIALIZED)
&& !p.is_labelled[locctr]
&& locctr < end_of_program);
if ( locctr >= end_of_program ) {
buf_size--;
}
operand = int2str(buf_size);
} else {
fatal("Reached part of decompiler that should not be reached");
}
ofile << asm_to_line(label,opcode,operand,is_indexed);
}
ofile << asm_to_line("","END","FIRST",false);
}<commit_msg>Prevent code marking for RSUB<commit_after>#include "disassembler.h"
#include "util.h"
#include "symtab.h"
#include <vector>
#include <cctype>
using namespace std;
enum ByteTypeGuess {
UNINITIALIZED,
UNKNOWN,
CHAR_DATA,
UNINITIALIZED_CHAR_DATA,
WORD_DATA,
UNINITIALIZED_WORD_DATA,
CODE,
};
struct program {
ByteTypeGuess byte_type_guess[65536];
char memory[65536];
bool is_labelled[65536];
string name;
string starting_address;
int length_of_program;
string first_executable_instruction;
program() {
for ( int i = 0 ; i < 65536 ; i++ ) {
byte_type_guess[i] = UNINITIALIZED;
memory[i] = 0;
is_labelled[i] = false;
}
name = "";
starting_address = "";
length_of_program = 0;
first_executable_instruction = "";
}
};
bool read_record(ifstream &ifile, string &record);
void record_to_memory(const string record, program &p);
void analyze_code_data(program &p);
void write_assembly(const program &p, ofstream &ofile);
bool disassemble(ifstream &ifile, ofstream &ofile) {
string record;
program p;
while ( read_record(ifile, record) ) {
record_to_memory(record, p);
}
status("Done reading records");
analyze_code_data(p);
status("Done analyzing program for code and data");
write_assembly(p, ofile);
status("Done writing output file");
return true;
}
string read_columns(ifstream &ifile, int col_begin, int col_end, char record_type = 'a') { // inclusive of both
string ret;
char t;
for ( int col = col_begin ; col <= col_end ; col++ ) {
t = ifile.get();
if ( t == EOF || t == '\n' ) {
string errstr;
errstr += "Unexpected end of ";
errstr += record_type;
errstr += " record";
fatal(errstr);
}
ret += t;
}
return ret;
}
string read_hex_columns(ifstream &ifile, int col_begin, int col_end, char record_type = 'a') { // inclusive of both
string ret;
ret = read_columns(ifile,col_begin,col_end,record_type);
make_upper_case(ret);
if ( !is_hex_string(ret) ) {
string errstr;
errstr += "Unexpected non-hexadecimal character found in ";
errstr += record_type;
errstr += " record";
fatal(errstr);
}
return ret;
}
bool read_record(ifstream &ifile, string &record) {
int temp_int;
string temp_str;
char t;
do {
t = ifile.get();
if ( t == EOF ) {
return false;
}
} while ( t == '\n' || t == ' ' );
record = "";
record += t;
switch (t) {
case 'H': // Header
record += read_columns(ifile,2,7,'H');
record += read_hex_columns(ifile,8,19,'H');
break;
case 'T': // Text
record += read_hex_columns(ifile,2,7,'T');
temp_str = read_hex_columns(ifile,8,9,'T');
temp_int = hex2int(temp_str);
record += temp_str;
record += read_hex_columns(ifile,10,9+2*temp_int,'T');
break;
case 'E': // End
record += read_hex_columns(ifile,2,7,'E');
break;
default:
{
string errstr = "Unknown record type ";
errstr += t;
fatal(errstr);
}
}
return true;
}
void record_to_memory(const string record, program &p) {
const char * c_record = record.c_str();
switch (*c_record) {
case 'H': // Header
if ( p.name.length() != 0 ) {
fatal("Multiple H records");
}
p.name = record.substr(1,6);
p.starting_address = record.substr(7,6);
p.length_of_program = hex2int(record.substr(13,6));
break;
case 'T': // Text
{
int text_start = hex2int(record.substr(1,6));
int bit_length = hex2int(record.substr(7,2));
for ( int i = 0 ; i < bit_length ; i++ ) {
p.memory[i+text_start] = hex2int(record.substr(9+2*i,2));
p.byte_type_guess[i+text_start] = UNKNOWN;
}
}
break;
case 'E': // End
if ( p.first_executable_instruction.length() != 0 ) {
fatal("Multiple E records");
}
p.first_executable_instruction = record.substr(1,6);
break;
default:
{
string errstr;
errstr += "Unknown record type ";
errstr += *c_record;
fatal(errstr);
}
}
}
void mark_code_data(program &p, int location, ByteTypeGuess btg) {
if ( location >= hex2int(p.starting_address) + p.length_of_program ) {
return;
}
switch (btg) {
case UNINITIALIZED:
case UNKNOWN:
break;
case CHAR_DATA:
case UNINITIALIZED_CHAR_DATA:
{
if ( p.byte_type_guess[location] != UNKNOWN &&
p.byte_type_guess[location] != UNINITIALIZED ) {
break;
}
if ( p.byte_type_guess[location] == UNINITIALIZED )
btg = UNINITIALIZED_CHAR_DATA;
p.byte_type_guess[location] = btg;
break;
}
case WORD_DATA:
case UNINITIALIZED_WORD_DATA:
{
if ( p.byte_type_guess[location] != UNKNOWN &&
p.byte_type_guess[location] != UNINITIALIZED ) {
break;
}
if ( p.byte_type_guess[location] == UNINITIALIZED )
btg = UNINITIALIZED_WORD_DATA;
p.byte_type_guess[location+0] = btg;
p.byte_type_guess[location+1] = btg;
p.byte_type_guess[location+2] = btg;
break;
}
case CODE:
{
if ( p.byte_type_guess[location] == UNINITIALIZED ) {
fatal("Attempting to use uninitialized section as code");
}
if ( p.byte_type_guess[location] == CODE ) {
break;
}
p.byte_type_guess[location+0] = btg;
p.byte_type_guess[location+1] = btg;
p.byte_type_guess[location+2] = btg;
string opcode_val = byte2hex(p.memory[location]);
string opcode;
string operand = byte2hex(p.memory[location+1])+byte2hex(p.memory[location+2]);
operand = int2hex(hex2int(operand)&0x7FFF); // remove index flag
if ( ! find_from_symtab(opcode,opcode_val) ) {
string errstr;
errstr += "Unknown opcode ";
errstr += opcode_val;
errstr += " at location ";
errstr += int2hex(location);
fatal(errstr);
}
if ( opcode == "ADD" ||
opcode == "AND" ||
opcode == "COMP" ||
opcode == "DIV" ||
opcode == "LDA" ||
opcode == "LDL" ||
opcode == "LDX" ||
opcode == "MUL" ||
opcode == "OR" ||
opcode == "STA" ||
opcode == "STL" ||
opcode == "STX" ||
opcode == "SUB" ||
opcode == "TIX" ) {
give_label(operand);
p.is_labelled[hex2int(operand)] = true;
mark_code_data(p,hex2int(operand),WORD_DATA);
}
if ( opcode == "LDCH" ||
opcode == "STCH" ) {
give_label(operand);
p.is_labelled[hex2int(operand)] = true;
mark_code_data(p,hex2int(operand),CHAR_DATA);
}
if ( opcode == "J" ||
opcode == "JEQ" ||
opcode == "JGT" ||
opcode == "JLT" ||
opcode == "JSUB" ) {
give_label(operand);
p.is_labelled[hex2int(operand)] = true;
mark_code_data(p,hex2int(operand),CODE);
}
if ( opcode != "J" &&
opcode != "RSUB" ) {
mark_code_data(p,location+3,btg);
}
break;
}
}
}
void analyze_code_data(program &p) {
if ( p.name.length() == 0 ) {
fatal("No Header record");
}
if ( p.first_executable_instruction.length() == 0 ) {
fatal("No End record");
}
initialize_symtab();
add_to_symtab("FIRST",p.first_executable_instruction);
p.is_labelled[hex2int(p.first_executable_instruction)] = true;
mark_code_data(p,hex2int(p.first_executable_instruction),CODE);
}
string asm_to_line(string label, string opcode, string operand, bool is_indexed) {
const int labellength = 8;
const int opcodelength = 6;
string ret = "";
ret += label + string(labellength-label.length(),' ');
ret += opcode + string(opcodelength-opcode.length(),' ');
ret += operand;
if ( is_indexed ) {
ret += ",X";
}
ret += '\n';
return ret;
}
void write_assembly(const program &p, ofstream &ofile) {
ofile << asm_to_line(p.name,"START",p.starting_address,false);
int start_of_program = hex2int(p.starting_address);
int end_of_program = start_of_program + p.length_of_program;
for ( int locctr = start_of_program ; locctr < end_of_program ; ) {
string label = "";
string opcode = "";
string operand = "";
bool is_indexed = false;
if ( p.is_labelled[locctr] ) {
if ( !find_from_symtab(label,int2hex(locctr)) ) {
string errstr;
errstr += "Label not created for location ";
errstr += int2hex(locctr);
error(errstr);
}
}
if ( p.byte_type_guess[locctr] == CODE ) {
if ( ! find_from_symtab(opcode,byte2hex(p.memory[locctr])) ) {
string errstr;
errstr += "Unknown opcode ";
errstr += opcode;
errstr += " at location ";
errstr += int2hex(locctr);
fatal(errstr);
}
operand = byte2hex(p.memory[locctr+1])+byte2hex(p.memory[locctr+2]);
is_indexed = (hex2int(operand)&0x8000);
operand = int2hex(hex2int(operand)&0x7FFF); // remove index flag
if ( opcode != "RD" &&
opcode != "TD" &&
opcode != "WD" &&
opcode != "RSUB" ) {
if ( !find_from_symtab(operand,operand) ) {
string errstr;
errstr += "Label not created for operand ";
errstr += operand;
error(errstr);
}
}
if ( opcode == "RSUB" ) {
operand = "";
}
locctr += 3;
} else if ( p.byte_type_guess[locctr] == CHAR_DATA ||
p.byte_type_guess[locctr] == UNKNOWN ) {
if ( p.byte_type_guess[locctr] == UNKNOWN ) {
label = "UNUSED"; // This should not happen in a well written code
}
vector<char> byte_list;
bool type_c = true;
do {
byte_list.push_back(p.memory[locctr]);
if ( !isprint(p.memory[locctr]) ) {
type_c = false;
}
locctr++;
} while ( p.byte_type_guess[locctr] == CHAR_DATA && !p.is_labelled[locctr] );
opcode = "CHAR";
operand += (type_c?"C":"X");
operand += "'";
for ( int i = 0 ; i < (int)byte_list.size() ; i++ ) {
if ( type_c ) {
operand += byte_list[i];
} else {
operand += byte2hex(byte_list[i]);
}
}
operand += "'";
} else if ( p.byte_type_guess[locctr] == WORD_DATA ) {
opcode = "WORD";
operand = int2str(
p.memory[locctr+0]*256*256+
p.memory[locctr+1]*256+
p.memory[locctr+2]
);
locctr += 3;
} else if ( p.byte_type_guess[locctr] == UNINITIALIZED_CHAR_DATA ||
p.byte_type_guess[locctr] == UNINITIALIZED ) {
opcode = "RESB";
int buf_size = 0;
do {
buf_size++;
locctr++;
} while ( (p.byte_type_guess[locctr] == UNINITIALIZED_CHAR_DATA
|| p.byte_type_guess[locctr] == UNINITIALIZED)
&& !p.is_labelled[locctr]
&& locctr < end_of_program);
if ( locctr >= end_of_program ) {
buf_size--;
}
operand = int2str(buf_size);
} else if ( p.byte_type_guess[locctr] == UNINITIALIZED_WORD_DATA ) {
opcode = "RESW";
int buf_size = 0;
do {
buf_size++;
locctr+=3;
} while ( (p.byte_type_guess[locctr] == UNINITIALIZED_WORD_DATA
|| p.byte_type_guess[locctr] == UNINITIALIZED)
&& !p.is_labelled[locctr]
&& locctr < end_of_program);
if ( locctr >= end_of_program ) {
buf_size--;
}
operand = int2str(buf_size);
} else {
fatal("Reached part of decompiler that should not be reached");
}
ofile << asm_to_line(label,opcode,operand,is_indexed);
}
ofile << asm_to_line("","END","FIRST",false);
}<|endoftext|>
|
<commit_before>#include <iostream>
using namespace std;
class Message {
int myId;
public:
operator int() { return myId; }
Message(int id) : myId(id) {}
/*
equalTo - the Message Obect determines its equality with another message object. This may well be an == operator
*/
bool equalTo(int id) {
return id % myId == 0;
}
};
class HandlerBase {
Message myMessage;
protected:
HandlerBase *m_successor;
public:
HandlerBase(HandlerBase *s, Message *m) : m_successor(s), myMessage(*m) {}
void HandleMessage(Message *m) {
if(myMessage.equalTo(*m)) { // test equality with own message and handle it
cout << "Message " << *m << " got handled by " << myMessage << "\n";
} else if(m_successor) { // else hand over to next handler in line
cout << "Message " << *m << " got handed to successor" << "\n";
m_successor->HandleMessage(m);
} else { // or if this was the last handler, give up
cout << "Message " << *m << " had no handler" << "\n";
}
}
};
int main() {
Message m1(3), m2(5), m3(7), m4(4);
HandlerBase h1(0, &m1), h2(&h1,&m2), h3(&h2,&m3), h4(&h3,&m4); // create handler chain h4 <> h3 <> h2 <> h1
int m;
while(cin >> m) {
Message newMsg(m);
h4.HandleMessage(&newMsg);
}
return 0;
}
<commit_msg>Update chainresp_01.cpp<commit_after>#include <iostream>
using namespace std;
class Message {
protected:
int myId;
public:
operator int() { return myId; }
Message(int id) : myId(id) {}
/*
equalTo - the Message Obect determines its equality with another message object. This may well be an == operator
*/
virtual bool equalTo(int id) {
return id % myId == 0;
}
};
class HandlerBase {
Message myMessage;
protected:
HandlerBase *m_successor;
public:
HandlerBase(HandlerBase *s, Message *m) : m_successor(s), myMessage(*m) {}
virtual void HandleMessage(Message *m) {
if(myMessage.equalTo(*m)) { // test equality with own message and handle it
cout << "Message " << *m << " got handled by " << myMessage << "\n";
} else if(m_successor) { // else hand over to next handler in line
cout << "Message " << *m << " got handed to successor" << "\n";
m_successor->HandleMessage(m);
} else { // or if this was the last handler, give up
cout << "Message " << *m << " had no handler" << "\n";
}
}
};
int main() {
Message m1(3), m2(5), m3(7), m4(4);
HandlerBase h1(0, &m1), h2(&h1,&m2), h3(&h2,&m3), h4(&h3,&m4); // create handler chain h4 <> h3 <> h2 <> h1
int m;
while(cin >> m) {
Message newMsg(m);
h4.HandleMessage(&newMsg);
}
return 0;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: flt_reghelper.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: hr $ $Date: 2004-08-02 15:25:38 $
*
* 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 EXPRESS 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): Ocke Janssen
*
*
************************************************************************/
#ifndef _FLT_REGHELPER_HXX_
#define _FLT_REGHELPER_HXX_
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif
#ifndef _COM_SUN_STAR_REGISTRY_XREGISTRYKEY_HPP_
#include <com/sun/star/registry/XRegistryKey.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _CPPUHELPER_FACTORY_HXX_
#include <cppuhelper/factory.hxx>
#endif
namespace dbaxml
{
#define _REGISTRATIONHELPER_INCLUDED_INDIRECTLY_
#include "registrationhelper.hxx"
#undef _REGISTRATIONHELPER_INCLUDED_INDIRECTLY_
}
#endif // _FLT_REGHELPER_HXX_
<commit_msg>INTEGRATION: CWS ooo19126 (1.2.204); FILE MERGED 2005/09/05 17:33:00 rt 1.2.204.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: flt_reghelper.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-08 14:13:52 $
*
* 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 _FLT_REGHELPER_HXX_
#define _FLT_REGHELPER_HXX_
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif
#ifndef _COM_SUN_STAR_REGISTRY_XREGISTRYKEY_HPP_
#include <com/sun/star/registry/XRegistryKey.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _CPPUHELPER_FACTORY_HXX_
#include <cppuhelper/factory.hxx>
#endif
namespace dbaxml
{
#define _REGISTRATIONHELPER_INCLUDED_INDIRECTLY_
#include "registrationhelper.hxx"
#undef _REGISTRATIONHELPER_INCLUDED_INDIRECTLY_
}
#endif // _FLT_REGHELPER_HXX_
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: browserids.hxx,v $
*
* $Revision: 1.33 $
*
* last change: $Author: hr $ $Date: 2004-08-02 15:55:46 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the License); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an AS IS basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef DBACCESS_UI_BROWSER_ID_HXX
#define DBACCESS_UI_BROWSER_ID_HXX
#ifndef _SBASLTID_HRC
#include <svx/svxids.hrc>
#endif
#ifndef _DBACCESS_SLOTID_HRC_
#include "dbaccess_slotid.hrc"
#endif
#define ID_BROWSER_COPY SID_COPY
#define ID_BROWSER_CUT SID_CUT
#define ID_BROWSER_EDITDOC SID_EDITDOC
#define ID_BROWSER_UNDORECORD SID_FM_RECORD_UNDO
#define ID_BROWSER_SAVERECORD SID_FM_RECORD_SAVE
#define ID_BROWSER_PASTE SID_PASTE
#define ID_BROWSER_CLIPBOARD_FORMAT_ITEMS SID_CLIPBOARD_FORMAT_ITEMS
#define ID_BROWSER_REDO SID_REDO
#define ID_BROWSER_SAVEDOC SID_SAVEDOC
#define ID_BROWSER_SAVEASDOC SID_SAVEASDOC
#define ID_BROWSER_TITLE SID_DOCINFO_TITLE
#define ID_BROWSER_UNDO SID_UNDO
#define ID_BROWSER_INSERTCOLUMNS SID_SBA_BRW_INSERT
#define ID_BROWSER_FORMLETTER SID_SBA_BRW_MERGE
#define ID_BROWSER_INSERTCONTENT SID_SBA_BRW_UPDATE
#define ID_BROWSER_SEARCH SID_FM_SEARCH
#define ID_BROWSER_SORTUP SID_FM_SORTUP
#define ID_BROWSER_SORTDOWN SID_FM_SORTDOWN
#define ID_BROWSER_AUTOFILTER SID_FM_AUTOFILTER
#define ID_BROWSER_FILTERCRIT SID_FM_FILTERCRIT
#define ID_BROWSER_ORDERCRIT SID_FM_ORDERCRIT
#define ID_BROWSER_REMOVEFILTER SID_FM_REMOVE_FILTER_SORT
#define ID_BROWSER_FILTERED SID_FM_FORM_FILTERED
#define ID_BROWSER_REFRESH SID_FM_REFRESH
#define ID_BROWSER_EXPL_PREVLEVEL SID_EXPLORER_PREVLEVEL
#define ID_BROWSER_COLATTRSET 20 // Spaltenformatierung
#define ID_BROWSER_COLWIDTH 21 // Spaltenbreite
#define ID_BROWSER_TABLEATTR 22 // table format attributes
#define ID_BROWSER_ROWHEIGHT 23 // Zeilenhoehe
#define ID_BROWSER_COLUMNINFO 24 // copies the column description to insert it into the table design
#define ID_BROWSER_COUNTALL SID_FM_COUNTALL // count all
#define ID_BROWSER_ADDTABLE SID_FM_ADDTABLE
#define ID_BROWSER_DESIGN SID_SBA_QRY_DESIGN
#define ID_BROWSER_EXPLORER SID_DSBROWSER_EXPLORER
#define ID_BROWSER_DOCUMENT_DATASOURCE SID_DOCUMENT_DATA_SOURCE
// The following ids are local to special components (e.g. menus), so they don't need to be unique
// overall. Please have this in mind when changing anything
#define ID_TREE_ADMINISTRATE 1
#define ID_TREE_CLOSE_CONN 2
#define ID_TREE_REBUILD_CONN 3
#define ID_TREE_RELATION_DESIGN 7
#define ID_TABLE_DESIGN_NO_CONNECTION 8
#define ID_OPEN_DOCUMENT 9
#define ID_EDIT_DOCUMENT 10
// free
// free
// free
#define ID_CREATE_NEW_DOC 14
#define ID_FORM_NEW_TEXT 15
#define ID_FORM_NEW_CALC 16
#define ID_FORM_NEW_IMPRESS 17
#define ID_FORM_NEW_PILOT 18
#define ID_FORM_NEW_TEMPLATE 19
#define ID_NEW_QUERY_DESIGN 20
#define ID_EDIT_QUERY_DESIGN 21
#define ID_NEW_QUERY_SQL 22
#define ID_EDIT_QUERY_SQL 23
#define ID_DROP_QUERY 24
#define ID_NEW_TABLE_DESIGN 25
#define ID_EDIT_TABLE 26
#define ID_DROP_TABLE 27
#define ID_NEW_VIEW_DESIGN 28
#define ID_DIRECT_SQL 32
#define ID_BROWSER_REFRESH_REBUILD 34
#define ID_RENAME_ENTRY 35
#define ID_INDEX_NEW 36
#define ID_INDEX_DROP 37
#define ID_INDEX_RENAME 38
#define ID_INDEX_SAVE 39
#define ID_INDEX_RESET 40
#define ID_DOCUMENT_CREATE_REPWIZ 41
#define ID_BROWSER_SQL 42
#define ID_APP_NEW_FORM 43
#define ID_APP_NEW_QUERY_AUTO_PILOT 44
#define ID_NEW_TABLE_DESIGN_AUTO_PILOT 45
#define ID_NEW_VIEW_DESIGN_AUTO_PILOT 46
#define ID_NEW_VIEW_SQL 47
#define ID_DOCUMENT_CREATE_REPWIZ_PRE_SEL 48
#define ID_FORM_NEW_PILOT_PRE_SEL 49
#define ID_APP_NEW_FOLDER 50
// image ids
#define SID_DB_FORM_DELETE 65
#define SID_DB_FORM_RENAME 66
#define SID_DB_FORM_EDIT 67
#define SID_DB_FORM_OPEN 68
#define SID_DB_REPORT_DELETE 69
#define SID_DB_REPORT_RENAME 70
#define SID_DB_REPORT_EDIT 71
#define SID_DB_REPORT_OPEN 72
#define SID_DB_QUERY_OPEN 73
#define SID_DB_TABLE_OPEN 74
#define SID_DB_QUERY_EDIT 75
// other
#define ID_BROWSER_QUERY_EXECUTE SID_FM_EXECUTE
#define ID_BROWSER_CLEAR_QUERY SID_SBA_CLEAR_QUERY
#define ID_RELATION_ADD_RELATION SID_SBA_ADD_RELATION
#define ID_BROWSER_QUERY_VIEW_FUNCTIONS SID_SBA_QUERY_VIEW_FUNCTIONS
#define ID_BROWSER_QUERY_VIEW_TABLES SID_SBA_QUERY_VIEW_TABLES
#define ID_BROWSER_QUERY_VIEW_ALIASES SID_SBA_QUERY_VIEW_ALIASES
#define ID_BROWSER_QUERY_DISTINCT_VALUES SID_SBA_QUERY_DISTINCT_VALUES
#define ID_BROWSER_CLOSE SID_CLOSEWIN
#define ID_BROWSER_ESACPEPROCESSING SID_FM_NATIVESQL
#define ID_QUERY_FUNCTION (SID_SBA_START + 41) // Funktionen anzeigen
#define ID_QUERY_TABLENAME (SID_SBA_START + 42) // Tabellennamen anzeigen
#define ID_QUERY_ALIASNAME (SID_SBA_START + 43) // Aliasnamen anzeigen
#define ID_QUERY_DISTINCT (SID_SBA_START + 44) // Distinct anzeigen
#define ID_QUERY_EDIT_JOINCONNECTION (SID_SBA_START + 45) // show-edit Join
#define ID_QUERY_ZOOM_IN SID_ZOOM_IN
#define ID_QUERY_ZOOM_OUT SID_ZOOM_OUT
#endif // DBACCESS_UI_BROWSER_ID_HXX
<commit_msg>INTEGRATION: CWS insight02 (1.33.2); FILE MERGED 2004/08/13 14:28:19 oj 1.33.2.2: #i32563# toolbox changes 2004/08/13 08:52:54 oj 1.33.2.1: #i32563# toolbox changes<commit_after>/*************************************************************************
*
* $RCSfile: browserids.hxx,v $
*
* $Revision: 1.34 $
*
* last change: $Author: rt $ $Date: 2004-09-09 09:44:38 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the License); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an AS IS basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef DBACCESS_UI_BROWSER_ID_HXX
#define DBACCESS_UI_BROWSER_ID_HXX
#ifndef _SBASLTID_HRC
#include <svx/svxids.hrc>
#endif
#ifndef _DBACCESS_SLOTID_HRC_
#include "dbaccess_slotid.hrc"
#endif
#define ID_BROWSER_COPY SID_COPY
#define ID_BROWSER_CUT SID_CUT
#define ID_BROWSER_EDITDOC SID_EDITDOC
#define ID_BROWSER_UNDORECORD SID_FM_RECORD_UNDO
#define ID_BROWSER_SAVERECORD SID_FM_RECORD_SAVE
#define ID_BROWSER_PASTE SID_PASTE
#define ID_BROWSER_CLIPBOARD_FORMAT_ITEMS SID_CLIPBOARD_FORMAT_ITEMS
#define ID_BROWSER_REDO SID_REDO
#define ID_BROWSER_SAVEDOC SID_SAVEDOC
#define ID_BROWSER_SAVEASDOC SID_SAVEASDOC
#define ID_BROWSER_TITLE SID_DOCINFO_TITLE
#define ID_BROWSER_UNDO SID_UNDO
#define ID_BROWSER_INSERTCOLUMNS SID_SBA_BRW_INSERT
#define ID_BROWSER_FORMLETTER SID_SBA_BRW_MERGE
#define ID_BROWSER_INSERTCONTENT SID_SBA_BRW_UPDATE
#define ID_BROWSER_SEARCH SID_FM_SEARCH
#define ID_BROWSER_SORTUP SID_FM_SORTUP
#define ID_BROWSER_SORTDOWN SID_FM_SORTDOWN
#define ID_BROWSER_AUTOFILTER SID_FM_AUTOFILTER
#define ID_BROWSER_FILTERCRIT SID_FM_FILTERCRIT
#define ID_BROWSER_ORDERCRIT SID_FM_ORDERCRIT
#define ID_BROWSER_REMOVEFILTER SID_FM_REMOVE_FILTER_SORT
#define ID_BROWSER_FILTERED SID_FM_FORM_FILTERED
#define ID_BROWSER_REFRESH SID_FM_REFRESH
#define ID_BROWSER_EXPL_PREVLEVEL SID_EXPLORER_PREVLEVEL
#define ID_BROWSER_COLATTRSET 20 // Spaltenformatierung
#define ID_BROWSER_COLWIDTH 21 // Spaltenbreite
#define ID_BROWSER_TABLEATTR 22 // table format attributes
#define ID_BROWSER_ROWHEIGHT 23 // Zeilenhoehe
#define ID_BROWSER_COLUMNINFO 24 // copies the column description to insert it into the table design
#define ID_BROWSER_COUNTALL SID_FM_COUNTALL // count all
#define ID_BROWSER_ADDTABLE SID_FM_ADDTABLE
#define ID_BROWSER_EXPLORER SID_DSBROWSER_EXPLORER
#define ID_BROWSER_DOCUMENT_DATASOURCE SID_DOCUMENT_DATA_SOURCE
// The following ids are local to special components (e.g. menus), so they don't need to be unique
// overall. Please have this in mind when changing anything
#define ID_TREE_ADMINISTRATE 1
#define ID_TREE_CLOSE_CONN 2
#define ID_TREE_REBUILD_CONN 3
// free
// free
// free
// free
#define ID_FORM_NEW_TEXT 15
#define ID_FORM_NEW_CALC 16
#define ID_FORM_NEW_IMPRESS 17
#define ID_FORM_NEW_PILOT 18
#define ID_NEW_QUERY_DESIGN 20
#define ID_EDIT_QUERY_DESIGN 21
#define ID_NEW_QUERY_SQL 22
#define ID_EDIT_QUERY_SQL 23
#define ID_NEW_TABLE_DESIGN 25
#define ID_NEW_VIEW_DESIGN 28
#define ID_DIRECT_SQL 32
#define ID_BROWSER_REFRESH_REBUILD 34
#define ID_INDEX_NEW 36
#define ID_INDEX_DROP 37
#define ID_INDEX_RENAME 38
#define ID_INDEX_SAVE 39
#define ID_INDEX_RESET 40
#define ID_DOCUMENT_CREATE_REPWIZ 41
#define ID_BROWSER_SQL 42
#define ID_APP_NEW_QUERY_AUTO_PILOT 44
#define ID_NEW_TABLE_DESIGN_AUTO_PILOT 45
#define ID_NEW_VIEW_DESIGN_AUTO_PILOT 46
#define ID_NEW_VIEW_SQL 47
// other
#define ID_BROWSER_QUERY_EXECUTE SID_FM_EXECUTE
#define ID_BROWSER_CLOSE SID_CLOSEWIN
#define ID_BROWSER_ESACPEPROCESSING SID_FM_NATIVESQL
#define ID_QUERY_FUNCTION (SID_SBA_START + 41) // Funktionen anzeigen
#define ID_QUERY_TABLENAME (SID_SBA_START + 42) // Tabellennamen anzeigen
#define ID_QUERY_ALIASNAME (SID_SBA_START + 43) // Aliasnamen anzeigen
#define ID_QUERY_DISTINCT (SID_SBA_START + 44) // Distinct anzeigen
#define ID_QUERY_EDIT_JOINCONNECTION (SID_SBA_START + 45) // show-edit Join
#define ID_QUERY_ZOOM_IN SID_ZOOM_IN
#define ID_QUERY_ZOOM_OUT SID_ZOOM_OUT
#endif // DBACCESS_UI_BROWSER_ID_HXX
<|endoftext|>
|
<commit_before>#include <cassert>
#include <ostream>
#include <exception>
#include "vm.hh"
#include "env.hh"
#include "printer.hh"
#include "zs_memory.hh"
VM vm;
VM::VM() : code(), stack(),
return_value(1, {}),
extent(),
symtable(),
frame(nullptr),
exception_handler()
{}
VM::VM(const VM& other) : code(other.code), stack(other.stack),
return_value(other.return_value),
extent(other.extent),
symtable(other.symtable),
frame(other.frame),
exception_handler(other.exception_handler)
{}
VM::~VM(){}
VM& VM::operator=(const VM& other){
code = other.code;
stack = other.stack;
return_value = other.return_value;
extent = other.extent,
symtable = other.symtable;
frame = other.frame;
exception_handler = other.exception_handler;
return *this;
}
std::ostream& operator<<(std::ostream& f, const VM& v){
f << "--- [code] ---\n";
for(auto i = v.code.rbegin(), e = v.code.rend(); i != e; ++i){
f << *i << '\n';
}
f << "--- [stack] ---\n";
for(auto i = v.stack.rbegin(), e = v.stack.rend(); i != e; ++i){
f << *i << '\n';
}
f << "--- [return value] ---\n";
f << '[' << v.return_value.size() << "] ";
for(auto i = v.return_value.begin(), e = v.return_value.end(); i != e; ++i){
f << '\t' << *i << '\n';
}
if(!v.extent.empty()){
f << "--- [extent] ---\n";
for(auto i = v.extent.begin(), e = v.extent.end(); i != e; ++i){
f << i->thunk << ": " << i->before << ", " << i->after << "\n";
}
}
// f << "--- [env] ---\n";
// f << *v.frame_;
// f << "--- [symtable] ---\n";
// f << *v.symtable_;
if(!v.exception_handler.empty()){
f << "--- [exception handler] ---\n";
for(auto i = v.exception_handler.rbegin(), e = v.exception_handler.rend(); i != e; ++i){
f << *i << "\n";
}
}
f << "\n\n";
return f;
}
// class ZsArgs
// - invalidate() :: marks as unusable.
// - cleanup() :: destroys vm's arguments really.
ZsArgs::ZsArgs()
: size_(vm.stack.back().get<int>()),
stack_iter_s_(vm.stack.end() - (size_ + 1)){}
ZsArgs::ZsArgs(ZsArgs&& other)
: size_(other.size_),
stack_iter_s_(move(other.stack_iter_s_)){
other.invalidate();
}
ZsArgs::~ZsArgs(){
cleanup();
}
ZsArgs& ZsArgs::operator=(ZsArgs&& other){
size_ = other.size_;
stack_iter_s_ = move(other.stack_iter_s_);
other.invalidate();
return *this;
}
void ZsArgs::cleanup(){
if(size_ < 0) return;
if(!std::uncaught_exception()){
vm.stack.erase(this->begin(), this->end() + 1);
invalidate();
}
}
inline
void ZsArgs::invalidate(){
size_ = -1;
}
inline
bool ZsArgs::valid() const{
return (size_ >= 0);
}
<commit_msg>cleanup vm.cc<commit_after>#include <cassert>
#include <ostream>
#include <exception>
#include "vm.hh"
#include "env.hh"
#include "printer.hh"
#include "zs_memory.hh"
VM vm;
VM::VM() : code(), stack(),
return_value(1, {}),
extent(),
symtable(),
frame(nullptr),
exception_handler()
{}
VM::VM(const VM&) = default;
VM::~VM() = default;
VM& VM::operator=(const VM&) = default;
std::ostream& operator<<(std::ostream& f, const VM& v){
f << "--- [code] ---\n";
for(auto i = v.code.rbegin(), e = v.code.rend(); i != e; ++i){
f << *i << '\n';
}
f << "--- [stack] ---\n";
for(auto i = v.stack.rbegin(), e = v.stack.rend(); i != e; ++i){
f << *i << '\n';
}
f << "--- [return value] ---\n";
f << '[' << v.return_value.size() << "] ";
for(auto i = v.return_value.begin(), e = v.return_value.end(); i != e; ++i){
f << '\t' << *i << '\n';
}
if(!v.extent.empty()){
f << "--- [extent] ---\n";
for(auto i = v.extent.begin(), e = v.extent.end(); i != e; ++i){
f << i->thunk << ": " << i->before << ", " << i->after << "\n";
}
}
// f << "--- [env] ---\n";
// f << *v.frame_;
// f << "--- [symtable] ---\n";
// f << *v.symtable_;
if(!v.exception_handler.empty()){
f << "--- [exception handler] ---\n";
for(auto i = v.exception_handler.rbegin(), e = v.exception_handler.rend(); i != e; ++i){
f << *i << "\n";
}
}
f << "\n\n";
return f;
}
// class ZsArgs
// - invalidate() :: marks as unusable.
// - cleanup() :: destroys vm's arguments really.
ZsArgs::ZsArgs()
: size_(vm.stack.back().get<int>()),
stack_iter_s_(vm.stack.end() - (size_ + 1)){}
ZsArgs::ZsArgs(ZsArgs&& other)
: size_(other.size_),
stack_iter_s_(move(other.stack_iter_s_)){
other.invalidate();
}
ZsArgs::~ZsArgs(){
cleanup();
}
ZsArgs& ZsArgs::operator=(ZsArgs&& other){
size_ = other.size_;
stack_iter_s_ = move(other.stack_iter_s_);
other.invalidate();
return *this;
}
void ZsArgs::cleanup(){
if(size_ < 0) return;
if(!std::uncaught_exception()){
vm.stack.erase(this->begin(), this->end() + 1);
invalidate();
}
}
inline
void ZsArgs::invalidate(){
size_ = -1;
}
inline
bool ZsArgs::valid() const{
return (size_ >= 0);
}
<|endoftext|>
|
<commit_before>#include "CppLINQ.h"
#include <iostream>
#include <string>
int main()
{
using namespace LL;
struct PetOwner
{
PetOwner() = default;
PetOwner(const std::string &name, const std::vector<std::string> &pets, const std::vector<int> &num)
:name_(name), pets_(pets), num_(num) {};
std::string name_;
std::vector<std::string> pets_;
std::vector<int> num_;
};
std::vector<PetOwner> vp{ PetOwner("higa", std::vector<std::string>{std::string("scruffy"), std::string("sam")}, std::vector<int>{10,20,30}), PetOwner("ronen", std::vector<std::string>{std::string("walker"), std::string("sugar")}, std::vector<int>{40,50,60}) };
auto s = from(vp).select_many([](PetOwner i) {return i.pets_; });
std::vector<std::vector<int>> a{ std::vector<int>{1,2},std::vector<int>{4,5,6,7},std::vector<int>{8,10,11,12} };
std::vector<int> a1{ 1, 2, 3, 4, 5, 6 };
std::vector<int> a3{};
std::vector<float> a2{ 123.456f };
std::vector<int> a4{ 1,2,2,3,4,4,10 };
auto b = from(a1);
auto c = from(a1).skip(2);
auto e = b.concat(c);
auto f = from(a4).distinct().linq_union(from(a4));
auto g = from(a3).default_if_empty();
//auto b = from(a).select_many([](auto i) {return i; }).to_vector();
//auto d = from(a2).cast<std::string>();
//for(auto ele:b)
//std::cout << ele << std::endl;
//for (auto ele : e)
//std::cout << ele << std::endl;
for (auto ele : s)
{
std::cout << ele << std::endl;
}
//std::cout << c.last_or_default([](auto i) {return i < 0; }) << std::endl;
}
<commit_msg>add test<commit_after>#ifdef _MSC_VER
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#endif
#include "CppLINQ.h"
#include <iostream>
#include <string>
#include <assert.h>
#include <algorithm>
using namespace LL;
struct PetOwner
{
PetOwner() = default;
PetOwner(const std::string &name, const std::vector<std::string> &pets, const std::vector<int> &num)
:name_(name), pets_(pets), num_(num) {};
std::string name_;
std::vector<std::string> pets_;
std::vector<int> num_;
};
void test()
{
//////////////////////////////////////////////////////////////////
// from
//////////////////////////////////////////////////////////////////
{
std::vector<int> xs = { 1, 2, 3, 4, 5 };
int sum = 0;
for (auto x : from(xs.begin(), xs.end()))
{
sum += x;
}
assert(sum == 15);
}
{
std::vector<int> xs = { 1, 2, 3, 4, 5 };
int sum = 0;
for (auto x : from(xs))
{
sum += x;
}
assert(sum == 15);
}
{
int xs[] = { 1, 2, 3, 4, 5 };
int sum = 0;
for (auto x : from(from(from(xs))))
{
sum += x;
}
assert(sum == 15);
}
//////////////////////////////////////////////////////////////////
// select
//////////////////////////////////////////////////////////////////
{
int xs[] = { 1, 2, 3, 4, 5 };
assert(from(xs).select([](int x){return x * 2; }).sequence_equal({ 2, 4, 6, 8, 10 }));
}
//////////////////////////////////////////////////////////////////
// hide type test
//////////////////////////////////////////////////////////////////
{
//int xs[] = { 1, 2, 3, 4, 5 };
//linq<int> hidden = from(xs).select([](int x){return x * 2; });
//assert(hidden.sequence_equal({ 2, 4, 6, 8, 10 }));
}
//////////////////////////////////////////////////////////////////
// where
//////////////////////////////////////////////////////////////////
{
int xs[] = { 1, 2, 3, 4, 5 };
assert(from(xs).where([](int x){return x % 2 == 0; }).sequence_equal({ 2, 4 }));
}
//////////////////////////////////////////////////////////////////
// iterating
//////////////////////////////////////////////////////////////////
{
std::vector<int> empty;
int xs[] = { 1, 2, 3, 4, 5 };
int ys[] = { 1, 2, 3 };
int zs[] = { 4, 5 };
assert(from(xs).take(3).sequence_equal(ys));
assert(from(xs).skip(3).sequence_equal(zs));
assert(from(xs).take_while([](int a){return a != 4; }).sequence_equal(ys));
assert(from(xs).skip_while([](int a){return a != 4; }).sequence_equal(zs));
assert(from(xs).take(0).sequence_equal(empty));
assert(from(xs).skip(5).sequence_equal(empty));
assert(from(ys).concat(from(zs)).sequence_equal(xs));
assert(from(xs).concat(from(empty)).sequence_equal(xs));
assert(from(empty).concat(from(xs)).sequence_equal(xs));
assert(from(empty).concat(from(empty)).sequence_equal(empty));
assert(from(ys).concat(zs).sequence_equal(xs));
assert(from(xs).concat(empty).sequence_equal(xs));
assert(from(empty).concat(xs).sequence_equal(xs));
assert(from(empty).concat(empty).sequence_equal(empty));
}
//////////////////////////////////////////////////////////////////
// counting
//////////////////////////////////////////////////////////////////
{
int a[] = { 1, 2, 3, 4, 5 };
std::vector<int> b = { 1, 2, 3, 4, 5 };
std::vector<int> c;
int d[] = { 1, 2, 3, 4 };
int e[] = { 1, 2, 3, 4, 5, 6 };
int f[] = { 6, 7, 8, 9, 10 };
int g[] = { 0 };
//linq<int> xs[] = { from(b), from(c), from(d), from(e), from(f) };
//assert(from(a).sequence_equal(b));
//for (auto& x : xs)
//{
//for (auto& y : xs)
//{
//assert(x.sequence_equal(y) == (&x == &y));
//}
//}
assert(from(a).contains(1));
assert(from(a).contains(5));
assert(!from(a).contains(6));
assert(!from(c).contains(6));
assert(from(a).count() == 5);
assert(from(c).count() == 0);
assert(from(a).default_if_empty(0).sequence_equal(b));
assert(from(c).default_if_empty(0).sequence_equal(g));
assert(from(a).element_at(0) == 1);
assert(from(a).element_at(4) == 5);
try{ from(a).element_at(-1); assert(false); }
catch (const linq_exception&){}
try{ from(a).element_at(6); assert(false); }
catch (const linq_exception&){}
try{ from(c).element_at(0); assert(false); }
catch (const linq_exception&){}
assert(!from(a).empty());
assert(from(c).empty());
assert(from(a).first() == 1);
assert(from(a).first_or_default() == 1);
assert(from(a).last() == 5);
assert(from(a).last_or_default() == 5);
assert(from(c).first_or_default() == 0);
assert(from(c).last_or_default() == 0);
try{ from(c).first(); assert(false); }
catch (const linq_exception&){}
try{ from(c).last(); assert(false); }
catch (const linq_exception&){}
assert(from(c).single_or_default() == 0);
assert(from(g).single() == 0);
try{ from(a).single(); assert(false); }
catch (const linq_exception&){}
try{ from(a).single_or_default(); assert(false); }
catch (const linq_exception&){}
try{ from(c).single(); assert(false); }
catch (const linq_exception&){}
}
//////////////////////////////////////////////////////////////////
// containers
//////////////////////////////////////////////////////////////////
{
int xs[] = { 1, 2, 3, 4, 5 };
assert(from(xs).sequence_equal(from(xs).to_vector()));
assert(from(xs).sequence_equal(from(xs).to_list()));
assert(from(xs).sequence_equal(from(xs).to_set()));
auto f = [](int x){return x; };
assert(from(xs).sequence_equal(from(from(xs).to_map(f, f)).select([](std::pair<int, int> p){return p.first; })));
assert(from(xs).sequence_equal(from(from(xs).to_map(f, f)).select([](std::pair<int, int> p){return p.second; })));
}
//////////////////////////////////////////////////////////////////
// aggregating
//////////////////////////////////////////////////////////////////
{
int xs[] = { 1, 2, 3, 4, 5 };
assert(from(xs).aggregate([](int a, int b){return a + b; }) == 15);
assert(from(xs).aggregate(0, [](int a, int b){return a + b; }) == 15);
assert(from(xs).sum() == 15);
assert(from(xs).aggregate([](int a, int b){return a * b; }) == 120);
assert(from(xs).aggregate(1, [](int a, int b){return a * b; }) == 120);
assert(from(xs).all([](int a){return a > 1; }) == false);
assert(from(xs).all([](int a){return a > 0; }) == true);
assert(from(xs).any([](int a){return a > 1; }) == true);
assert(from(xs).any([](int a){return a > 0; }) == true);
assert(from(xs).min() == 1);
assert(from(xs).max() == 5);
assert(from(xs).average() == 3);
std::vector<int> ys;
try{ from(ys).min(); assert(false); }
catch (const linq_exception&){}
try{ from(ys).max(); assert(false); }
catch (const linq_exception&){}
try{ from(ys).average(); assert(false); }
catch (const linq_exception&){}
}
//////////////////////////////////////////////////////////////////
// set
//////////////////////////////////////////////////////////////////
{
int xs[] = { 1, 1, 2, 2, 3, 3 };
int ys[] = { 2, 2, 3, 3, 4, 4 };
assert(from(xs).distinct().sequence_equal({ 1, 2, 3 }));
assert(from(ys).distinct().sequence_equal({ 2, 3, 4 }));
//assert(from(xs).except_with(ys).sequence_equal({ 1 }));
//assert(from(xs).intersect_with(ys).sequence_equal({ 2, 3 }));
//assert(from(xs).union_with(ys).sequence_equal({ 1, 2, 3, 4 }));
}
//////////////////////////////////////////////////////////////////
// restructuring
//////////////////////////////////////////////////////////////////
{
int xs[] = { 1, 2, 3, 4, 5 };
int ys[] = { 6, 7, 8, 9, 10 };
//zip_pair<int, int> zs[] = { { 1, 6 }, { 2, 7 }, { 3, 8 }, { 4, 9 }, { 5, 10 } };
//assert(from(xs).zip_with(ys).sequence_equal(zs));
//auto g = from(xs).group_by([](int x){return x % 2; });
//assert(g.select([](zip_pair<int, linq<int>> p){return p.first; }).sequence_equal({ 0, 1 }));
//assert(g.first().second.sequence_equal({ 2, 4 }));
//assert(g.last().second.sequence_equal({ 1, 3, 5 }));
//assert(
//from_values({ 1, 2, 3 })
//.select_many([](int x){return from_values({ x, x*x, x*x*x }); })
//.sequence_equal({ 1, 1, 1, 2, 4, 8, 3, 9, 27 })
//);
}
//////////////////////////////////////////////////////////////////
// ordering
//////////////////////////////////////////////////////////////////
{
//int xs[] = { 7, 1, 12, 2, 8, 3, 11, 4, 9, 5, 13, 6, 10 };
//int ys[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 };
//int zs[] = { 10, 1, 11, 2, 12, 3, 13, 4, 5, 6, 7, 8, 9 };
//assert(from(xs).order_by([](int x){return x; }).sequence_equal(ys));
//assert(
//flatten(
//from(xs)
//.first_order_by([](int x){return x % 10; })
//.then_order_by([](int x){return x / 10; })
//)
//.sequence_equal(zs)
//);
}
//////////////////////////////////////////////////////////////////
// joining
//////////////////////////////////////////////////////////////////
{
//person magnus = { "Hedlund, Magnus" };
//person terry = { "Adams, Terry" };
//person charlotte = { "Weiss, Charlotte" };
//person persons[] = { magnus, terry, charlotte };
//pet barley = { "Barley", terry };
//pet boots = { "Boots", terry };
//pet whiskers = { "Whiskers", charlotte };
//pet daisy = { "Daisy", magnus };
//pet pets[] = { barley, boots, whiskers, daisy };
//auto person_name = [](const person& p){return p.name; };
//auto pet_name = [](const pet& p){return p.name; };
//auto pet_owner_name = [](const pet& p){return p.owner.name; };
//auto f = from(persons).full_join(from(pets), person_name, pet_owner_name);
//{
//typedef join_pair<string, linq<person>, linq<pet>> TItem;
//auto xs = f.to_vector();
//assert(from(xs).select([](const TItem& item){return item.first; }).sequence_equal({ terry.name, magnus.name, charlotte.name }));
//assert(xs[0].second.first.select(person_name).sequence_equal({ terry.name }));
//assert(xs[1].second.first.select(person_name).sequence_equal({ magnus.name }));
//assert(xs[2].second.first.select(person_name).sequence_equal({ charlotte.name }));
//assert(xs[0].second.second.select(pet_name).sequence_equal({ barley.name, boots.name }));
//assert(xs[1].second.second.select(pet_name).sequence_equal({ daisy.name }));
//assert(xs[2].second.second.select(pet_name).sequence_equal({ whiskers.name }));
//}
//auto g = from(persons).group_join(from(pets), person_name, pet_owner_name);
//{
//typedef join_pair<string, person, linq<pet>> TItem;
//auto xs = g.to_vector();
//assert(from(xs).select([](const TItem& item){return item.first; }).sequence_equal({ terry.name, magnus.name, charlotte.name }));
//assert(xs[0].second.first.name == terry.name);
//assert(xs[1].second.first.name == magnus.name);
//assert(xs[2].second.first.name == charlotte.name);
//assert(xs[0].second.second.select(pet_name).sequence_equal({ barley.name, boots.name }));
//assert(xs[1].second.second.select(pet_name).sequence_equal({ daisy.name }));
//assert(xs[2].second.second.select(pet_name).sequence_equal({ whiskers.name }));
//}
//auto j = from(persons).join(from(pets), person_name, pet_owner_name);
//{
//typedef join_pair<string, person, pet> TItem;
//auto xs = j.to_vector();
//assert(from(xs).select([](const TItem& item){return item.first; }).sequence_equal({ terry.name, terry.name, magnus.name, charlotte.name }));
//assert(xs[0].second.first.name == terry.name);
//assert(xs[1].second.first.name == terry.name);
//assert(xs[2].second.first.name == magnus.name);
//assert(xs[3].second.first.name == charlotte.name);
//assert(xs[0].second.second.name == barley.name);
//assert(xs[1].second.second.name == boots.name);
//assert(xs[2].second.second.name == daisy.name);
//assert(xs[3].second.second.name == whiskers.name);
}
}
int main()
{
test();
{
// calculate sum of squares of odd numbers
int xs[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = from(xs)
.where([](int x){return x % 2 == 1; })
.select([](int x){return x * x; })
.sum();
std::cout << sum << std::endl;
assert(sum == 165);
}
{
// iterate of squares of odd numbers ordered by the last digit
std::vector<int> xs = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
for (auto x : from(xs)
.where([](int x){return x % 2 == 1; })
.select([](int x){return x * x; })
)
{
std::cout << x << " ";
}
// prints 1 81 25 9 49
}
{
std::vector<PetOwner> vp{ PetOwner("higa", std::vector<std::string>{std::string("scruffy"), std::string("sam")}, std::vector<int>{10,20,30}), PetOwner("ronen", std::vector<std::string>{std::string("walker"), std::string("sugar")}, std::vector<int>{40,50,60}) };
auto xs = from(vp).select_many([](PetOwner i) {return i.pets_; });
for (auto ele : xs)
{
std::cout << ele << std::endl;
}
std::vector<std::string> result {"scruffy", "sam", "walker", "sugar"};
assert(xs.to_vector() == result);
}
#ifdef _MSC_VER
_CrtDumpMemoryLeaks();
#endif
return 0;
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm.h"
#include "SkCanvas.h"
#include "SkPath.h"
#include "SkGradientShader.h"
#include "SkTypeface.h"
static SkShader* make_heatGradient(const SkPoint pts[2]) {
const SkColor colors[] = {
SK_ColorBLACK, SK_ColorBLUE, SK_ColorCYAN, SK_ColorGREEN,
SK_ColorYELLOW, SK_ColorRED, SK_ColorWHITE
};
const SkColor bw[] = { SK_ColorBLACK, SK_ColorWHITE };
return SkGradientShader::CreateLinear(pts, bw, NULL,
SK_ARRAY_COUNT(bw),
SkShader::kClamp_TileMode);
}
static bool setFont(SkPaint* paint, const char name[]) {
SkTypeface* tf = SkTypeface::CreateFromName(name, SkTypeface::kNormal);
if (tf) {
paint->setTypeface(tf)->unref();
return true;
}
return false;
}
#ifdef SK_BUILD_FOR_MAC
#import <ApplicationServices/ApplicationServices.h>
#define BITMAP_INFO_RGB (kCGImageAlphaNoneSkipFirst | kCGBitmapByteOrder32Host)
static CGContextRef makeCG(const SkBitmap& bm) {
if (SkBitmap::kARGB_8888_Config != bm.config() ||
NULL == bm.getPixels()) {
return NULL;
}
CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();
CGContextRef cg = CGBitmapContextCreate(bm.getPixels(), bm.width(), bm.height(),
8, bm.rowBytes(), space, BITMAP_INFO_RGB);
CFRelease(space);
CGContextSetAllowsFontSubpixelQuantization(cg, false);
CGContextSetShouldSubpixelQuantizeFonts(cg, false);
return cg;
}
extern CTFontRef SkTypeface_GetCTFontRef(const SkTypeface* face);
static CGFontRef typefaceToCGFont(const SkTypeface* face) {
if (NULL == face) {
return 0;
}
CTFontRef ct = SkTypeface_GetCTFontRef(face);
return CTFontCopyGraphicsFont(ct, NULL);
}
static void cgSetPaintForText(CGContextRef cg, const SkPaint& paint) {
SkColor c = paint.getColor();
CGFloat rgba[] = {
SkColorGetB(c) / 255.0,
SkColorGetG(c) / 255.0,
SkColorGetR(c) / 255.0,
SkColorGetA(c) / 255.0,
};
CGContextSetRGBFillColor(cg, rgba[0], rgba[1], rgba[2], rgba[3]);
CGContextSetTextDrawingMode(cg, kCGTextFill);
CGContextSetFont(cg, typefaceToCGFont(paint.getTypeface()));
CGContextSetFontSize(cg, SkScalarToFloat(paint.getTextSize()));
CGContextSetAllowsFontSubpixelPositioning(cg, paint.isSubpixelText());
CGContextSetShouldSubpixelPositionFonts(cg, paint.isSubpixelText());
CGContextSetShouldAntialias(cg, paint.isAntiAlias());
CGContextSetShouldSmoothFonts(cg, paint.isLCDRenderText());
}
static void cgDrawText(CGContextRef cg, const void* text, size_t len,
float x, float y, const SkPaint& paint) {
if (cg) {
cgSetPaintForText(cg, paint);
uint16_t glyphs[200];
int count = paint.textToGlyphs(text, len, glyphs);
CGContextShowGlyphsAtPoint(cg, x, y, glyphs, count);
}
}
#endif
namespace skiagm {
/**
Test a set of clipping problems discovered while writing blitAntiRect,
and test all the code paths through the clipping blitters.
Each region should show as a blue center surrounded by a 2px green
border, with no red.
*/
#define HEIGHT 480
class GammaTextGM : public GM {
public:
GammaTextGM() {
}
protected:
virtual SkString onShortName() {
return SkString("gammatext");
}
virtual SkISize onISize() {
return make_isize(1024, HEIGHT);
}
static void drawGrad(SkCanvas* canvas) {
SkPoint pts[] = { { 0, 0 }, { 0, SkIntToScalar(HEIGHT) } };
#if 0
const SkColor colors[] = { SK_ColorBLACK, SK_ColorWHITE };
SkShader* s = SkGradientShader::CreateLinear(pts, colors, NULL, 2, SkShader::kClamp_TileMode);
#else
SkShader* s = make_heatGradient(pts);
#endif
canvas->clear(SK_ColorRED);
SkPaint paint;
paint.setShader(s)->unref();
SkRect r = { 0, 0, SkIntToScalar(1024), SkIntToScalar(HEIGHT) };
canvas->drawRect(r, paint);
}
virtual void onDraw(SkCanvas* canvas) {
#ifdef SK_BUILD_FOR_MAC
CGContextRef cg = makeCG(canvas->getDevice()->accessBitmap(false));
#endif
drawGrad(canvas);
const SkColor fg[] = {
0xFFFFFFFF,
0xFFFFFF00, 0xFFFF00FF, 0xFF00FFFF,
0xFFFF0000, 0xFF00FF00, 0xFF0000FF,
0xFF000000,
};
const char* text = "Hamburgefons";
size_t len = strlen(text);
SkPaint paint;
setFont(&paint, "Times");
paint.setTextSize(SkIntToScalar(16));
paint.setAntiAlias(true);
paint.setLCDRenderText(true);
SkScalar x = SkIntToScalar(10);
for (size_t i = 0; i < SK_ARRAY_COUNT(fg); ++i) {
paint.setColor(fg[i]);
SkScalar y = SkIntToScalar(40);
SkScalar stopy = SkIntToScalar(HEIGHT);
while (y < stopy) {
#if 1
canvas->drawText(text, len, x, y, paint);
#else
cgDrawText(cg, text, len, x, SkIntToScalar(HEIGHT) - y, paint);
#endif
y += paint.getTextSize() * 2;
}
x += SkIntToScalar(1024) / SK_ARRAY_COUNT(fg);
}
}
private:
typedef GM INHERITED;
};
//////////////////////////////////////////////////////////////////////////////
static GM* MyFactory(void*) { return new GammaTextGM; }
static GMRegistry reg(MyFactory);
}
<commit_msg>Fix some float/scalar/int confusion.<commit_after>/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm.h"
#include "SkCanvas.h"
#include "SkPath.h"
#include "SkGradientShader.h"
#include "SkTypeface.h"
static SkShader* make_heatGradient(const SkPoint pts[2]) {
const SkColor colors[] = {
SK_ColorBLACK, SK_ColorBLUE, SK_ColorCYAN, SK_ColorGREEN,
SK_ColorYELLOW, SK_ColorRED, SK_ColorWHITE
};
const SkColor bw[] = { SK_ColorBLACK, SK_ColorWHITE };
return SkGradientShader::CreateLinear(pts, bw, NULL,
SK_ARRAY_COUNT(bw),
SkShader::kClamp_TileMode);
}
static bool setFont(SkPaint* paint, const char name[]) {
SkTypeface* tf = SkTypeface::CreateFromName(name, SkTypeface::kNormal);
if (tf) {
paint->setTypeface(tf)->unref();
return true;
}
return false;
}
#ifdef SK_BUILD_FOR_MAC
#import <ApplicationServices/ApplicationServices.h>
#define BITMAP_INFO_RGB (kCGImageAlphaNoneSkipFirst | kCGBitmapByteOrder32Host)
static CGContextRef makeCG(const SkBitmap& bm) {
if (SkBitmap::kARGB_8888_Config != bm.config() ||
NULL == bm.getPixels()) {
return NULL;
}
CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();
CGContextRef cg = CGBitmapContextCreate(bm.getPixels(), bm.width(), bm.height(),
8, bm.rowBytes(), space, BITMAP_INFO_RGB);
CFRelease(space);
CGContextSetAllowsFontSubpixelQuantization(cg, false);
CGContextSetShouldSubpixelQuantizeFonts(cg, false);
return cg;
}
extern CTFontRef SkTypeface_GetCTFontRef(const SkTypeface* face);
static CGFontRef typefaceToCGFont(const SkTypeface* face) {
if (NULL == face) {
return 0;
}
CTFontRef ct = SkTypeface_GetCTFontRef(face);
return CTFontCopyGraphicsFont(ct, NULL);
}
static void cgSetPaintForText(CGContextRef cg, const SkPaint& paint) {
SkColor c = paint.getColor();
CGFloat rgba[] = {
SkColorGetB(c) / 255.0,
SkColorGetG(c) / 255.0,
SkColorGetR(c) / 255.0,
SkColorGetA(c) / 255.0,
};
CGContextSetRGBFillColor(cg, rgba[0], rgba[1], rgba[2], rgba[3]);
CGContextSetTextDrawingMode(cg, kCGTextFill);
CGContextSetFont(cg, typefaceToCGFont(paint.getTypeface()));
CGContextSetFontSize(cg, SkScalarToFloat(paint.getTextSize()));
CGContextSetAllowsFontSubpixelPositioning(cg, paint.isSubpixelText());
CGContextSetShouldSubpixelPositionFonts(cg, paint.isSubpixelText());
CGContextSetShouldAntialias(cg, paint.isAntiAlias());
CGContextSetShouldSmoothFonts(cg, paint.isLCDRenderText());
}
static void cgDrawText(CGContextRef cg, const void* text, size_t len,
float x, float y, const SkPaint& paint) {
if (cg) {
cgSetPaintForText(cg, paint);
uint16_t glyphs[200];
int count = paint.textToGlyphs(text, len, glyphs);
CGContextShowGlyphsAtPoint(cg, x, y, glyphs, count);
}
}
#endif
namespace skiagm {
/**
Test a set of clipping problems discovered while writing blitAntiRect,
and test all the code paths through the clipping blitters.
Each region should show as a blue center surrounded by a 2px green
border, with no red.
*/
#define HEIGHT 480
class GammaTextGM : public GM {
public:
GammaTextGM() {
}
protected:
virtual SkString onShortName() {
return SkString("gammatext");
}
virtual SkISize onISize() {
return make_isize(1024, HEIGHT);
}
static void drawGrad(SkCanvas* canvas) {
SkPoint pts[] = { { 0, 0 }, { 0, SkIntToScalar(HEIGHT) } };
#if 0
const SkColor colors[] = { SK_ColorBLACK, SK_ColorWHITE };
SkShader* s = SkGradientShader::CreateLinear(pts, colors, NULL, 2, SkShader::kClamp_TileMode);
#else
SkShader* s = make_heatGradient(pts);
#endif
canvas->clear(SK_ColorRED);
SkPaint paint;
paint.setShader(s)->unref();
SkRect r = { 0, 0, SkIntToScalar(1024), SkIntToScalar(HEIGHT) };
canvas->drawRect(r, paint);
}
virtual void onDraw(SkCanvas* canvas) {
#ifdef SK_BUILD_FOR_MAC
CGContextRef cg = makeCG(canvas->getDevice()->accessBitmap(false));
#endif
drawGrad(canvas);
const SkColor fg[] = {
0xFFFFFFFF,
0xFFFFFF00, 0xFFFF00FF, 0xFF00FFFF,
0xFFFF0000, 0xFF00FF00, 0xFF0000FF,
0xFF000000,
};
const char* text = "Hamburgefons";
size_t len = strlen(text);
SkPaint paint;
setFont(&paint, "Times");
paint.setTextSize(SkIntToScalar(16));
paint.setAntiAlias(true);
paint.setLCDRenderText(true);
SkScalar x = SkIntToScalar(10);
for (size_t i = 0; i < SK_ARRAY_COUNT(fg); ++i) {
paint.setColor(fg[i]);
SkScalar y = SkIntToScalar(40);
SkScalar stopy = SkIntToScalar(HEIGHT);
while (y < stopy) {
#if 1
canvas->drawText(text, len, x, y, paint);
#else
cgDrawText(cg, text, len, SkScalarToFloat(x),
static_cast<float>(HEIGHT) - SkScalarToFloat(y),
paint);
#endif
y += paint.getTextSize() * 2;
}
x += SkIntToScalar(1024) / SK_ARRAY_COUNT(fg);
}
}
private:
typedef GM INHERITED;
};
//////////////////////////////////////////////////////////////////////////////
static GM* MyFactory(void*) { return new GammaTextGM; }
static GMRegistry reg(MyFactory);
}
<|endoftext|>
|
<commit_before>#include "TolonSpellCheck.h"
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
void util_begin_test(char* szPreamble);
void util_end_test(bool bResult);
void util_is_expected(tsc_result r, bool& bSetFalseIfFailed);
void util_is_failure(char* szTestPartName, const tsc_result rActual, bool& bSetFalseIfNotFailed);
void util_is_success(char* szTestPartName, const tsc_result rActual, bool& bSetFalseIfFailed);
const char* util_textify_result(tsc_result r);
void check_test(bool bResult);
void print_stats();
// The tests
bool test_abnormal_init_uninit();
bool test_getversion();
bool test_no_init();
bool test_normal_init_uninit();
bool test_show_options();
bool test_word();
// Subtests
void subtest_tscInit(bool& bTestResult);
void subtest_tscCreateSession(tsc_cookie& c, bool& bTestResult);
void subtest_tscDestroySession(tsc_cookie c, bool& bTestResult);
void subtest_tscUninit(bool& bTestResult);
//static char s_szTextResult[64];
static string s_sTextResult;
static int g_nTestStartCount, g_nTestEndCount, g_nSuccessCount, g_nFailCount;
static const char* g_szLine = "--------------------------------------------------------------------------------";
int main()
{
g_nTestStartCount = g_nTestEndCount = g_nSuccessCount = g_nFailCount = 0;
cout << "Tolon Spell Check Test Program. Copyright (c) 2009 Alex Paterson." << endl;
cout << g_szLine << endl;
check_test(test_abnormal_init_uninit());
check_test(test_normal_init_uninit());
check_test(test_no_init());
check_test(test_getversion());
check_test(test_word());
check_test(test_show_options());
print_stats();
return 0;
}
// Utils
void check_test(bool bResult)
{
if (bResult)
++g_nSuccessCount;
else
++g_nFailCount;
}
void print_stats()
{
cout << g_nTestStartCount << " tests started, " << g_nTestEndCount << " tests finished." << endl;
cout << g_nSuccessCount << " ok, " << g_nFailCount << " failed." << endl;
cout << g_szLine << endl;
cout << endl;
}
void util_begin_test(char* szPreamble)
{
++g_nTestStartCount;
cout << szPreamble << endl;
}
void util_end_test(bool bResult)
{
++g_nTestEndCount;
if (bResult)
cout << "Test ok" << endl;
else
cout << "TEST FAILED" << endl;
cout << g_szLine << endl;
}
void util_is_expected(char* szTestPartName, const tsc_result rExpected, const tsc_result rActual, bool& bSetFalseIfFailed)
{
if (rActual == rExpected) {
cout << "\t" << szTestPartName <<" ok" << endl;
}
else {
cout << "FAIL->\t" << szTestPartName <<" FAIL; expected " << util_textify_result(rExpected) << ", got " << util_textify_result(rActual) << endl;
bSetFalseIfFailed = false;
}
cout << "\t\tLastError: " << ::tscGetLastError() << endl;
}
void util_is_failure(char* szTestPartName, const tsc_result rActual, bool& bSetFalseIfNotFailed)
{
if (FAILED(rActual)) {
cout << "\t" << szTestPartName <<" ok" << endl;
}
else {
cout << "FAIL->\t" << szTestPartName <<" FAIL; expected failure, got " << util_textify_result(rActual) << endl;
bSetFalseIfNotFailed = false;
}
cout << "\t\tLastError: " << ::tscGetLastError() << endl;
}
void util_is_success(char* szTestPartName, const tsc_result rActual, bool& bSetFalseIfFailed)
{
if (SUCCEEDED(rActual)) {
cout << "\t" << szTestPartName <<" ok" << endl;
}
else {
cout << "FAIL->\t" << szTestPartName <<" FAIL; expected success, got " << util_textify_result(rActual) << endl;
bSetFalseIfFailed = false;
}
cout << "\t\tLastError: " << ::tscGetLastError() << endl;
}
const char* util_textify_result(tsc_result r)
{
switch(r)
{
case TSC_S_FALSE:
return "TSC_S_FALSE";
case TSC_S_OK:
return "TSC_S_OK";
case TSC_E_FAIL:
return "TSC_E_FAIL";
case TSC_E_INVALIDARG:
return "TSC_E_INVALIDARG";
case TSC_E_NOTIMPL:
return "TSC_E_NOTIMPL";
case TSC_E_POINTER:
return "TSC_E_POINTER";
case TSC_E_UNEXPECTED:
return "TSC_E_UNEXPECTED";
default:
stringstream ss;
ss << "unknown 0x" << setw(8) << hex << r;
s_sTextResult.swap(ss.str());
return s_sTextResult.c_str();
}
return "";
}
// Tests below are in alphabetical order
bool test_abnormal_init_uninit()
{
bool bTestResult = true;
tsc_result r;
TSC_INIT_DATA id;
util_begin_test("test_abnormal_init_uninit()\r\nTesting abnormal tscInit/tscUninit sequences...");
memset(&id, 0xff, sizeof(TSC_INIT_DATA));
id.cbSize = sizeof(TSC_INIT_DATA);
strcpy(id.szAppName, "TestAppName01234567890123456789");
// Test uninit without init
r = ::tscUninit();
util_is_failure("tscUninit without tscInit", r, bTestResult);
// Test double init
r = ::tscInit(&id);
util_is_success("double tscInit, first call", r, bTestResult);
r = ::tscInit(&id);
util_is_failure("double tscInit, second call", r, bTestResult);
// Test double uninit
r = ::tscUninit();
util_is_success("double tscUninit, first call", r, bTestResult);
r = ::tscUninit();
util_is_failure("double tscUninit, second call", r, bTestResult);
util_end_test(bTestResult);
return bTestResult;
}
bool test_getversion()
{
bool bTestResult = true;
tsc_result r;
TSC_INIT_DATA id;
TSC_VERSION_DATA vd;
util_begin_test("test_getversion()\r\nTesting tscGetVersion...");
memset(&id, 0xff, sizeof(TSC_INIT_DATA));
id.cbSize = sizeof(TSC_INIT_DATA);
strcpy(id.szAppName, "TestAppName01234567890123456789");
r = ::tscInit(&id);
memset(&vd, 0xff, sizeof(TSC_VERSION_DATA));
vd.cbSize = sizeof(TSC_VERSION_DATA);
r = ::tscGetVersion(&vd);
util_is_success("tscGetVersion", r, bTestResult);
r = ::tscUninit();
util_end_test(bTestResult);
return bTestResult;
}
bool test_no_init()
{
bool bTestResult = true;
const tsc_result rExpected = E_UNEXPECTED;
tsc_result r = 0;
util_begin_test("test_no_init()\r\nTesting API use without calling tscInit() first...");
// Because the library has not been initialised, the functions below
// should return TSC_E_UNEXPECTED without attempting to use any of the
// parameters. Hence passing NULL should be OK.
r = ::tscUninit();
util_is_expected("tscUninit", rExpected, r, bTestResult);
r = ::tscGetVersion(NULL);
util_is_expected("tscGetVersion", rExpected, r, bTestResult);
r = ::tscCreateSession(NULL, NULL);
util_is_expected("tscCreateSession", rExpected, r, bTestResult);
r = ::tscDestroySession(TSC_NULL_COOKIE);
util_is_expected("tscDestroySession", rExpected, r, bTestResult);
r = ::tscGetSessionOptions(TSC_NULL_COOKIE, NULL);
util_is_expected("tscGetSessionOptions", rExpected, r, bTestResult);
r = ::tscSetSessionOptions(TSC_NULL_COOKIE, NULL);
util_is_expected("tscSetSessionOptions", rExpected, r, bTestResult);
r = ::tscShowOptionsWindow(TSC_NULL_COOKIE, NULL);
util_is_expected("tscShowOptionsWindow", rExpected, r, bTestResult);
r = ::tscCheckSpelling(TSC_NULL_COOKIE, NULL);
util_is_expected("tscCheckSpelling", rExpected, r, bTestResult);
r = ::tscCheckWord(TSC_NULL_COOKIE, NULL);
util_is_expected("tscCheckWord", rExpected, r, bTestResult);
util_end_test(bTestResult);
return bTestResult;
}
bool test_normal_init_uninit()
{
bool bTestResult = true;
tsc_result r;
TSC_INIT_DATA id;
util_begin_test("test_normal_init_uninit()\r\nTesting normal tscInit/tscUninit sequence...");
memset(&id, 0xff, sizeof(TSC_INIT_DATA));
id.cbSize = sizeof(TSC_INIT_DATA);
strcpy(id.szAppName, "TestAppName01234567890123456789");
r = ::tscInit(&id);
util_is_success("tscInit", r, bTestResult);
r = ::tscUninit();
util_is_success("tscUninit", r, bTestResult);
util_end_test(bTestResult);
return bTestResult;
}
bool test_show_options()
{
bool bTestResult = true;
tsc_result r;
tsc_cookie c = TSC_NULL_COOKIE;
util_begin_test("test_show_options()\r\nTesting tscShowOptionsWindow...");
// Init module
TSC_INIT_DATA id;
memset(&id, 0xff, sizeof(TSC_INIT_DATA));
id.cbSize = sizeof(TSC_INIT_DATA);
strcpy(id.szAppName, "TestAppName01234567890123456789");
r = ::tscInit(&id);
util_is_success("tscInit", r, bTestResult);
// Create session
TSC_CREATESESSION_DATA cs;
memset(&cs, 0xff, sizeof(TSC_CREATESESSION_DATA));
cs.cbSize = sizeof(TSC_CREATESESSION_DATA);
r = ::tscCreateSession(&c, &cs);
util_is_success("tscCreateSession", r, bTestResult);
// Show options window
TSC_SHOWOPTIONSWINDOW_DATA sow;
memset(&sow, 0xff, sizeof(TSC_SHOWOPTIONSWINDOW_DATA));
sow.cbSize = sizeof(TSC_SHOWOPTIONSWINDOW_DATA);
sow.hWndParent = NULL;
r = ::tscShowOptionsWindow(c, &sow);
util_is_success("tscShowOptionsWindow", r, bTestResult);
// Destroy session
r = ::tscDestroySession(c);
util_is_success("tscDestroySession", r, bTestResult);
// Uninit module
r = ::tscUninit();
util_is_success("tscUninit", r, bTestResult);
util_end_test(bTestResult);
return bTestResult;
}
bool test_word()
{
bool bTestResult = true;
tsc_result r;
tsc_cookie c = TSC_NULL_COOKIE;
const char* szWordToTest = "helllllo";
util_begin_test("test_word()\r\nTesting tscCheckWord(\"helllo\")...");
// Prologue
subtest_tscInit(bTestResult);
subtest_tscCreateSession(c, bTestResult);
// CheckWord
TSC_CHECKWORD_DATA cw;
memset(&cw, 0xff, sizeof(TSC_CHECKWORD_DATA));
cw.cbSize = sizeof(TSC_CHECKWORD_DATA);
cw.uTestWord.szWord8 = szWordToTest;
cw.uResultString.szResults8 = NULL;
cw.nResultStringSize = 0;
r = ::tscCheckWord(c, &cw);
util_is_success("tscCheckWord", r, bTestResult);
// Epilogue
subtest_tscDestroySession(c, bTestResult);
subtest_tscUninit(bTestResult);
util_end_test(bTestResult);
return bTestResult;
}
void subtest_tscInit(bool& bTestResult)
{
tsc_result r = TSC_E_FAIL;
TSC_INIT_DATA id;
memset(&id, 0xff, sizeof(TSC_INIT_DATA));
id.cbSize = sizeof(TSC_INIT_DATA);
strcpy(id.szAppName, "TestAppName01234567890123456789");
r = ::tscInit(&id);
util_is_success("tscInit", r, bTestResult);
}
void subtest_tscCreateSession(tsc_cookie& c, bool& bTestResult)
{
tsc_result r = TSC_E_FAIL;
TSC_CREATESESSION_DATA cs;
memset(&cs, 0xff, sizeof(TSC_CREATESESSION_DATA));
cs.cbSize = sizeof(TSC_CREATESESSION_DATA);
r = ::tscCreateSession(&c, &cs);
util_is_success("tscCreateSession", r, bTestResult);
}
void subtest_tscDestroySession(tsc_cookie c, bool& bTestResult)
{
tsc_result r = TSC_E_FAIL;
r = ::tscDestroySession(c);
util_is_success("tscDestroySession", r, bTestResult);
}
void subtest_tscUninit(bool& bTestResult)
{
tsc_result r = TSC_E_FAIL;
r = ::tscUninit();
util_is_success("tscUninit", r, bTestResult);
}
<commit_msg>Support visual themes for test app<commit_after>#include "TolonSpellCheck.h"
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
#include <windows.h>
#include <commctrl.h>
#pragma comment(linker, \
"\"/manifestdependency:type='Win32' "\
"name='Microsoft.Windows.Common-Controls' "\
"version='6.0.0.0' "\
"processorArchitecture='*' "\
"publicKeyToken='6595b64144ccf1df' "\
"language='*'\"")
using namespace std;
void util_begin_test(char* szPreamble);
void util_end_test(bool bResult);
void util_is_expected(tsc_result r, bool& bSetFalseIfFailed);
void util_is_failure(char* szTestPartName, const tsc_result rActual, bool& bSetFalseIfNotFailed);
void util_is_success(char* szTestPartName, const tsc_result rActual, bool& bSetFalseIfFailed);
const char* util_textify_result(tsc_result r);
void check_test(bool bResult);
void print_stats();
// The tests
bool test_abnormal_init_uninit();
bool test_getversion();
bool test_no_init();
bool test_normal_init_uninit();
bool test_show_options();
bool test_word();
// Subtests
void subtest_tscInit(bool& bTestResult);
void subtest_tscCreateSession(tsc_cookie& c, bool& bTestResult);
void subtest_tscDestroySession(tsc_cookie c, bool& bTestResult);
void subtest_tscUninit(bool& bTestResult);
//static char s_szTextResult[64];
static string s_sTextResult;
static int g_nTestStartCount, g_nTestEndCount, g_nSuccessCount, g_nFailCount;
static const char* g_szLine = "--------------------------------------------------------------------------------";
int main()
{
g_nTestStartCount = g_nTestEndCount = g_nSuccessCount = g_nFailCount = 0;
::InitCommonControls();
cout << "Tolon Spell Check Test Program. Copyright (c) 2009 Alex Paterson." << endl;
cout << g_szLine << endl;
check_test(test_abnormal_init_uninit());
check_test(test_normal_init_uninit());
check_test(test_no_init());
check_test(test_getversion());
check_test(test_word());
check_test(test_show_options());
print_stats();
return 0;
}
// Utils
void check_test(bool bResult)
{
if (bResult)
++g_nSuccessCount;
else
++g_nFailCount;
}
void print_stats()
{
cout << g_nTestStartCount << " tests started, " << g_nTestEndCount << " tests finished." << endl;
cout << g_nSuccessCount << " ok, " << g_nFailCount << " failed." << endl;
cout << g_szLine << endl;
cout << endl;
}
void util_begin_test(char* szPreamble)
{
++g_nTestStartCount;
cout << szPreamble << endl;
}
void util_end_test(bool bResult)
{
++g_nTestEndCount;
if (bResult)
cout << "Test ok" << endl;
else
cout << "TEST FAILED" << endl;
cout << g_szLine << endl;
}
void util_is_expected(char* szTestPartName, const tsc_result rExpected, const tsc_result rActual, bool& bSetFalseIfFailed)
{
if (rActual == rExpected) {
cout << "\t" << szTestPartName <<" ok" << endl;
}
else {
cout << "FAIL->\t" << szTestPartName <<" FAIL; expected " << util_textify_result(rExpected) << ", got " << util_textify_result(rActual) << endl;
bSetFalseIfFailed = false;
}
cout << "\t\tLastError: " << ::tscGetLastError() << endl;
}
void util_is_failure(char* szTestPartName, const tsc_result rActual, bool& bSetFalseIfNotFailed)
{
if (FAILED(rActual)) {
cout << "\t" << szTestPartName <<" ok" << endl;
}
else {
cout << "FAIL->\t" << szTestPartName <<" FAIL; expected failure, got " << util_textify_result(rActual) << endl;
bSetFalseIfNotFailed = false;
}
cout << "\t\tLastError: " << ::tscGetLastError() << endl;
}
void util_is_success(char* szTestPartName, const tsc_result rActual, bool& bSetFalseIfFailed)
{
if (SUCCEEDED(rActual)) {
cout << "\t" << szTestPartName <<" ok" << endl;
}
else {
cout << "FAIL->\t" << szTestPartName <<" FAIL; expected success, got " << util_textify_result(rActual) << endl;
bSetFalseIfFailed = false;
}
cout << "\t\tLastError: " << ::tscGetLastError() << endl;
}
const char* util_textify_result(tsc_result r)
{
switch(r)
{
case TSC_S_FALSE:
return "TSC_S_FALSE";
case TSC_S_OK:
return "TSC_S_OK";
case TSC_E_FAIL:
return "TSC_E_FAIL";
case TSC_E_INVALIDARG:
return "TSC_E_INVALIDARG";
case TSC_E_NOTIMPL:
return "TSC_E_NOTIMPL";
case TSC_E_POINTER:
return "TSC_E_POINTER";
case TSC_E_UNEXPECTED:
return "TSC_E_UNEXPECTED";
default:
stringstream ss;
ss << "unknown 0x" << setw(8) << hex << r;
s_sTextResult.swap(ss.str());
return s_sTextResult.c_str();
}
return "";
}
// Tests below are in alphabetical order
bool test_abnormal_init_uninit()
{
bool bTestResult = true;
tsc_result r;
TSC_INIT_DATA id;
util_begin_test("test_abnormal_init_uninit()\r\nTesting abnormal tscInit/tscUninit sequences...");
memset(&id, 0xff, sizeof(TSC_INIT_DATA));
id.cbSize = sizeof(TSC_INIT_DATA);
strcpy(id.szAppName, "TestAppName01234567890123456789");
// Test uninit without init
r = ::tscUninit();
util_is_failure("tscUninit without tscInit", r, bTestResult);
// Test double init
r = ::tscInit(&id);
util_is_success("double tscInit, first call", r, bTestResult);
r = ::tscInit(&id);
util_is_failure("double tscInit, second call", r, bTestResult);
// Test double uninit
r = ::tscUninit();
util_is_success("double tscUninit, first call", r, bTestResult);
r = ::tscUninit();
util_is_failure("double tscUninit, second call", r, bTestResult);
util_end_test(bTestResult);
return bTestResult;
}
bool test_getversion()
{
bool bTestResult = true;
tsc_result r;
TSC_INIT_DATA id;
TSC_VERSION_DATA vd;
util_begin_test("test_getversion()\r\nTesting tscGetVersion...");
memset(&id, 0xff, sizeof(TSC_INIT_DATA));
id.cbSize = sizeof(TSC_INIT_DATA);
strcpy(id.szAppName, "TestAppName01234567890123456789");
r = ::tscInit(&id);
memset(&vd, 0xff, sizeof(TSC_VERSION_DATA));
vd.cbSize = sizeof(TSC_VERSION_DATA);
r = ::tscGetVersion(&vd);
util_is_success("tscGetVersion", r, bTestResult);
r = ::tscUninit();
util_end_test(bTestResult);
return bTestResult;
}
bool test_no_init()
{
bool bTestResult = true;
const tsc_result rExpected = E_UNEXPECTED;
tsc_result r = 0;
util_begin_test("test_no_init()\r\nTesting API use without calling tscInit() first...");
// Because the library has not been initialised, the functions below
// should return TSC_E_UNEXPECTED without attempting to use any of the
// parameters. Hence passing NULL should be OK.
r = ::tscUninit();
util_is_expected("tscUninit", rExpected, r, bTestResult);
r = ::tscGetVersion(NULL);
util_is_expected("tscGetVersion", rExpected, r, bTestResult);
r = ::tscCreateSession(NULL, NULL);
util_is_expected("tscCreateSession", rExpected, r, bTestResult);
r = ::tscDestroySession(TSC_NULL_COOKIE);
util_is_expected("tscDestroySession", rExpected, r, bTestResult);
r = ::tscGetSessionOptions(TSC_NULL_COOKIE, NULL);
util_is_expected("tscGetSessionOptions", rExpected, r, bTestResult);
r = ::tscSetSessionOptions(TSC_NULL_COOKIE, NULL);
util_is_expected("tscSetSessionOptions", rExpected, r, bTestResult);
r = ::tscShowOptionsWindow(TSC_NULL_COOKIE, NULL);
util_is_expected("tscShowOptionsWindow", rExpected, r, bTestResult);
r = ::tscCheckSpelling(TSC_NULL_COOKIE, NULL);
util_is_expected("tscCheckSpelling", rExpected, r, bTestResult);
r = ::tscCheckWord(TSC_NULL_COOKIE, NULL);
util_is_expected("tscCheckWord", rExpected, r, bTestResult);
util_end_test(bTestResult);
return bTestResult;
}
bool test_normal_init_uninit()
{
bool bTestResult = true;
tsc_result r;
TSC_INIT_DATA id;
util_begin_test("test_normal_init_uninit()\r\nTesting normal tscInit/tscUninit sequence...");
memset(&id, 0xff, sizeof(TSC_INIT_DATA));
id.cbSize = sizeof(TSC_INIT_DATA);
strcpy(id.szAppName, "TestAppName01234567890123456789");
r = ::tscInit(&id);
util_is_success("tscInit", r, bTestResult);
r = ::tscUninit();
util_is_success("tscUninit", r, bTestResult);
util_end_test(bTestResult);
return bTestResult;
}
bool test_show_options()
{
bool bTestResult = true;
tsc_result r;
tsc_cookie c = TSC_NULL_COOKIE;
util_begin_test("test_show_options()\r\nTesting tscShowOptionsWindow...");
// Init module
TSC_INIT_DATA id;
memset(&id, 0xff, sizeof(TSC_INIT_DATA));
id.cbSize = sizeof(TSC_INIT_DATA);
strcpy(id.szAppName, "TestAppName01234567890123456789");
r = ::tscInit(&id);
util_is_success("tscInit", r, bTestResult);
// Create session
TSC_CREATESESSION_DATA cs;
memset(&cs, 0xff, sizeof(TSC_CREATESESSION_DATA));
cs.cbSize = sizeof(TSC_CREATESESSION_DATA);
r = ::tscCreateSession(&c, &cs);
util_is_success("tscCreateSession", r, bTestResult);
// Show options window
TSC_SHOWOPTIONSWINDOW_DATA sow;
memset(&sow, 0xff, sizeof(TSC_SHOWOPTIONSWINDOW_DATA));
sow.cbSize = sizeof(TSC_SHOWOPTIONSWINDOW_DATA);
sow.hWndParent = NULL;
r = ::tscShowOptionsWindow(c, &sow);
util_is_success("tscShowOptionsWindow", r, bTestResult);
// Destroy session
r = ::tscDestroySession(c);
util_is_success("tscDestroySession", r, bTestResult);
// Uninit module
r = ::tscUninit();
util_is_success("tscUninit", r, bTestResult);
util_end_test(bTestResult);
return bTestResult;
}
bool test_word()
{
bool bTestResult = true;
tsc_result r;
tsc_cookie c = TSC_NULL_COOKIE;
const char* szWordToTest = "helllllo";
util_begin_test("test_word()\r\nTesting tscCheckWord(\"helllo\")...");
// Prologue
subtest_tscInit(bTestResult);
subtest_tscCreateSession(c, bTestResult);
// CheckWord
TSC_CHECKWORD_DATA cw;
memset(&cw, 0xff, sizeof(TSC_CHECKWORD_DATA));
cw.cbSize = sizeof(TSC_CHECKWORD_DATA);
cw.uTestWord.szWord8 = szWordToTest;
cw.uResultString.szResults8 = NULL;
cw.nResultStringSize = 0;
r = ::tscCheckWord(c, &cw);
util_is_success("tscCheckWord", r, bTestResult);
// Epilogue
subtest_tscDestroySession(c, bTestResult);
subtest_tscUninit(bTestResult);
util_end_test(bTestResult);
return bTestResult;
}
void subtest_tscInit(bool& bTestResult)
{
tsc_result r = TSC_E_FAIL;
TSC_INIT_DATA id;
memset(&id, 0xff, sizeof(TSC_INIT_DATA));
id.cbSize = sizeof(TSC_INIT_DATA);
strcpy(id.szAppName, "TestAppName01234567890123456789");
r = ::tscInit(&id);
util_is_success("tscInit", r, bTestResult);
}
void subtest_tscCreateSession(tsc_cookie& c, bool& bTestResult)
{
tsc_result r = TSC_E_FAIL;
TSC_CREATESESSION_DATA cs;
memset(&cs, 0xff, sizeof(TSC_CREATESESSION_DATA));
cs.cbSize = sizeof(TSC_CREATESESSION_DATA);
r = ::tscCreateSession(&c, &cs);
util_is_success("tscCreateSession", r, bTestResult);
}
void subtest_tscDestroySession(tsc_cookie c, bool& bTestResult)
{
tsc_result r = TSC_E_FAIL;
r = ::tscDestroySession(c);
util_is_success("tscDestroySession", r, bTestResult);
}
void subtest_tscUninit(bool& bTestResult)
{
tsc_result r = TSC_E_FAIL;
r = ::tscUninit();
util_is_success("tscUninit", r, bTestResult);
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: fumeasur.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: obo $ $Date: 2004-01-20 11:05:47 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
#include "fumeasur.hxx"
#include <svx/measure.hxx>
#ifndef _SV_MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef _SFXREQUEST_HXX //autogen
#include <sfx2/request.hxx>
#endif
#ifndef SD_VIEW_HXX
#include "View.hxx"
#endif
#ifndef SD_VIEW_SHELL_HXX
#include "ViewShell.hxx"
#endif
#include "drawdoc.hxx"
namespace sd {
TYPEINIT1( FuMeasureDlg, FuPoor );
/*************************************************************************
|*
|* Konstruktor
|*
\************************************************************************/
FuMeasureDlg::FuMeasureDlg (
ViewShell* pViewSh,
::sd::Window* pWin,
::sd::View* pView,
SdDrawDocument* pDoc,
SfxRequest& rReq)
: FuPoor(pViewSh, pWin, pView, pDoc, rReq)
{
SfxItemSet aNewAttr( pDoc->GetPool() );
pView->GetAttributes( aNewAttr );
const SfxItemSet* pArgs = rReq.GetArgs();
if( !pArgs )
{
SvxMeasureDialog* pDlg = new SvxMeasureDialog( NULL, aNewAttr, pView );
USHORT nResult = pDlg->Execute();
switch( nResult )
{
case RET_OK:
{
pArgs = pDlg->GetOutputItemSet();
rReq.Done( *pArgs );
}
break;
default:
{
delete( pDlg );
}
return; // Abbruch
}
delete( pDlg );
}
pView->SetAttributes( *pArgs );
}
} // end of namespace sd
<commit_msg>INTEGRATION: CWS dialogdiet (1.1.1.1.316); FILE MERGED 2004/01/17 01:28:09 mwu 1.1.1.1.316.1: DialogDiet 2004_01_17<commit_after>/*************************************************************************
*
* $RCSfile: fumeasur.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: hr $ $Date: 2004-02-04 10:09:53 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
#include "fumeasur.hxx"
//CHINA001 #include <svx/measure.hxx>
#ifndef _SV_MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef _SFXREQUEST_HXX //autogen
#include <sfx2/request.hxx>
#endif
#ifndef SD_VIEW_HXX
#include "View.hxx"
#endif
#ifndef SD_VIEW_SHELL_HXX
#include "ViewShell.hxx"
#endif
#include "drawdoc.hxx"
#include <svx/svxdlg.hxx> //CHINA001
#include <svx/dialogs.hrc> //CHINA001
namespace sd {
TYPEINIT1( FuMeasureDlg, FuPoor );
/*************************************************************************
|*
|* Konstruktor
|*
\************************************************************************/
FuMeasureDlg::FuMeasureDlg (
ViewShell* pViewSh,
::sd::Window* pWin,
::sd::View* pView,
SdDrawDocument* pDoc,
SfxRequest& rReq)
: FuPoor(pViewSh, pWin, pView, pDoc, rReq)
{
SfxItemSet aNewAttr( pDoc->GetPool() );
pView->GetAttributes( aNewAttr );
const SfxItemSet* pArgs = rReq.GetArgs();
if( !pArgs )
{
//CHINA001 SvxMeasureDialog* pDlg = new SvxMeasureDialog( NULL, aNewAttr, pView );
SvxAbstractDialogFactory* pFact = SvxAbstractDialogFactory::Create();
DBG_ASSERT(pFact, "Dialogdiet Factory fail!");//CHINA001
AbstractSfxSingleTabDialog * pDlg = pFact->CreateSfxSingleTabDialog( NULL,
aNewAttr,
pView,
ResId(RID_SVXPAGE_MEASURE));
DBG_ASSERT(pDlg, "Dialogdiet fail!");//CHINA001
USHORT nResult = pDlg->Execute();
switch( nResult )
{
case RET_OK:
{
pArgs = pDlg->GetOutputItemSet();
rReq.Done( *pArgs );
}
break;
default:
{
delete( pDlg );
}
return; // Abbruch
}
delete( pDlg );
}
pView->SetAttributes( *pArgs );
}
} // end of namespace sd
<|endoftext|>
|
<commit_before>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, version 1.0 beta 3 *
* (c) 2006-2008 MGH, INRIA, USTL, UJF, CNRS *
* *
* This library is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Lesser General Public License as published by *
* the Free Software Foundation; either version 2.1 of the License, or (at *
* your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this library; if not, write to the Free Software Foundation, *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *
*******************************************************************************
* SOFA :: Framework *
* *
* Authors: M. Adam, J. Allard, B. Andre, P-J. Bensoussan, S. Cotin, C. Duriez,*
* H. Delingette, F. Falipou, F. Faure, S. Fonteneau, L. Heigeas, C. Mendoza, *
* M. Nesme, P. Neumann, J-P. de la Plata Alcade, F. Poyer and F. Roy *
* *
* Contact information: contact@sofa-framework.org *
******************************************************************************/
#include <sofa/helper/TagFactory.h>
#include <sofa/core/objectmodel/Tag.h>
#include <algorithm> // for std::includes
namespace sofa
{
namespace core
{
namespace objectmodel
{
Tag::Tag(const std::string& s)
: id(0)
{
if (!s.empty())
{
id = helper::TagFactory::getID(s);
}
}
Tag::operator std::string() const
{
if (id == 0) return std::string("0");
else return helper::TagFactory::getName(id);
}
bool TagSet::includes(const TagSet& t) const
{
return std::includes(t.begin(), t.end(), this->begin(), this->end());
}
} // namespace objectmodel
} // namespace core
} // namespace sofa
<commit_msg>r4113/sofa-dev : FIX: std::includes return true if the first element is empty => test on size before.<commit_after>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, version 1.0 beta 3 *
* (c) 2006-2008 MGH, INRIA, USTL, UJF, CNRS *
* *
* This library is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Lesser General Public License as published by *
* the Free Software Foundation; either version 2.1 of the License, or (at *
* your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this library; if not, write to the Free Software Foundation, *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *
*******************************************************************************
* SOFA :: Framework *
* *
* Authors: M. Adam, J. Allard, B. Andre, P-J. Bensoussan, S. Cotin, C. Duriez,*
* H. Delingette, F. Falipou, F. Faure, S. Fonteneau, L. Heigeas, C. Mendoza, *
* M. Nesme, P. Neumann, J-P. de la Plata Alcade, F. Poyer and F. Roy *
* *
* Contact information: contact@sofa-framework.org *
******************************************************************************/
#include <sofa/helper/TagFactory.h>
#include <sofa/core/objectmodel/Tag.h>
#include <algorithm> // for std::includes
namespace sofa
{
namespace core
{
namespace objectmodel
{
Tag::Tag(const std::string& s)
: id(0)
{
if (!s.empty())
{
id = helper::TagFactory::getID(s);
}
}
Tag::operator std::string() const
{
if (id == 0) return std::string("0");
else return helper::TagFactory::getName(id);
}
bool TagSet::includes(const TagSet& t) const
{
return !empty() && std::includes(t.begin(), t.end(), this->begin(), this->end());
}
} // namespace objectmodel
} // namespace core
} // namespace sofa
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: drviewsg.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: ka $ $Date: 2002-08-09 09:14:17 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _SVXIDS_HRC
#include <svx/svxids.hrc>
#endif
#ifndef _IMAPDLG_HXX
#include <svx/imapdlg.hxx>
#endif
#ifndef _SFXREQUEST_HXX //autogen
#include <sfx2/request.hxx>
#endif
#ifndef _SFXDISPATCH_HXX //autogen
#include <sfx2/dispatch.hxx>
#endif
#include <sfx2/viewfrm.hxx>
#ifndef _SVDOGRAF_HXX //autogen
#include <svx/svdograf.hxx>
#endif
#ifndef _SVDOOLE2_HXX //autogen
#include <svx/svdoole2.hxx>
#endif
#pragma hdrstop
#include "app.hrc"
#include "drviewsh.hxx"
#include "drawdoc.hxx"
#include "fuslshow.hxx"
#include "imapinfo.hxx"
#include "sdmod.hxx"
#include "optsitem.hxx"
#include "frmview.hxx"
#include "drawview.hxx"
/*************************************************************************
|*
|*
|*
\************************************************************************/
void SdDrawViewShell::ExecIMap( SfxRequest& rReq )
{
// waehrend einer Diashow wird nichts ausgefuehrt!
if (pFuActual && pFuActual->GetSlotID() == SID_PRESENTATION)
return;
if ( rReq.GetSlot() == SID_IMAP_EXEC )
{
SdrMark* pMark = pDrView->GetMarkList().GetMark(0);
if ( pMark )
{
SdrObject* pSdrObj = pMark->GetObj();
SvxIMapDlg* pDlg = SVXIMAPDLG();
if ( pDlg->GetEditingObject() == (void*) pSdrObj )
{
const ImageMap& rImageMap = pDlg->GetImageMap();
SdIMapInfo* pIMapInfo = pDoc->GetIMapInfo( pSdrObj );
if ( !pIMapInfo )
pSdrObj->InsertUserData( new SdIMapInfo( rImageMap ) );
else
pIMapInfo->SetImageMap( rImageMap );
pDoc->SetChanged( sal_True );
}
}
}
}
/*************************************************************************
|*
|*
|*
\************************************************************************/
void SdDrawViewShell::GetIMapState( SfxItemSet& rSet )
{
BOOL bDisable = TRUE;
if( GetViewFrame()->HasChildWindow( SvxIMapDlgChildWindow::GetChildWindowId() ) )
{
const SdrMarkList& rMarkList = pDrView->GetMarkList();
const SdrObject* pObj = NULL;
ULONG nMarkCount = rMarkList.GetMarkCount();
if ( nMarkCount == 1 )
{
pObj = rMarkList.GetMark( 0 )->GetObj();
if ( ( pObj->ISA( SdrGrafObj ) || pObj->ISA( SdrOle2Obj ) ) &&
( SVXIMAPDLG()->GetEditingObject() == (void*) pObj ) )
{
bDisable = FALSE;
}
}
}
rSet.Put( SfxBoolItem( SID_IMAP_EXEC, bDisable ) );
}
/*************************************************************************
|*
|* Execute-Methode der Optionsleiste
|*
\************************************************************************/
void SdDrawViewShell::ExecOptionsBar( SfxRequest& rReq )
{
// waehrend einer Diashow wird nichts ausgefuehrt!
if (pFuActual && pFuActual->GetSlotID() == SID_PRESENTATION)
return;
BOOL bDefault = FALSE;
USHORT nSlot = rReq.GetSlot();
FrameView* pFrameView = GetFrameView();
SdOptions* pOptions = SD_MOD()->GetSdOptions(pDoc->GetDocumentType());
switch( nSlot )
{
// Ersatzdarstellung-Optionen
case SID_GRAPHIC_DRAFT:
pOptions->SetExternGraphic( !pDrView->IsGrafDraft() );
break;
case SID_FILL_DRAFT:
pOptions->SetOutlineMode( !pDrView->IsFillDraft() );
break;
case SID_TEXT_DRAFT:
pOptions->SetNoText( !pDrView->IsTextDraft() );
break;
case SID_LINE_DRAFT:
pOptions->SetHairlineMode( !pDrView->IsLineDraft() );
break;
case SID_HANDLES_DRAFT:
pOptions->SetSolidMarkHdl( !pDrView->IsSolidMarkHdl() );
break;
case SID_SOLID_CREATE:
pOptions->SetSolidDragging( !pDrView->IsSolidDragging() );
break;
// Raster- / Hilfslinien-Optionen
case SID_GRID_VISIBLE: // noch nicht hier !
{
pOptions->SetGridVisible( !pDrView->IsGridVisible() );
}
break;
case SID_GRID_USE:
{
pOptions->SetUseGridSnap( !pDrView->IsGridSnap() );
}
break;
case SID_HELPLINES_VISIBLE: // noch nicht hier !
{
pOptions->SetHelplines( !pDrView->IsHlplVisible() );
}
break;
case SID_HELPLINES_USE:
{
pOptions->SetSnapHelplines( !pDrView->IsHlplSnap() );
}
break;
case SID_HELPLINES_MOVE:
{
pOptions->SetDragStripes( !pDrView->IsDragStripes() );
}
break;
case SID_SNAP_BORDER:
{
pOptions->SetSnapBorder( !pDrView->IsBordSnap() );
}
break;
case SID_SNAP_FRAME:
{
pOptions->SetSnapFrame( !pDrView->IsOFrmSnap() );
}
break;
case SID_SNAP_POINTS:
{
pOptions->SetSnapPoints( !pDrView->IsOPntSnap() );
}
break;
case SID_QUICKEDIT:
{
pOptions->SetQuickEdit( !pDrView->IsQuickTextEditMode() );
}
break;
case SID_PICK_THROUGH:
{
pOptions->SetPickThrough(
!pDrView->GetModel()->IsPickThroughTransparentTextFrames() );
}
break;
case SID_BIG_HANDLES:
{
pOptions->SetBigHandles( !pFrameView->IsBigHandles() );
}
break;
case SID_DOUBLECLICK_TEXTEDIT:
{
pOptions->SetDoubleClickTextEdit( !pFrameView->IsDoubleClickTextEdit() );
}
break;
case SID_CLICK_CHANGE_ROTATION:
{
pOptions->SetClickChangeRotation( !pFrameView->IsClickChangeRotation() );
}
break;
default:
bDefault = TRUE;
break;
}
if( !bDefault )
{
pOptions->StoreConfig();
// Speichert die Konfiguration SOFORT
// SFX_APP()->SaveConfiguration();
WriteFrameViewData();
//FrameView* pFrameView = pViewShell->GetFrameView(); schon oben
pFrameView->Update( pOptions );
ReadFrameViewData( pFrameView );
Invalidate( nSlot );
rReq.Done();
}
}
/*************************************************************************
|*
|* State-Methode der Optionsleiste
|*
\************************************************************************/
void SdDrawViewShell::GetOptionsBarState( SfxItemSet& rSet )
{
FrameView* pFrameView = GetFrameView();
rSet.Put( SfxBoolItem( SID_GRAPHIC_DRAFT, pDrView->IsGrafDraft() ) );
rSet.Put( SfxBoolItem( SID_FILL_DRAFT, pDrView->IsFillDraft() ) );
rSet.Put( SfxBoolItem( SID_TEXT_DRAFT, pDrView->IsTextDraft() ) );
rSet.Put( SfxBoolItem( SID_LINE_DRAFT, pDrView->IsLineDraft() ) );
rSet.Put( SfxBoolItem( SID_HANDLES_DRAFT, !pDrView->IsSolidMarkHdl() ) );
rSet.Put( SfxBoolItem( SID_SOLID_CREATE, pDrView->IsSolidDragging() ) );
rSet.Put( SfxBoolItem( SID_GRID_VISIBLE, pDrView->IsGridVisible() ) );
rSet.Put( SfxBoolItem( SID_GRID_USE, pDrView->IsGridSnap() ) );
rSet.Put( SfxBoolItem( SID_HELPLINES_VISIBLE, pDrView->IsHlplVisible() ) );
rSet.Put( SfxBoolItem( SID_HELPLINES_USE, pDrView->IsHlplSnap() ) );
rSet.Put( SfxBoolItem( SID_HELPLINES_MOVE, pDrView->IsDragStripes() ) );
rSet.Put( SfxBoolItem( SID_SNAP_BORDER, pDrView->IsBordSnap() ) );
rSet.Put( SfxBoolItem( SID_SNAP_FRAME, pDrView->IsOFrmSnap() ) );
rSet.Put( SfxBoolItem( SID_SNAP_POINTS, pDrView->IsOPntSnap() ) );
rSet.Put( SfxBoolItem( SID_QUICKEDIT, pDrView->IsQuickTextEditMode() ) );
rSet.Put( SfxBoolItem( SID_PICK_THROUGH,
pDrView->GetModel()->IsPickThroughTransparentTextFrames() ) );
rSet.Put( SfxBoolItem( SID_BIG_HANDLES, pFrameView->IsBigHandles() ) );
rSet.Put( SfxBoolItem( SID_DOUBLECLICK_TEXTEDIT, pFrameView->IsDoubleClickTextEdit() ) );
rSet.Put( SfxBoolItem( SID_CLICK_CHANGE_ROTATION, pFrameView->IsClickChangeRotation() ) );
}
<commit_msg>INTEGRATION: CWS impress1 (1.5.222); FILE MERGED 2004/01/09 16:32:56 af 1.5.222.2: #111996# Renamed header files DrawView.hxx, Fader.hxx, and ShowView.hxx back to lowercase version. 2003/09/17 08:10:09 af 1.5.222.1: #111996# Transition to stacked sub-shells. Introduction of namespace sd.<commit_after>/*************************************************************************
*
* $RCSfile: drviewsg.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: obo $ $Date: 2004-01-20 12:48:32 $
*
* 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): _______________________________________
*
*
************************************************************************/
#include "DrawViewShell.hxx"
#ifndef _SVXIDS_HRC
#include <svx/svxids.hrc>
#endif
#ifndef _IMAPDLG_HXX
#include <svx/imapdlg.hxx>
#endif
#ifndef _SFXREQUEST_HXX //autogen
#include <sfx2/request.hxx>
#endif
#ifndef _SFXDISPATCH_HXX //autogen
#include <sfx2/dispatch.hxx>
#endif
#include <sfx2/viewfrm.hxx>
#ifndef _SVDOGRAF_HXX //autogen
#include <svx/svdograf.hxx>
#endif
#ifndef _SVDOOLE2_HXX //autogen
#include <svx/svdoole2.hxx>
#endif
#pragma hdrstop
#include "app.hrc"
#include "drawdoc.hxx"
#ifndef SD_FU_SLIDE_SHOW_HXX
#include "fuslshow.hxx"
#endif
#include "imapinfo.hxx"
#include "sdmod.hxx"
#include "optsitem.hxx"
#ifndef SD_FRAME_VIEW
#include "FrameView.hxx"
#endif
#ifndef SD_DRAW_VIEW_HXX
#include "drawview.hxx"
#endif
namespace sd {
/*************************************************************************
|*
|*
|*
\************************************************************************/
void DrawViewShell::ExecIMap( SfxRequest& rReq )
{
// waehrend einer Diashow wird nichts ausgefuehrt!
if (pFuActual && pFuActual->GetSlotID() == SID_PRESENTATION)
return;
if ( rReq.GetSlot() == SID_IMAP_EXEC )
{
SdrMark* pMark = pDrView->GetMarkList().GetMark(0);
if ( pMark )
{
SdrObject* pSdrObj = pMark->GetObj();
SvxIMapDlg* pDlg = SVXIMAPDLG();
if ( pDlg->GetEditingObject() == (void*) pSdrObj )
{
const ImageMap& rImageMap = pDlg->GetImageMap();
SdIMapInfo* pIMapInfo = GetDoc()->GetIMapInfo( pSdrObj );
if ( !pIMapInfo )
pSdrObj->InsertUserData( new SdIMapInfo( rImageMap ) );
else
pIMapInfo->SetImageMap( rImageMap );
GetDoc()->SetChanged( sal_True );
}
}
}
}
/*************************************************************************
|*
|*
|*
\************************************************************************/
void DrawViewShell::GetIMapState( SfxItemSet& rSet )
{
BOOL bDisable = TRUE;
if( GetViewFrame()->HasChildWindow( SvxIMapDlgChildWindow::GetChildWindowId() ) )
{
const SdrMarkList& rMarkList = pDrView->GetMarkList();
const SdrObject* pObj = NULL;
ULONG nMarkCount = rMarkList.GetMarkCount();
if ( nMarkCount == 1 )
{
pObj = rMarkList.GetMark( 0 )->GetObj();
if ( ( pObj->ISA( SdrGrafObj ) || pObj->ISA( SdrOle2Obj ) ) &&
( SVXIMAPDLG()->GetEditingObject() == (void*) pObj ) )
{
bDisable = FALSE;
}
}
}
rSet.Put( SfxBoolItem( SID_IMAP_EXEC, bDisable ) );
}
/*************************************************************************
|*
|* Execute-Methode der Optionsleiste
|*
\************************************************************************/
void DrawViewShell::ExecOptionsBar( SfxRequest& rReq )
{
// waehrend einer Diashow wird nichts ausgefuehrt!
if (pFuActual && pFuActual->GetSlotID() == SID_PRESENTATION)
return;
BOOL bDefault = FALSE;
USHORT nSlot = rReq.GetSlot();
FrameView* pFrameView = GetFrameView();
SdOptions* pOptions = SD_MOD()->GetSdOptions(GetDoc()->GetDocumentType());
switch( nSlot )
{
// Ersatzdarstellung-Optionen
case SID_GRAPHIC_DRAFT:
pOptions->SetExternGraphic( !pDrView->IsGrafDraft() );
break;
case SID_FILL_DRAFT:
pOptions->SetOutlineMode( !pDrView->IsFillDraft() );
break;
case SID_TEXT_DRAFT:
pOptions->SetNoText( !pDrView->IsTextDraft() );
break;
case SID_LINE_DRAFT:
pOptions->SetHairlineMode( !pDrView->IsLineDraft() );
break;
case SID_HANDLES_DRAFT:
pOptions->SetSolidMarkHdl( !pDrView->IsSolidMarkHdl() );
break;
case SID_SOLID_CREATE:
pOptions->SetSolidDragging( !pDrView->IsSolidDragging() );
break;
// Raster- / Hilfslinien-Optionen
case SID_GRID_VISIBLE: // noch nicht hier !
{
pOptions->SetGridVisible( !pDrView->IsGridVisible() );
}
break;
case SID_GRID_USE:
{
pOptions->SetUseGridSnap( !pDrView->IsGridSnap() );
}
break;
case SID_HELPLINES_VISIBLE: // noch nicht hier !
{
pOptions->SetHelplines( !pDrView->IsHlplVisible() );
}
break;
case SID_HELPLINES_USE:
{
pOptions->SetSnapHelplines( !pDrView->IsHlplSnap() );
}
break;
case SID_HELPLINES_MOVE:
{
pOptions->SetDragStripes( !pDrView->IsDragStripes() );
}
break;
case SID_SNAP_BORDER:
{
pOptions->SetSnapBorder( !pDrView->IsBordSnap() );
}
break;
case SID_SNAP_FRAME:
{
pOptions->SetSnapFrame( !pDrView->IsOFrmSnap() );
}
break;
case SID_SNAP_POINTS:
{
pOptions->SetSnapPoints( !pDrView->IsOPntSnap() );
}
break;
case SID_QUICKEDIT:
{
pOptions->SetQuickEdit( !pDrView->IsQuickTextEditMode() );
}
break;
case SID_PICK_THROUGH:
{
pOptions->SetPickThrough(
!pDrView->GetModel()->IsPickThroughTransparentTextFrames() );
}
break;
case SID_BIG_HANDLES:
{
pOptions->SetBigHandles( !pFrameView->IsBigHandles() );
}
break;
case SID_DOUBLECLICK_TEXTEDIT:
{
pOptions->SetDoubleClickTextEdit( !pFrameView->IsDoubleClickTextEdit() );
}
break;
case SID_CLICK_CHANGE_ROTATION:
{
pOptions->SetClickChangeRotation( !pFrameView->IsClickChangeRotation() );
}
break;
default:
bDefault = TRUE;
break;
}
if( !bDefault )
{
pOptions->StoreConfig();
// Speichert die Konfiguration SOFORT
// SFX_APP()->SaveConfiguration();
WriteFrameViewData();
//FrameView* pFrameView = pViewShell->GetFrameView(); schon oben
pFrameView->Update( pOptions );
ReadFrameViewData( pFrameView );
Invalidate( nSlot );
rReq.Done();
}
}
/*************************************************************************
|*
|* State-Methode der Optionsleiste
|*
\************************************************************************/
void DrawViewShell::GetOptionsBarState( SfxItemSet& rSet )
{
FrameView* pFrameView = GetFrameView();
rSet.Put( SfxBoolItem( SID_GRAPHIC_DRAFT, pDrView->IsGrafDraft() ) );
rSet.Put( SfxBoolItem( SID_FILL_DRAFT, pDrView->IsFillDraft() ) );
rSet.Put( SfxBoolItem( SID_TEXT_DRAFT, pDrView->IsTextDraft() ) );
rSet.Put( SfxBoolItem( SID_LINE_DRAFT, pDrView->IsLineDraft() ) );
rSet.Put( SfxBoolItem( SID_HANDLES_DRAFT, !pDrView->IsSolidMarkHdl() ) );
rSet.Put( SfxBoolItem( SID_SOLID_CREATE, pDrView->IsSolidDragging() ) );
rSet.Put( SfxBoolItem( SID_GRID_VISIBLE, pDrView->IsGridVisible() ) );
rSet.Put( SfxBoolItem( SID_GRID_USE, pDrView->IsGridSnap() ) );
rSet.Put( SfxBoolItem( SID_HELPLINES_VISIBLE, pDrView->IsHlplVisible() ) );
rSet.Put( SfxBoolItem( SID_HELPLINES_USE, pDrView->IsHlplSnap() ) );
rSet.Put( SfxBoolItem( SID_HELPLINES_MOVE, pDrView->IsDragStripes() ) );
rSet.Put( SfxBoolItem( SID_SNAP_BORDER, pDrView->IsBordSnap() ) );
rSet.Put( SfxBoolItem( SID_SNAP_FRAME, pDrView->IsOFrmSnap() ) );
rSet.Put( SfxBoolItem( SID_SNAP_POINTS, pDrView->IsOPntSnap() ) );
rSet.Put( SfxBoolItem( SID_QUICKEDIT, pDrView->IsQuickTextEditMode() ) );
rSet.Put( SfxBoolItem( SID_PICK_THROUGH,
pDrView->GetModel()->IsPickThroughTransparentTextFrames() ) );
rSet.Put( SfxBoolItem( SID_BIG_HANDLES, pFrameView->IsBigHandles() ) );
rSet.Put( SfxBoolItem( SID_DOUBLECLICK_TEXTEDIT, pFrameView->IsDoubleClickTextEdit() ) );
rSet.Put( SfxBoolItem( SID_CLICK_CHANGE_ROTATION, pFrameView->IsClickChangeRotation() ) );
}
} // end of namespace sd
<|endoftext|>
|
<commit_before>/*
* ArcScript Scripts for Arcemu MMORPG Server
* Copyright (C) 2008 Arcemu Team
* Copyright (C) 2007 Moon++ <http://www.moonplusplus.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
* 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 "StdAfx.h"
#include "Setup.h"
//Crimson Hammersmith
class CrimsonHammersmith : public CreatureAIScript
{
public:
ADD_CREATURE_FACTORY_FUNCTION(CrimsonHammersmith);
CrimsonHammersmith(Creature* pCreature) : CreatureAIScript(pCreature) {}
void OnCombatStart(Unit* mTarget)
{
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "Who Dares Disturb Me");
}
};
//Corrupt Minor Manifestation Water Dead
class Corrupt_Minor_Manifestation_Water_Dead : public CreatureAIScript
{
public:
ADD_CREATURE_FACTORY_FUNCTION(Corrupt_Minor_Manifestation_Water_Dead);
Corrupt_Minor_Manifestation_Water_Dead(Creature* pCreature) : CreatureAIScript(pCreature) {}
void OnDied(Unit *mKiller)
{
float SSX = _unit->GetPositionX();
float SSY = _unit->GetPositionY();
float SSZ = _unit->GetPositionZ();
float SSO = _unit->GetOrientation();
_unit->GetMapMgr()->GetInterface()->SpawnCreature(5895, SSX, SSY+1, SSZ, SSO, true, false, 0, 0)->Despawn(600000, 0);
}
};
class SavannahProwler : public CreatureAIScript
{
public:
SavannahProwler(Creature* pCreature) : CreatureAIScript(pCreature) {}
void OnLoad()
{
uint8 chance = RandomUInt(3);
if(chance == 1)
_unit->SetStandState(STANDSTATE_SLEEP);
}
void OnCombatStart()
{
if(_unit->GetStandState() == STANDSTATE_SLEEP)
_unit->SetStandState(0);
}
void Destroy()
{
delete (SavannahProwler*)this;
}
static CreatureAIScript *Create(Creature * c) { return new SavannahProwler(c); }
};
//Lazy Peons
class PeonSleepingAI : public CreatureAIScript
{
public:
ADD_CREATURE_FACTORY_FUNCTION(PeonSleepingAI);
PeonSleepingAI(Creature* pCreature) : CreatureAIScript(pCreature)
{
Unit * target = static_cast< Unit* >(_unit);
SpellEntry * pSpellEntry = dbcSpell.LookupEntry(18795);
sEventMgr.AddEvent( target ,&Unit::EventCastSpell , target , pSpellEntry , 0, 3000 + RandomUInt( 180000 ), 1, 1 );
}
};
void SetupMiscCreatures(ScriptMgr *mgr)
{
mgr->register_creature_script(11120, &CrimsonHammersmith::Create);
mgr->register_creature_script(5894, &Corrupt_Minor_Manifestation_Water_Dead::Create);
mgr->register_creature_script(3425, &SavannahProwler::Create);
mgr->register_creature_script(10556, &PeonSleepingAI::Create);
}<commit_msg>Temporary fix with creature AI. Needs to be done by spell when I get time.<commit_after>/*
* ArcScript Scripts for Arcemu MMORPG Server
* Copyright (C) 2008 Arcemu Team
* Copyright (C) 2007 Moon++ <http://www.moonplusplus.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
* 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 "StdAfx.h"
#include "Setup.h"
//Nestlewood Owlkin
class NestlewoodOwlkin : public CreatureAIScript
{
public:
ADD_CREATURE_FACTORY_FUNCTION(NestlewoodOwlkin);
NestlewoodOwlkin(Creature* pCreature) : CreatureAIScript(pCreature) {}
void OnCombatStart(Unit* mTarget)
{
if (_unit->HasAura(29528))
RegisterAIUpdateEvent(3000);
_unit->GetAIInterface()->disable_targeting = true;
_unit->Root();
_unit->Despawn(3100, 60000);
}
void AIUpdate()
{
_unit->GetMapMgr()->GetInterface()->SpawnCreature(16534, _unit->GetPositionX(), _unit->GetPositionY(), _unit->GetPositionZ(), _unit->GetOrientation(), true, false, 0, 0)->Despawn(RandomUInt(14000, 20000), 0);
RemoveAIUpdateEvent();
}
};
//Crimson Hammersmith
class CrimsonHammersmith : public CreatureAIScript
{
public:
ADD_CREATURE_FACTORY_FUNCTION(CrimsonHammersmith);
CrimsonHammersmith(Creature* pCreature) : CreatureAIScript(pCreature) {}
void OnCombatStart(Unit* mTarget)
{
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, "Who Dares Disturb Me");
}
};
//Corrupt Minor Manifestation Water Dead
class Corrupt_Minor_Manifestation_Water_Dead : public CreatureAIScript
{
public:
ADD_CREATURE_FACTORY_FUNCTION(Corrupt_Minor_Manifestation_Water_Dead);
Corrupt_Minor_Manifestation_Water_Dead(Creature* pCreature) : CreatureAIScript(pCreature) {}
void OnDied(Unit *mKiller)
{
float SSX = _unit->GetPositionX();
float SSY = _unit->GetPositionY();
float SSZ = _unit->GetPositionZ();
float SSO = _unit->GetOrientation();
_unit->GetMapMgr()->GetInterface()->SpawnCreature(5895, SSX, SSY+1, SSZ, SSO, true, false, 0, 0)->Despawn(600000, 0);
}
};
class SavannahProwler : public CreatureAIScript
{
public:
SavannahProwler(Creature* pCreature) : CreatureAIScript(pCreature) {}
void OnLoad()
{
uint8 chance = RandomUInt(3);
if(chance == 1)
_unit->SetStandState(STANDSTATE_SLEEP);
}
void OnCombatStart()
{
if(_unit->GetStandState() == STANDSTATE_SLEEP)
_unit->SetStandState(0);
}
void Destroy()
{
delete (SavannahProwler*)this;
}
static CreatureAIScript *Create(Creature * c) { return new SavannahProwler(c); }
};
//Lazy Peons
class PeonSleepingAI : public CreatureAIScript
{
public:
ADD_CREATURE_FACTORY_FUNCTION(PeonSleepingAI);
PeonSleepingAI(Creature* pCreature) : CreatureAIScript(pCreature)
{
Unit * target = static_cast< Unit* >(_unit);
SpellEntry * pSpellEntry = dbcSpell.LookupEntry(18795);
sEventMgr.AddEvent( target ,&Unit::EventCastSpell , target , pSpellEntry , 0, 3000 + RandomUInt( 180000 ), 1, 1 );
}
};
void SetupMiscCreatures(ScriptMgr *mgr)
{
mgr->register_creature_script(16518, &NestlewoodOwlkin::Create);
mgr->register_creature_script(11120, &CrimsonHammersmith::Create);
mgr->register_creature_script(5894, &Corrupt_Minor_Manifestation_Water_Dead::Create);
mgr->register_creature_script(3425, &SavannahProwler::Create);
mgr->register_creature_script(10556, &PeonSleepingAI::Create);
}<|endoftext|>
|
<commit_before>#include <Render/ProgramResources/Factory/ProgramResourcesFactory.hh>
#include <Render/ProgramResources/Types/BlockResources.hh>
#include <Render/ProgramResources/Types/UniformBlock.hh>
#include <Render/Program.hh>
#include <array>
#define LAMBDA_PROTO [this](GLint id, std::string &&name)
# define DECLAR_BUILDERS \
std::make_pair(GL_UNIFORM, LAMBDA_PROTO \
{ \
auto const nbr_prop = 2; \
std::array<GLenum, nbr_prop> const prop = {GL_TYPE, GL_BLOCK_INDEX }; \
std::array<GLint, nbr_prop> params; \
glGetProgramResourceiv(_program.id(), GL_UNIFORM, id, nbr_prop, prop.data(), nbr_prop, nullptr, params.data()); \
if (params[1] == -1) { \
return (_uniformsFactory.build(params[0], id, std::move(name))); \
} \
_block_resources.emplace_back(std::make_shared<BlockResources>(id, std::move(name), params[0]));\
return (std::unique_ptr<IProgramResources>(nullptr)); \
}), \
ProgramResourcesFactory::ProgramResourcesFactory(Program const &program) :
_program(program),
_blue_prints({ DECLAR_BUILDERS
std::make_pair(GL_UNIFORM_BLOCK, LAMBDA_PROTO
{
auto const nbr_prop = 2;
std::array<GLenum, nbr_prop> const prop = {GL_BUFFER_DATA_SIZE, GL_NUM_ACTIVE_VARIABLES};
std::array<GLint, nbr_prop> params;
glGetProgramResourceiv(_program.id(), GL_UNIFORM_BLOCK, id, nbr_prop, prop.data(), nbr_prop, nullptr, params.data());
std::vector<std::shared_ptr<BlockResources>> block_resources;
block_resources.reserve(params[1]);
GLenum const active_variable_prop = GL_ACTIVE_RESOURCES;
std::vector<GLint> active_variables(params[1]);
glGetProgramResourceiv(_program.id(), GL_UNIFORM_BLOCK, id, 1, &active_variable_prop, params[1], nullptr, active_variables.data());
for (auto index = 0ull; index < params[1]; ++index) {
for (auto &resource : _block_resources) {
if (resource->id() == active_variables[index]) {
block_resources.push_back(resource);
}
}
}
return (std::make_unique<UniformBlock>(id, std::move(name), std::move(block_resources), params[0]));
})
})
{
}
std::unique_ptr<IProgramResources> ProgramResourcesFactory::build(GLenum mode, GLint id, std::string &&name)
{
for (auto &blue_print : _blue_prints) {
if (mode == blue_print.first) {
return (blue_print.second(id, std::move(name)));
}
}
return (std::unique_ptr<IProgramResources>(nullptr));
}
<commit_msg>debuf uniform block introspection it works now :)<commit_after>#include <Render/ProgramResources/Factory/ProgramResourcesFactory.hh>
#include <Render/ProgramResources/Types/BlockResources.hh>
#include <Render/ProgramResources/Types/UniformBlock.hh>
#include <Render/Program.hh>
#include <array>
#define LAMBDA_PROTO [this](GLint id, std::string &&name)
# define DECLAR_BUILDERS \
std::make_pair(GL_UNIFORM, LAMBDA_PROTO \
{ \
auto const nbr_prop = 2; \
std::array<GLenum, nbr_prop> const prop = {GL_TYPE, GL_BLOCK_INDEX }; \
std::array<GLint, nbr_prop> params; \
glGetProgramResourceiv(_program.id(), GL_UNIFORM, id, nbr_prop, prop.data(), nbr_prop, nullptr, params.data()); \
if (params[1] == -1) { \
return (_uniformsFactory.build(params[0], id, std::move(name))); \
} \
_block_resources.emplace_back(std::make_shared<BlockResources>(id, std::move(name), params[0])); \
return (std::unique_ptr<IProgramResources>(nullptr)); \
}), \
\
std::make_pair(GL_UNIFORM_BLOCK, LAMBDA_PROTO \
{ \
auto const nbr_prop = 2; \
std::array<GLenum, nbr_prop> const prop = { GL_BUFFER_DATA_SIZE, GL_NUM_ACTIVE_VARIABLES }; \
std::array<GLint, nbr_prop> params; \
glGetProgramResourceiv(_program.id(), GL_UNIFORM_BLOCK, id, nbr_prop, prop.data(), nbr_prop, nullptr, params.data()); \
std::vector<std::shared_ptr<BlockResources>> block_resources; \
block_resources.reserve(params[1]); \
GLenum const active_variable_prop = GL_ACTIVE_VARIABLES; \
std::vector<GLint> active_variables(params[1]); \
glGetProgramResourceiv(_program.id(), GL_UNIFORM_BLOCK, id, 1, &active_variable_prop, params[1], nullptr, active_variables.data()); \
for (auto index = 0ull; index < params[1]; ++index) { \
for (auto &resource : _block_resources) { \
if (resource->id() == active_variables[index]) { \
block_resources.push_back(resource); \
} \
} \
} \
return (std::make_unique<UniformBlock>(id, std::move(name), std::move(block_resources), params[0])); \
})
ProgramResourcesFactory::ProgramResourcesFactory(Program const &program) :
_program(program),
_blue_prints({ DECLAR_BUILDERS })
{
}
std::unique_ptr<IProgramResources> ProgramResourcesFactory::build(GLenum mode, GLint id, std::string &&name)
{
for (auto &blue_print : _blue_prints) {
if (mode == blue_print.first) {
return (blue_print.second(id, std::move(name)));
}
}
return (std::unique_ptr<IProgramResources>(nullptr));
}
<|endoftext|>
|
<commit_before>#include <algorithm>
#include <fstream>
#include <ctime>
#include <set>
#ifdef WIN32
# define WIN32_LEAN_AND_MEAN
# include <Windows.h>
#else
# include <sys/stat.h>
#endif
#include "CLogger.hpp"
#include "CSampConfigReader.hpp"
#include "crashhandler.hpp"
#include "amx/amx2.h"
#include <fmt/format.h>
CLogManager::CLogManager() :
m_ThreadRunning(true)
{
crashhandler::Install();
if (CSampConfigReader::Get()->GetVar("logtimeformat", m_DateTimeFormat))
{
//delete brackets
size_t pos = 0;
while ((pos = m_DateTimeFormat.find_first_of("[]()")) != std::string::npos)
m_DateTimeFormat.erase(pos, 1);
}
else
{
m_DateTimeFormat = "%x %X";
}
CreateFolder("logs");
m_WarningLog.open("logs/warnings.log");
m_ErrorLog.open("logs/errors.log");
m_Thread = new std::thread(std::bind(&CLogManager::Process, this));
}
CLogManager::~CLogManager()
{
m_ThreadRunning = false;
m_QueueNotifier.notify_one();
m_Thread->join();
delete m_Thread;
}
void CLogManager::QueueLogMessage(Message_t &&msg)
{
{
std::lock_guard<std::mutex> lg(m_QueueMtx);
m_LogMsgQueue.push(std::move(msg));
}
m_QueueNotifier.notify_one();
}
void CLogManager::Process()
{
std::unique_lock<std::mutex> lk(m_QueueMtx);
std::set<size_t> HashedModules;
std::hash<std::string> StringHash;
do
{
m_QueueNotifier.wait(lk);
while (!m_LogMsgQueue.empty())
{
Message_t msg = std::move(m_LogMsgQueue.front());
m_LogMsgQueue.pop();
//manually unlock mutex
//the whole write-to-file code below has no need to be locked with the
//message queue mutex; while writing to the log file, new messages can
//now be queued
lk.unlock();
char timestamp[64];
std::time_t now_c = std::chrono::system_clock::to_time_t(msg->timestamp);
std::strftime(timestamp, sizeof(timestamp) / sizeof(char),
m_DateTimeFormat.c_str(), std::localtime(&now_c));
const char *loglevel_str = "<unknown>";
switch (msg->loglevel)
{
case LogLevel::DEBUG:
loglevel_str = "DEBUG";
break;
case LogLevel::INFO:
loglevel_str = "INFO";
break;
case LogLevel::WARNING:
loglevel_str = "WARNING";
break;
case LogLevel::ERROR:
loglevel_str = "ERROR";
break;
}
const string &modulename = msg->log_module;
size_t module_hash = StringHash(modulename);
if (HashedModules.find(module_hash) == HashedModules.end())
{
//create possibly non-existing folders before opening log file
size_t pos = 0;
while ((pos = modulename.find('/', pos)) != std::string::npos)
{
CreateFolder("logs/" + modulename.substr(0, pos++));
}
HashedModules.insert(module_hash);
}
//default logging
std::ofstream logfile("logs/" + modulename + ".log",
std::ofstream::out | std::ofstream::app);
logfile <<
"[" << timestamp << "] " <<
"[" << loglevel_str << "] " <<
msg->text;
if (msg->line != 0)
{
logfile << " (" << msg->file << ":" << msg->line << ")";
}
logfile << '\n' << std::flush;
//per-log-level logging
std::ofstream *loglevel_file = nullptr;
if (msg->loglevel & LogLevel::WARNING)
loglevel_file = &m_WarningLog;
else if (msg->loglevel & LogLevel::ERROR)
loglevel_file = &m_ErrorLog;
if (loglevel_file != nullptr)
{
(*loglevel_file) <<
"[" << timestamp << "] " <<
"[" << modulename << "] " <<
msg->text;
if (msg->line != 0)
{
(*loglevel_file) << " (" << msg->file << ":" << msg->line << ")";
}
(*loglevel_file) << '\n' << std::flush;
}
//lock the log message queue again (because while-condition and cv.wait)
lk.lock();
}
} while (m_ThreadRunning);
}
void CLogManager::CreateFolder(std::string foldername)
{
#ifdef WIN32
std::replace(foldername.begin(), foldername.end(), '/', '\\');
CreateDirectoryA(foldername.c_str(), NULL);
#else
std::replace(foldername.begin(), foldername.end(), '\\', '/');
mkdir(foldername.c_str(), ACCESSPERMS);
#endif
}
void samplog_Init()
{
CLogManager::Get()->IncreasePluginCounter();
}
void samplog_Exit()
{
CLogManager::Get()->DecreasePluginCounter();
}
bool samplog_LogMessage(const char *module, LogLevel level, const char *msg,
int line /*= 0*/, const char *file /*= ""*/, const char *func /*= ""*/)
{
if (module == nullptr || strlen(module) == 0)
return false;
CLogManager::Get()->QueueLogMessage(std::unique_ptr<CMessage>(new CMessage(
module, level, msg ? msg : "", line, file ? file : "", func ? func : "")));
return true;
}
bool samplog_LogNativeCall(const char *module,
AMX * const amx, const char *name, const char *params_format)
{
if (module == nullptr || strlen(module) == 0)
return false;
if (amx == nullptr)
return false;
if (name == nullptr || strlen(name) == 0)
return false;
if (params_format == nullptr) // params_format == "" is valid (no parameters)
return false;
const cell *params = CAmxDebugManager::Get()->GetNativeParamsPtr(amx);
if (params == nullptr)
return false;
size_t format_len = strlen(params_format);
fmt::MemoryWriter fmt_msg;
fmt_msg << name << '(';
for (int i = 0; i != format_len; ++i)
{
if (i != 0)
fmt_msg << ", ";
cell current_param = params[i + 1];
switch (params_format[i])
{
case 'd': //decimal
case 'i': //integer
fmt_msg << static_cast<int>(current_param);
break;
case 'f': //float
fmt_msg << amx_ctof(current_param);
break;
case 'h': //hexadecimal
case 'x': //
fmt_msg << fmt::hex(current_param);
break;
case 'b': //binary
fmt_msg << fmt::bin(current_param);
break;
case 's': //string
fmt_msg << '"' << amx_GetCppString(amx, current_param) << '"';
break;
case '*': //censored output
fmt_msg << "\"*****\"";
break;
case 'r': //reference
{
cell *addr_dest = nullptr;
amx_GetAddr(amx, current_param, &addr_dest);
fmt_msg << "0x" << fmt::pad(fmt::hexu(reinterpret_cast<unsigned int>(addr_dest)), 8, '0');
} break;
case 'p': //pointer-value
fmt_msg << "0x" << fmt::pad(fmt::hexu(current_param), 8, '0');
break;
default:
return false; //unrecognized format specifier
}
}
fmt_msg << ')';
int line = 0;
const char
*file = "",
*func = "";
CAmxDebugManager::Get()->GetLastAmxLine(amx, line);
CAmxDebugManager::Get()->GetLastAmxFile(amx, &file);
CAmxDebugManager::Get()->GetLastAmxFunction(amx, &func);
CLogManager::Get()->QueueLogMessage(std::unique_ptr<CMessage>(new CMessage(
module, LogLevel::DEBUG, fmt_msg.str(), line, file, func)));
return true;
}
<commit_msg>Remove line ending after timestamp<commit_after>#include <algorithm>
#include <fstream>
#include <ctime>
#include <set>
#ifdef WIN32
# define WIN32_LEAN_AND_MEAN
# include <Windows.h>
#else
# include <sys/stat.h>
#endif
#include "CLogger.hpp"
#include "CSampConfigReader.hpp"
#include "crashhandler.hpp"
#include "amx/amx2.h"
#include <fmt/format.h>
CLogManager::CLogManager() :
m_ThreadRunning(true)
{
crashhandler::Install();
if (CSampConfigReader::Get()->GetVar("logtimeformat", m_DateTimeFormat))
{
//delete brackets
size_t pos = 0;
while ((pos = m_DateTimeFormat.find_first_of("[]()")) != std::string::npos)
m_DateTimeFormat.erase(pos, 1);
}
else
{
m_DateTimeFormat = "%x %X";
}
CreateFolder("logs");
m_WarningLog.open("logs/warnings.log");
m_ErrorLog.open("logs/errors.log");
m_Thread = new std::thread(std::bind(&CLogManager::Process, this));
}
CLogManager::~CLogManager()
{
m_ThreadRunning = false;
m_QueueNotifier.notify_one();
m_Thread->join();
delete m_Thread;
}
void CLogManager::QueueLogMessage(Message_t &&msg)
{
{
std::lock_guard<std::mutex> lg(m_QueueMtx);
m_LogMsgQueue.push(std::move(msg));
}
m_QueueNotifier.notify_one();
}
void CLogManager::Process()
{
std::unique_lock<std::mutex> lk(m_QueueMtx);
std::set<size_t> HashedModules;
std::hash<std::string> StringHash;
do
{
m_QueueNotifier.wait(lk);
while (!m_LogMsgQueue.empty())
{
Message_t msg = std::move(m_LogMsgQueue.front());
m_LogMsgQueue.pop();
//manually unlock mutex
//the whole write-to-file code below has no need to be locked with the
//message queue mutex; while writing to the log file, new messages can
//now be queued
lk.unlock();
char timestamp[64];
std::time_t now_c = std::chrono::system_clock::to_time_t(msg->timestamp);
std::strftime(timestamp, sizeof(timestamp) / sizeof(char),
m_DateTimeFormat.c_str(), std::localtime(&now_c));
timestamp[strlen(timestamp) - 1] = '\0';
const char *loglevel_str = "<unknown>";
switch (msg->loglevel)
{
case LogLevel::DEBUG:
loglevel_str = "DEBUG";
break;
case LogLevel::INFO:
loglevel_str = "INFO";
break;
case LogLevel::WARNING:
loglevel_str = "WARNING";
break;
case LogLevel::ERROR:
loglevel_str = "ERROR";
break;
}
const string &modulename = msg->log_module;
size_t module_hash = StringHash(modulename);
if (HashedModules.find(module_hash) == HashedModules.end())
{
//create possibly non-existing folders before opening log file
size_t pos = 0;
while ((pos = modulename.find('/', pos)) != std::string::npos)
{
CreateFolder("logs/" + modulename.substr(0, pos++));
}
HashedModules.insert(module_hash);
}
//default logging
std::ofstream logfile("logs/" + modulename + ".log",
std::ofstream::out | std::ofstream::app);
logfile <<
"[" << timestamp << "] " <<
"[" << loglevel_str << "] " <<
msg->text;
if (msg->line != 0)
{
logfile << " (" << msg->file << ":" << msg->line << ")";
}
logfile << '\n' << std::flush;
//per-log-level logging
std::ofstream *loglevel_file = nullptr;
if (msg->loglevel & LogLevel::WARNING)
loglevel_file = &m_WarningLog;
else if (msg->loglevel & LogLevel::ERROR)
loglevel_file = &m_ErrorLog;
if (loglevel_file != nullptr)
{
(*loglevel_file) <<
"[" << timestamp << "] " <<
"[" << modulename << "] " <<
msg->text;
if (msg->line != 0)
{
(*loglevel_file) << " (" << msg->file << ":" << msg->line << ")";
}
(*loglevel_file) << '\n' << std::flush;
}
//lock the log message queue again (because while-condition and cv.wait)
lk.lock();
}
} while (m_ThreadRunning);
}
void CLogManager::CreateFolder(std::string foldername)
{
#ifdef WIN32
std::replace(foldername.begin(), foldername.end(), '/', '\\');
CreateDirectoryA(foldername.c_str(), NULL);
#else
std::replace(foldername.begin(), foldername.end(), '\\', '/');
mkdir(foldername.c_str(), ACCESSPERMS);
#endif
}
void samplog_Init()
{
CLogManager::Get()->IncreasePluginCounter();
}
void samplog_Exit()
{
CLogManager::Get()->DecreasePluginCounter();
}
bool samplog_LogMessage(const char *module, LogLevel level, const char *msg,
int line /*= 0*/, const char *file /*= ""*/, const char *func /*= ""*/)
{
if (module == nullptr || strlen(module) == 0)
return false;
CLogManager::Get()->QueueLogMessage(std::unique_ptr<CMessage>(new CMessage(
module, level, msg ? msg : "", line, file ? file : "", func ? func : "")));
return true;
}
bool samplog_LogNativeCall(const char *module,
AMX * const amx, const char *name, const char *params_format)
{
if (module == nullptr || strlen(module) == 0)
return false;
if (amx == nullptr)
return false;
if (name == nullptr || strlen(name) == 0)
return false;
if (params_format == nullptr) // params_format == "" is valid (no parameters)
return false;
const cell *params = CAmxDebugManager::Get()->GetNativeParamsPtr(amx);
if (params == nullptr)
return false;
size_t format_len = strlen(params_format);
fmt::MemoryWriter fmt_msg;
fmt_msg << name << '(';
for (int i = 0; i != format_len; ++i)
{
if (i != 0)
fmt_msg << ", ";
cell current_param = params[i + 1];
switch (params_format[i])
{
case 'd': //decimal
case 'i': //integer
fmt_msg << static_cast<int>(current_param);
break;
case 'f': //float
fmt_msg << amx_ctof(current_param);
break;
case 'h': //hexadecimal
case 'x': //
fmt_msg << fmt::hex(current_param);
break;
case 'b': //binary
fmt_msg << fmt::bin(current_param);
break;
case 's': //string
fmt_msg << '"' << amx_GetCppString(amx, current_param) << '"';
break;
case '*': //censored output
fmt_msg << "\"*****\"";
break;
case 'r': //reference
{
cell *addr_dest = nullptr;
amx_GetAddr(amx, current_param, &addr_dest);
fmt_msg << "0x" << fmt::pad(fmt::hexu(reinterpret_cast<unsigned int>(addr_dest)), 8, '0');
} break;
case 'p': //pointer-value
fmt_msg << "0x" << fmt::pad(fmt::hexu(current_param), 8, '0');
break;
default:
return false; //unrecognized format specifier
}
}
fmt_msg << ')';
int line = 0;
const char
*file = "",
*func = "";
CAmxDebugManager::Get()->GetLastAmxLine(amx, line);
CAmxDebugManager::Get()->GetLastAmxFile(amx, &file);
CAmxDebugManager::Get()->GetLastAmxFunction(amx, &func);
CLogManager::Get()->QueueLogMessage(std::unique_ptr<CMessage>(new CMessage(
module, LogLevel::DEBUG, fmt_msg.str(), line, file, func)));
return true;
}
<|endoftext|>
|
<commit_before>////////////////////////////////////////////////////////////
//
// DAGON - An Adventure Game Engine
// Copyright (c) 2012 Senscape s.r.l.
// All rights reserved.
//
// NOTICE: Senscape permits you to use, modify, and
// distribute this file in accordance with the terms of the
// license agreement accompanying it.
//
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include "DGConfig.h"
#include "DGFont.h"
#include "DGLog.h"
////////////////////////////////////////////////////////////
// Implementation - Constructor
////////////////////////////////////////////////////////////
DGFont::DGFont() {
config = &DGConfig::getInstance();
log = &DGLog::getInstance();
_isLoaded = false;
this->setType(DGObjectFont);
}
////////////////////////////////////////////////////////////
// Implementation - Destructor
////////////////////////////////////////////////////////////
DGFont::~DGFont() {
// Nothing to do here
}
////////////////////////////////////////////////////////////
// Implementation
////////////////////////////////////////////////////////////
void DGFont::clear() {
if (_isLoaded) {
glDeleteTextures(128, _textures);
free(_textures);
FT_Done_Face(_face);
}
}
bool DGFont::isLoaded() {
return _isLoaded;
}
void DGFont::print(int x, int y, const char* text, ...) {
if (!_isLoaded)
return;
char line[DGMaxFeedLength];
const char* c;
va_list ap;
if (text == NULL)
*line = 0;
else {
va_start(ap, text);
vsprintf(line, text, ap);
va_end(ap);
}
glPushAttrib(GL_CURRENT_BIT | GL_ENABLE_BIT | GL_TRANSFORM_BIT);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glPushMatrix();
glTranslatef(x, y, 0);
c = line;
for (int j = 0; j < strlen(line); j++) {
int ch = *c;
GLfloat texCoords[] = { 0, 0,
0, _glyph[ch].y,
_glyph[ch].x, _glyph[ch].y,
_glyph[ch].x, 0 };
GLshort coords[] = { 0, 0,
0, _glyph[ch].rows,
_glyph[ch].width, _glyph[ch].rows,
_glyph[ch].width, 0 };
glBindTexture(GL_TEXTURE_2D, _textures[ch]);
glTranslatef((GLfloat)_glyph[ch].left, 0, 0);
glPushMatrix();
glTranslatef(0, -(GLfloat)_glyph[ch].top + _height, 0);
glTexCoordPointer(2, GL_FLOAT, 0, texCoords);
glVertexPointer(2, GL_SHORT, 0, coords);
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
glPopMatrix();
glTranslatef((GLfloat)(_glyph[ch].advance >> 6), 0, 0);
c++;
}
glPopMatrix();
glPopAttrib();
}
// FIXME: This is a repeated method from DGRenderManager - it would be best to avoid this
void DGFont::setColor(int color) {
uint32_t aux = color;
uint8_t b = (aux & 0x000000ff);
uint8_t g = (aux & 0x0000ff00) >> 8;
uint8_t r = (aux & 0x00ff0000) >> 16;
uint8_t a = (aux & 0xff000000) >> 24;
glColor4f((float)(r / 255.0f), (float)(g / 255.0f), (float)(b / 255.0f), (float)(a / 255.f));
}
void DGFont::setDefault(unsigned int heightOfFont) {
_height = (float)heightOfFont;
// WARNING: That 49052 size may not be exact... Careful!
if (FT_New_Memory_Face(*_library, DGDefFontBinary, 49052, 0, &_face)) {
log->error(DGModFont, "%s", DGMsg260004);
return;
}
_loadFont();
_isLoaded = true;
}
void DGFont::setLibrary(FT_Library* library) {
_library = library;
}
void DGFont::setResource(const char* fromFileName, unsigned int heightOfFont) {
_height = (float)heightOfFont;
if (FT_New_Face(*_library, config->path(DGPathRes, fromFileName, DGObjectFont), 0, &_face)) {
log->error(DGModFont, "%s: %s", DGMsg260003, fromFileName);
return;
}
_loadFont();
_isLoaded = true;
}
////////////////////////////////////////////////////////////
// Implementation - Private methods
////////////////////////////////////////////////////////////
void DGFont::_loadFont() {
unsigned char ch;
FT_Set_Char_Size(_face, _height << 6, _height << 6, 96, 96);
_textures = (GLuint*)malloc(128 * sizeof(GLuint));
glGenTextures(128, _textures);
for (ch = 0; ch < 128; ch++) {
int width, height;
float x, y;
FT_Bitmap bitmap;
FT_BitmapGlyph bitmapGlyph;
FT_Glyph glyph;
GLubyte* expandedData;
if (FT_Load_Glyph(_face, FT_Get_Char_Index(_face, ch), FT_LOAD_DEFAULT)) {
log->error(DGModFont, "%s: %c", DGMsg260005, ch);
return;
}
if (FT_Get_Glyph(_face->glyph, &glyph)) {
log->error(DGModFont, "%s: %c", DGMsg260006, ch);
return;
}
// Test code to define a stroke
/*FT_Stroker stroker = NULL;
FT_Stroker_New(*_library, &stroker);
FT_Stroker_Set(stroker, 32,
FT_STROKER_LINECAP_BUTT,
FT_STROKER_LINEJOIN_MITER,
0);
FT_Glyph_Stroke(&glyph, stroker, 1);
FT_Stroker_Done(stroker);*/
FT_Glyph_To_Bitmap(&glyph, ft_render_mode_normal, 0, 1);
bitmapGlyph = (FT_BitmapGlyph)glyph;
bitmap = bitmapGlyph->bitmap;
width = _next(bitmap.width);
height = _next(bitmap.rows);
expandedData = (GLubyte*)malloc(2 * width * height); // FIXME: Is there a sizeof() missing here?
for (int j = 0; j < height; j++) {
for (int i = 0; i < width; i++) {
expandedData[2 * (i + j * width)] = expandedData[2 * (i + j * width) + 1] =
(i >= bitmap.width || j >= bitmap.rows) ?
0 : bitmap.buffer[i + bitmap.width * j];
}
}
x = (float)bitmap.width / (float)width;
y = (float)bitmap.rows / (float)height;
_glyph[ch].x = x;
_glyph[ch].y = y;
_glyph[ch].width = bitmap.width;
_glyph[ch].rows = bitmap.rows;
_glyph[ch].left = bitmapGlyph->left;
_glyph[ch].top = bitmapGlyph->top;
_glyph[ch].advance = _face->glyph->advance.x;
glBindTexture(GL_TEXTURE_2D, _textures[ch]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height,
0, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, expandedData);
free(expandedData);
}
}
int DGFont::_next(int a) {
int rval = 1;
while (rval < a) rval <<= 1;
return rval;
}
<commit_msg>Fix potential buffer overflow<commit_after>////////////////////////////////////////////////////////////
//
// DAGON - An Adventure Game Engine
// Copyright (c) 2012 Senscape s.r.l.
// All rights reserved.
//
// NOTICE: Senscape permits you to use, modify, and
// distribute this file in accordance with the terms of the
// license agreement accompanying it.
//
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include "DGConfig.h"
#include "DGFont.h"
#include "DGLog.h"
////////////////////////////////////////////////////////////
// Implementation - Constructor
////////////////////////////////////////////////////////////
DGFont::DGFont() {
config = &DGConfig::getInstance();
log = &DGLog::getInstance();
_isLoaded = false;
this->setType(DGObjectFont);
}
////////////////////////////////////////////////////////////
// Implementation - Destructor
////////////////////////////////////////////////////////////
DGFont::~DGFont() {
// Nothing to do here
}
////////////////////////////////////////////////////////////
// Implementation
////////////////////////////////////////////////////////////
void DGFont::clear() {
if (_isLoaded) {
glDeleteTextures(128, _textures);
free(_textures);
FT_Done_Face(_face);
}
}
bool DGFont::isLoaded() {
return _isLoaded;
}
static int vsnprintf_wrapper(
char *buf,
size_t size,
const char *format,
va_list ap
) {
int count = vsnprintf(buf, size, format, ap);
#ifndef _MSC_VER
if (count >= 0 && static_cast<size_t>(count) >= size)
count = size - 1;
#else
/* Microsoft's CRT returns a non-standard value, if vsnprintf() wants to
* write more than 'size' chars.
*/
if (count < 0)
count = size - 1;
#endif
return count;
}
void DGFont::print(int x, int y, const char* text, ...) {
if (!_isLoaded)
return;
char line[DGMaxFeedLength];
int length;
va_list ap;
if (text == NULL) {
*line = 0;
length = 0;
} else {
va_start(ap, text);
length = vsnprintf_wrapper(line, sizeof(line), text, ap);
va_end(ap);
}
glPushAttrib(GL_CURRENT_BIT | GL_ENABLE_BIT | GL_TRANSFORM_BIT);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glPushMatrix();
glTranslatef(x, y, 0);
for (const char* c = line; length > 0; c++, length--) {
int ch = *c;
GLfloat texCoords[] = { 0, 0,
0, _glyph[ch].y,
_glyph[ch].x, _glyph[ch].y,
_glyph[ch].x, 0 };
GLshort coords[] = { 0, 0,
0, _glyph[ch].rows,
_glyph[ch].width, _glyph[ch].rows,
_glyph[ch].width, 0 };
glBindTexture(GL_TEXTURE_2D, _textures[ch]);
glTranslatef((GLfloat)_glyph[ch].left, 0, 0);
glPushMatrix();
glTranslatef(0, -(GLfloat)_glyph[ch].top + _height, 0);
glTexCoordPointer(2, GL_FLOAT, 0, texCoords);
glVertexPointer(2, GL_SHORT, 0, coords);
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
glPopMatrix();
glTranslatef((GLfloat)(_glyph[ch].advance >> 6), 0, 0);
}
glPopMatrix();
glPopAttrib();
}
// FIXME: This is a repeated method from DGRenderManager - it would be best to avoid this
void DGFont::setColor(int color) {
uint32_t aux = color;
uint8_t b = (aux & 0x000000ff);
uint8_t g = (aux & 0x0000ff00) >> 8;
uint8_t r = (aux & 0x00ff0000) >> 16;
uint8_t a = (aux & 0xff000000) >> 24;
glColor4f((float)(r / 255.0f), (float)(g / 255.0f), (float)(b / 255.0f), (float)(a / 255.f));
}
void DGFont::setDefault(unsigned int heightOfFont) {
_height = (float)heightOfFont;
// WARNING: That 49052 size may not be exact... Careful!
if (FT_New_Memory_Face(*_library, DGDefFontBinary, 49052, 0, &_face)) {
log->error(DGModFont, "%s", DGMsg260004);
return;
}
_loadFont();
_isLoaded = true;
}
void DGFont::setLibrary(FT_Library* library) {
_library = library;
}
void DGFont::setResource(const char* fromFileName, unsigned int heightOfFont) {
_height = (float)heightOfFont;
if (FT_New_Face(*_library, config->path(DGPathRes, fromFileName, DGObjectFont), 0, &_face)) {
log->error(DGModFont, "%s: %s", DGMsg260003, fromFileName);
return;
}
_loadFont();
_isLoaded = true;
}
////////////////////////////////////////////////////////////
// Implementation - Private methods
////////////////////////////////////////////////////////////
void DGFont::_loadFont() {
unsigned char ch;
FT_Set_Char_Size(_face, _height << 6, _height << 6, 96, 96);
_textures = (GLuint*)malloc(128 * sizeof(GLuint));
glGenTextures(128, _textures);
for (ch = 0; ch < 128; ch++) {
int width, height;
float x, y;
FT_Bitmap bitmap;
FT_BitmapGlyph bitmapGlyph;
FT_Glyph glyph;
GLubyte* expandedData;
if (FT_Load_Glyph(_face, FT_Get_Char_Index(_face, ch), FT_LOAD_DEFAULT)) {
log->error(DGModFont, "%s: %c", DGMsg260005, ch);
return;
}
if (FT_Get_Glyph(_face->glyph, &glyph)) {
log->error(DGModFont, "%s: %c", DGMsg260006, ch);
return;
}
// Test code to define a stroke
/*FT_Stroker stroker = NULL;
FT_Stroker_New(*_library, &stroker);
FT_Stroker_Set(stroker, 32,
FT_STROKER_LINECAP_BUTT,
FT_STROKER_LINEJOIN_MITER,
0);
FT_Glyph_Stroke(&glyph, stroker, 1);
FT_Stroker_Done(stroker);*/
FT_Glyph_To_Bitmap(&glyph, ft_render_mode_normal, 0, 1);
bitmapGlyph = (FT_BitmapGlyph)glyph;
bitmap = bitmapGlyph->bitmap;
width = _next(bitmap.width);
height = _next(bitmap.rows);
expandedData = (GLubyte*)malloc(2 * width * height); // FIXME: Is there a sizeof() missing here?
for (int j = 0; j < height; j++) {
for (int i = 0; i < width; i++) {
expandedData[2 * (i + j * width)] = expandedData[2 * (i + j * width) + 1] =
(i >= bitmap.width || j >= bitmap.rows) ?
0 : bitmap.buffer[i + bitmap.width * j];
}
}
x = (float)bitmap.width / (float)width;
y = (float)bitmap.rows / (float)height;
_glyph[ch].x = x;
_glyph[ch].y = y;
_glyph[ch].width = bitmap.width;
_glyph[ch].rows = bitmap.rows;
_glyph[ch].left = bitmapGlyph->left;
_glyph[ch].top = bitmapGlyph->top;
_glyph[ch].advance = _face->glyph->advance.x;
glBindTexture(GL_TEXTURE_2D, _textures[ch]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height,
0, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, expandedData);
free(expandedData);
}
}
int DGFont::_next(int a) {
int rval = 1;
while (rval < a) rval <<= 1;
return rval;
}
<|endoftext|>
|
<commit_before>////////////////////////////////////////////////////////////
//
// DAGON - An Adventure Game Engine
// Copyright (c) 2012 Senscape s.r.l.
// All rights reserved.
//
// NOTICE: Senscape permits you to use, modify, and
// distribute this file in accordance with the terms of the
// license agreement accompanying it.
//
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include "DGConfig.h"
#include "DGFont.h"
#include "DGLog.h"
#include <algorithm>
#include <limits>
////////////////////////////////////////////////////////////
// Implementation - Constructor
////////////////////////////////////////////////////////////
DGFont::DGFont() {
config = &DGConfig::getInstance();
log = &DGLog::getInstance();
_isLoaded = false;
this->setType(DGObjectFont);
}
////////////////////////////////////////////////////////////
// Implementation - Destructor
////////////////////////////////////////////////////////////
DGFont::~DGFont() {
// Nothing to do here
}
////////////////////////////////////////////////////////////
// Implementation
////////////////////////////////////////////////////////////
void DGFont::clear() {
if (_isLoaded) {
glDeleteTextures(128, _textures);
free(_textures);
FT_Done_Face(_face);
}
}
bool DGFont::isLoaded() {
return _isLoaded;
}
#ifndef _MSC_VER
# define c99_vsnprintf vsnprintf
#else
/* Microsoft CRT vsnprintf() does not conform to C99.
* Credit goes to http://stackoverflow.com/a/8712996
*/
static int c99_vsnprintf(
char *buf,
size_t size,
const char *format,
va_list ap
) {
int count = (buf != NULL && size > 0) ?
_vsnprintf_s(buf, size, _TRUNCATE, format, ap) :
-1;
if (count < 0)
count = _vscprintf(format, ap);
return count;
}
#endif
template <size_t Size>
static inline int vsnprintf_truncate(
char (&buf)[Size],
const char *format,
va_list ap
) {
using namespace std;
return min<int>(
c99_vsnprintf(buf, Size, format, ap),
Size > 0 ? min<size_t>(Size - 1, numeric_limits<int>::max()) : 0);
}
void DGFont::print(int x, int y, const char* text, ...) {
if (!_isLoaded)
return;
char line[DGMaxFeedLength];
int length;
va_list ap;
if (text == NULL) {
*line = 0;
length = 0;
} else {
va_start(ap, text);
length = vsnprintf_truncate(line, text, ap);
va_end(ap);
}
glPushAttrib(GL_CURRENT_BIT | GL_ENABLE_BIT | GL_TRANSFORM_BIT);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glPushMatrix();
glTranslatef(x, y, 0);
for (const char* c = line; length > 0; c++, length--) {
int ch = *c;
GLfloat texCoords[] = { 0, 0,
0, _glyph[ch].y,
_glyph[ch].x, _glyph[ch].y,
_glyph[ch].x, 0 };
GLshort coords[] = { 0, 0,
0, _glyph[ch].rows,
_glyph[ch].width, _glyph[ch].rows,
_glyph[ch].width, 0 };
glBindTexture(GL_TEXTURE_2D, _textures[ch]);
glTranslatef((GLfloat)_glyph[ch].left, 0, 0);
glPushMatrix();
glTranslatef(0, -(GLfloat)_glyph[ch].top + _height, 0);
glTexCoordPointer(2, GL_FLOAT, 0, texCoords);
glVertexPointer(2, GL_SHORT, 0, coords);
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
glPopMatrix();
glTranslatef((GLfloat)(_glyph[ch].advance >> 6), 0, 0);
}
glPopMatrix();
glPopAttrib();
}
// FIXME: This is a repeated method from DGRenderManager - it would be best to avoid this
void DGFont::setColor(int color) {
uint32_t aux = color;
uint8_t b = (aux & 0x000000ff);
uint8_t g = (aux & 0x0000ff00) >> 8;
uint8_t r = (aux & 0x00ff0000) >> 16;
uint8_t a = (aux & 0xff000000) >> 24;
glColor4f((float)(r / 255.0f), (float)(g / 255.0f), (float)(b / 255.0f), (float)(a / 255.f));
}
void DGFont::setDefault(unsigned int heightOfFont) {
_height = (float)heightOfFont;
// WARNING: That 49052 size may not be exact... Careful!
if (FT_New_Memory_Face(*_library, DGDefFontBinary, 49052, 0, &_face)) {
log->error(DGModFont, "%s", DGMsg260004);
return;
}
_loadFont();
_isLoaded = true;
}
void DGFont::setLibrary(FT_Library* library) {
_library = library;
}
void DGFont::setResource(const char* fromFileName, unsigned int heightOfFont) {
_height = (float)heightOfFont;
if (FT_New_Face(*_library, config->path(DGPathRes, fromFileName, DGObjectFont), 0, &_face)) {
log->error(DGModFont, "%s: %s", DGMsg260003, fromFileName);
return;
}
_loadFont();
_isLoaded = true;
}
////////////////////////////////////////////////////////////
// Implementation - Private methods
////////////////////////////////////////////////////////////
void DGFont::_loadFont() {
unsigned char ch;
FT_Set_Char_Size(_face, _height << 6, _height << 6, 96, 96);
_textures = (GLuint*)malloc(128 * sizeof(GLuint));
glGenTextures(128, _textures);
for (ch = 0; ch < 128; ch++) {
int width, height;
float x, y;
FT_Bitmap bitmap;
FT_BitmapGlyph bitmapGlyph;
FT_Glyph glyph;
GLubyte* expandedData;
if (FT_Load_Glyph(_face, FT_Get_Char_Index(_face, ch), FT_LOAD_DEFAULT)) {
log->error(DGModFont, "%s: %c", DGMsg260005, ch);
return;
}
if (FT_Get_Glyph(_face->glyph, &glyph)) {
log->error(DGModFont, "%s: %c", DGMsg260006, ch);
return;
}
// Test code to define a stroke
/*FT_Stroker stroker = NULL;
FT_Stroker_New(*_library, &stroker);
FT_Stroker_Set(stroker, 32,
FT_STROKER_LINECAP_BUTT,
FT_STROKER_LINEJOIN_MITER,
0);
FT_Glyph_Stroke(&glyph, stroker, 1);
FT_Stroker_Done(stroker);*/
FT_Glyph_To_Bitmap(&glyph, ft_render_mode_normal, 0, 1);
bitmapGlyph = (FT_BitmapGlyph)glyph;
bitmap = bitmapGlyph->bitmap;
width = _next(bitmap.width);
height = _next(bitmap.rows);
expandedData = (GLubyte*)malloc(2 * width * height); // FIXME: Is there a sizeof() missing here?
for (int j = 0; j < height; j++) {
for (int i = 0; i < width; i++) {
expandedData[2 * (i + j * width)] = expandedData[2 * (i + j * width) + 1] =
(i >= bitmap.width || j >= bitmap.rows) ?
0 : bitmap.buffer[i + bitmap.width * j];
}
}
x = (float)bitmap.width / (float)width;
y = (float)bitmap.rows / (float)height;
_glyph[ch].x = x;
_glyph[ch].y = y;
_glyph[ch].width = bitmap.width;
_glyph[ch].rows = bitmap.rows;
_glyph[ch].left = bitmapGlyph->left;
_glyph[ch].top = bitmapGlyph->top;
_glyph[ch].advance = _face->glyph->advance.x;
glBindTexture(GL_TEXTURE_2D, _textures[ch]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height,
0, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, expandedData);
free(expandedData);
}
}
int DGFont::_next(int a) {
int rval = 1;
while (rval < a) rval <<= 1;
return rval;
}
<commit_msg>Now using vsnprintf() from C++11 to parse strings.<commit_after>////////////////////////////////////////////////////////////
//
// DAGON - An Adventure Game Engine
// Copyright (c) 2012 Senscape s.r.l.
// All rights reserved.
//
// NOTICE: Senscape permits you to use, modify, and
// distribute this file in accordance with the terms of the
// license agreement accompanying it.
//
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include "DGConfig.h"
#include "DGFont.h"
#include "DGLog.h"
////////////////////////////////////////////////////////////
// Implementation - Constructor
////////////////////////////////////////////////////////////
DGFont::DGFont() {
config = &DGConfig::getInstance();
log = &DGLog::getInstance();
_isLoaded = false;
this->setType(DGObjectFont);
}
////////////////////////////////////////////////////////////
// Implementation - Destructor
////////////////////////////////////////////////////////////
DGFont::~DGFont() {
// Nothing to do here
}
////////////////////////////////////////////////////////////
// Implementation
////////////////////////////////////////////////////////////
void DGFont::clear() {
if (_isLoaded) {
glDeleteTextures(128, _textures);
free(_textures);
FT_Done_Face(_face);
}
}
bool DGFont::isLoaded() {
return _isLoaded;
}
void DGFont::print(int x, int y, const char* text, ...) {
if (!_isLoaded)
return;
char line[DGMaxFeedLength];
int length;
va_list ap;
if (text == NULL) {
*line = 0;
length = 0;
} else {
va_start(ap, text);
// TODO: Test if vsnprintf() works as expected on VS 2012,
// otherwise use fix from main branch
length = vsnprintf(line, DGMaxFeedLength, text, ap);
va_end(ap);
}
glPushAttrib(GL_CURRENT_BIT | GL_ENABLE_BIT | GL_TRANSFORM_BIT);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glPushMatrix();
glTranslatef(x, y, 0);
for (const char* c = line; length > 0; c++, length--) {
int ch = *c;
GLfloat texCoords[] = { 0, 0,
0, _glyph[ch].y,
_glyph[ch].x, _glyph[ch].y,
_glyph[ch].x, 0 };
GLshort coords[] = { 0, 0,
0, _glyph[ch].rows,
_glyph[ch].width, _glyph[ch].rows,
_glyph[ch].width, 0 };
glBindTexture(GL_TEXTURE_2D, _textures[ch]);
glTranslatef((GLfloat)_glyph[ch].left, 0, 0);
glPushMatrix();
glTranslatef(0, -(GLfloat)_glyph[ch].top + _height, 0);
glTexCoordPointer(2, GL_FLOAT, 0, texCoords);
glVertexPointer(2, GL_SHORT, 0, coords);
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
glPopMatrix();
glTranslatef((GLfloat)(_glyph[ch].advance >> 6), 0, 0);
}
glPopMatrix();
glPopAttrib();
}
// FIXME: This is a repeated method from DGRenderManager - it would be best to avoid this
void DGFont::setColor(int color) {
uint32_t aux = color;
uint8_t b = (aux & 0x000000ff);
uint8_t g = (aux & 0x0000ff00) >> 8;
uint8_t r = (aux & 0x00ff0000) >> 16;
uint8_t a = (aux & 0xff000000) >> 24;
glColor4f((float)(r / 255.0f), (float)(g / 255.0f), (float)(b / 255.0f), (float)(a / 255.f));
}
void DGFont::setDefault(unsigned int heightOfFont) {
_height = (float)heightOfFont;
// WARNING: That 49052 size may not be exact... Careful!
if (FT_New_Memory_Face(*_library, DGDefFontBinary, 49052, 0, &_face)) {
log->error(DGModFont, "%s", DGMsg260004);
return;
}
_loadFont();
_isLoaded = true;
}
void DGFont::setLibrary(FT_Library* library) {
_library = library;
}
void DGFont::setResource(const char* fromFileName, unsigned int heightOfFont) {
_height = (float)heightOfFont;
if (FT_New_Face(*_library, config->path(DGPathRes, fromFileName, DGObjectFont), 0, &_face)) {
log->error(DGModFont, "%s: %s", DGMsg260003, fromFileName);
return;
}
_loadFont();
_isLoaded = true;
}
////////////////////////////////////////////////////////////
// Implementation - Private methods
////////////////////////////////////////////////////////////
void DGFont::_loadFont() {
unsigned char ch;
FT_Set_Char_Size(_face, _height << 6, _height << 6, 96, 96);
_textures = (GLuint*)malloc(128 * sizeof(GLuint));
glGenTextures(128, _textures);
for (ch = 0; ch < 128; ch++) {
int width, height;
float x, y;
FT_Bitmap bitmap;
FT_BitmapGlyph bitmapGlyph;
FT_Glyph glyph;
GLubyte* expandedData;
if (FT_Load_Glyph(_face, FT_Get_Char_Index(_face, ch), FT_LOAD_DEFAULT)) {
log->error(DGModFont, "%s: %c", DGMsg260005, ch);
return;
}
if (FT_Get_Glyph(_face->glyph, &glyph)) {
log->error(DGModFont, "%s: %c", DGMsg260006, ch);
return;
}
// Test code to define a stroke
/*FT_Stroker stroker = NULL;
FT_Stroker_New(*_library, &stroker);
FT_Stroker_Set(stroker, 32,
FT_STROKER_LINECAP_BUTT,
FT_STROKER_LINEJOIN_MITER,
0);
FT_Glyph_Stroke(&glyph, stroker, 1);
FT_Stroker_Done(stroker);*/
FT_Glyph_To_Bitmap(&glyph, ft_render_mode_normal, 0, 1);
bitmapGlyph = (FT_BitmapGlyph)glyph;
bitmap = bitmapGlyph->bitmap;
width = _next(bitmap.width);
height = _next(bitmap.rows);
expandedData = (GLubyte*)malloc(2 * width * height); // FIXME: Is there a sizeof() missing here?
for (int j = 0; j < height; j++) {
for (int i = 0; i < width; i++) {
expandedData[2 * (i + j * width)] = expandedData[2 * (i + j * width) + 1] =
(i >= bitmap.width || j >= bitmap.rows) ?
0 : bitmap.buffer[i + bitmap.width * j];
}
}
x = (float)bitmap.width / (float)width;
y = (float)bitmap.rows / (float)height;
_glyph[ch].x = x;
_glyph[ch].y = y;
_glyph[ch].width = bitmap.width;
_glyph[ch].rows = bitmap.rows;
_glyph[ch].left = bitmapGlyph->left;
_glyph[ch].top = bitmapGlyph->top;
_glyph[ch].advance = _face->glyph->advance.x;
glBindTexture(GL_TEXTURE_2D, _textures[ch]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height,
0, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, expandedData);
free(expandedData);
}
}
int DGFont::_next(int a) {
int rval = 1;
while (rval < a) rval <<= 1;
return rval;
}
<|endoftext|>
|
<commit_before>#include "GameController.hpp"
#include "Game.hpp"
#include "../GameLogic/FourInALine/Game.hpp"
#include "../GameLogic/FourInALine/AAI.hpp"
#include "../Highscore/database.h"
#include "../../app/FourInALine.hpp"
#include <QDebug>
#include <QTimer>
namespace Game
{
/**
* Creates a new game controller.
*
* @param parent Parent object.
*/
GameController::GameController(QObject *parent) :
QObject(parent), moveRequested(false), artificialIntelligence(4)
{
this->timeLimitTimer = new QTimer(this);
this->timeLimitTimer->setInterval(1000);
this->artificialIntelligenceTimer = new QTimer(this);
this->artificialIntelligenceTimer->setInterval(100);
this->connect(this->timeLimitTimer, &QTimer::timeout, this, &GameController::updateRemainingTime);
this->connect(this->artificialIntelligenceTimer, &QTimer::timeout, this, &GameController::checkHintReady);
}
/**
* Frees all used resources.
*/
GameController::~GameController()
{
this->endGame();
}
/**
* Starts a new game.
*
* @param game The game to start.
*/
void GameController::startGame(QSharedPointer<Game> game)
{
this->game = game;
this->moveRequested = false;
qDebug() << "[" << this << "::startGame ] " << "Started new game.";
qDebug() << "[" << this << "::startGame ] " << "Player 1:" << game->getFirstPlayer()->getName();
qDebug() << "[" << this << "::startGame ] " << "Player 2:" << game->getSecondPlayer()->getName();
this->connect(this->game->getFirstPlayer().data(), &::Game::Players::AbstractPlayer::moveReady, this,
&::Game::GameController::makeMove);
this->connect(this->game->getSecondPlayer().data(), &::Game::Players::AbstractPlayer::moveReady, this,
&::Game::GameController::makeMove);
emit this->gameStarted(game->getGameLogic()->getBoard()->getNumberOfColumns(),
game->getGameLogic()->getBoard()->getNumberOfRows(),
game->getFirstPlayer(),
game->getSecondPlayer(),
game->getGameLogic()->hasTimeLimit());
// Replay moves already made in case this game was loaded from a savegame.
auto replay = game->getGameLogic()->getReplay();
for (unsigned int i = 0; i < replay.size(); ++i)
{
auto player = game->playerIdToPlayer(replay[i].first);
auto movePosition = game->getGameLogic()->computeMovePosition(i);
emit this->startPlayerTurn(player);
emit this->setCell(movePosition.first, movePosition.second, player);
emit this->endPlayerTurn();
}
this->requestNextMove();
}
/**
* Ends the current game.
*/
void GameController::endGame()
{
qDebug() << "[" << this << "::endGame ] " << "Ended game.";
this->abortRequest();
this->game.reset();
emit this->gameEnded();
}
/**
* Shows a hint for the next move a player could make.
*/
void GameController::showHint()
{
qDebug() << "[" << this << "::showHint ] " << "Show hint";
if (!this->artificialIntelligence.isComputing())
{
this->artificialIntelligence.computeNextMoveAsynchronously(*this->game->getGameLogic());
this->artificialIntelligenceTimer->start();
}
}
/**
* Undoes the last move.
*/
void GameController::undoLastMove()
{
qDebug() << "[" << this << "::undoLastMove ] " << "Undo last move";
bool gameWasOverBefore = this->game->getGameLogic()->isOver();
this->abortRequest();
if (gameWasOverBefore)
{
auto winningCells = this->game->getGameLogic()->getBoard()->findWinningCells();
for (auto it = winningCells.begin(); it != winningCells.end(); it++)
{
emit this->setCellHighlighted(it.getXPosition(), it.getYPosition(), false);
}
}
auto nMoves = this->game->getGameLogic()->getNumberOfMoves();
auto position = this->game->getGameLogic()->computeMovePosition(nMoves - 1);
this->game->getGameLogic()->undoLastMove();
emit this->removeCell(position.first, position.second);
position = this->game->getGameLogic()->computeMovePosition(nMoves - 2);
this->game->getGameLogic()->undoLastMove();
emit this->removeCell(position.first, position.second);
if (gameWasOverBefore)
{
emit this->gameNotOverAnymore();
}
this->requestNextMove();
}
/**
* Makes a move at the given position.
*
* @param x X position of the column in which the token should be dropped.
*/
void GameController::makeMove(unsigned int x)
{
qDebug() << "[" << this << "::makeMove ] " << "Player " << game->getCurrentPlayer()->getName()
<< " made a move, token dropped in column " << x;
auto currentPlayer = game->getCurrentPlayer();
this->moveRequested = false;
this->timeLimitTimer->stop();
this->game->getGameLogic()->makeMove(x);
auto moveNo = this->game->getGameLogic()->getNumberOfMoves() - 1;
auto position = this->game->getGameLogic()->computeMovePosition(moveNo);
emit this->setCell(position.first, position.second, currentPlayer);
emit this->endPlayerTurn();
if (!this->checkGameOver())
{
this->requestNextMove();
}
}
/**
* Decrements remaining seconds by one and makes a timeout move when the player's time is up.
*/
void GameController::updateRemainingTime()
{
auto RANDOM_MOVE = ::GameLogic::FourInALine::Game::TimeoutAction::RANDOM_MOVE;
this->remainingSeconds--;
emit this->remainingTimeChanged(this->game->getGameLogic()->getTimeLimit(), this->remainingSeconds);
if (0 == this->remainingSeconds)
{
qDebug() << "[" << this << "::updateRemainingTime ] " << "Player "
<< game->getCurrentPlayer()->getName() << " timed out.";
this->game->getGameLogic()->makeTimeoutMove();
if (this->game->getGameLogic()->getTimeoutAction() == RANDOM_MOVE)
{
this->moveRequested = false;
this->timeLimitTimer->stop();
auto moveNo = this->game->getGameLogic()->getNumberOfMoves() - 1;
auto position = this->game->getGameLogic()->computeMovePosition(moveNo);
emit this->endPlayerTurn();
emit this->setCell(position.first, position.second, this->game->getCurrentPlayer());
}
else
{
this->abortRequest();
}
// When the timeout action is RANDOM_MOVE, the game is probably not over after a timeout.
if (!this->checkGameOver())
{
this->requestNextMove();
}
}
}
/**
* Checks whether the game is over and if yes stops timer and emits gameOver().
*
* @return When it is over true, otherwise false.
*/
bool GameController::checkGameOver()
{
QSharedPointer< ::GameLogic::FourInALine::Game> game = this->game->getGameLogic();
if (game->isOver())
{
auto board = game->getBoard();
auto winningCells = board->findWinningCells();
qDebug() << "[" << this << "::checkGameOver ] " << "Game is over.";
this->abortRequest();
if (this->game->getGameLogic()->hasTimeLimit())
{
this->remainingSeconds = 0;
this->timeLimitTimer->stop();
}
for (auto it = winningCells.begin(); it != winningCells.end(); it++)
{
emit this->setCellHighlighted(it.getXPosition(), it.getYPosition(), true);
}
emit this->gameOver(game->isDraw());
if (this->game->isSavingHighscore())
{
Database* database = ::FourInALine::getInstance()->getDatabase();
int result = 0;
if (game->isDraw())
result = 2;
else if (this->game->getWinningPlayer() == this->game->getFirstPlayer())
result = 1;
database->insertHighscore(this->game->getFirstPlayer()->getName(), this->game->getSecondPlayer()->getName(), result);
}
return true;
}
return false;
}
/**
* Aborts current request for the next move if there is one.
*/
void GameController::abortRequest()
{
if (!this->moveRequested)
{
return;
}
qDebug() << "[" << this << "::abortRequest ] " << "Aborting request for next move by "
<< game->getCurrentPlayer()->getName() << ".";
if (this->game->getGameLogic()->hasTimeLimit())
{
this->remainingSeconds = 0;
this->timeLimitTimer->stop();
}
emit this->endPlayerTurn();
this->game->getCurrentPlayer()->abortMove();
this->moveRequested = false;
}
/**
* Requests next move from the current player and starts timer if there is a time limit.
*/
void GameController::requestNextMove()
{
qDebug() << "[" << this << "::requestNextMove ] " << "Requesting next move from player "
<< this->game->getCurrentPlayer()->getName() << ".";
if (this->moveRequested)
{
qDebug() << "[" << this << "::requestNextMove ] " << "ERROR: There is already a move request.";
this->abortRequest();
}
emit this->startPlayerTurn(this->game->getCurrentPlayer());
this->game->getCurrentPlayer()->requestMove(this->game);
this->moveRequested = true;
if (this->game->getGameLogic()->hasTimeLimit())
{
this->remainingSeconds = this->game->getGameLogic()->getTimeLimit();
this->timeLimitTimer->start();
}
}
/**
* Checks whether the AI has finished computing the hint and emits the according signal if so.
*/
void GameController::checkHintReady()
{
if (this->artificialIntelligence.isNextMoveReady())
{
unsigned int nColumns = this->game->getGameLogic()->getBoard()->getNumberOfColumns();
std::vector<int> columnScores(nColumns);
for (unsigned int i = 0; i < nColumns; ++i)
{
columnScores[i] = -1;
}
unsigned int nextMove = this->artificialIntelligence.getNextMove();
columnScores[nextMove] = 100;
emit this->showColumnHints(columnScores);
this->artificialIntelligenceTimer->stop();
}
}
}
<commit_msg>Fixed bug that led to a crash when saving the highscores.<commit_after>#include "GameController.hpp"
#include "Game.hpp"
#include "../GameLogic/FourInALine/Game.hpp"
#include "../GameLogic/FourInALine/AAI.hpp"
#include "../Highscore/database.h"
#include "../../app/FourInALine.hpp"
#include <QDebug>
#include <QTimer>
namespace Game
{
/**
* Creates a new game controller.
*
* @param parent Parent object.
*/
GameController::GameController(QObject *parent) :
QObject(parent), moveRequested(false), artificialIntelligence(4)
{
this->timeLimitTimer = new QTimer(this);
this->timeLimitTimer->setInterval(1000);
this->artificialIntelligenceTimer = new QTimer(this);
this->artificialIntelligenceTimer->setInterval(100);
this->connect(this->timeLimitTimer, &QTimer::timeout, this, &GameController::updateRemainingTime);
this->connect(this->artificialIntelligenceTimer, &QTimer::timeout, this, &GameController::checkHintReady);
}
/**
* Frees all used resources.
*/
GameController::~GameController()
{
this->endGame();
}
/**
* Starts a new game.
*
* @param game The game to start.
*/
void GameController::startGame(QSharedPointer<Game> game)
{
this->game = game;
this->moveRequested = false;
qDebug() << "[" << this << "::startGame ] " << "Started new game.";
qDebug() << "[" << this << "::startGame ] " << "Player 1:" << game->getFirstPlayer()->getName();
qDebug() << "[" << this << "::startGame ] " << "Player 2:" << game->getSecondPlayer()->getName();
this->connect(this->game->getFirstPlayer().data(), &::Game::Players::AbstractPlayer::moveReady, this,
&::Game::GameController::makeMove);
this->connect(this->game->getSecondPlayer().data(), &::Game::Players::AbstractPlayer::moveReady, this,
&::Game::GameController::makeMove);
emit this->gameStarted(game->getGameLogic()->getBoard()->getNumberOfColumns(),
game->getGameLogic()->getBoard()->getNumberOfRows(),
game->getFirstPlayer(),
game->getSecondPlayer(),
game->getGameLogic()->hasTimeLimit());
// Replay moves already made in case this game was loaded from a savegame.
auto replay = game->getGameLogic()->getReplay();
for (unsigned int i = 0; i < replay.size(); ++i)
{
auto player = game->playerIdToPlayer(replay[i].first);
auto movePosition = game->getGameLogic()->computeMovePosition(i);
emit this->startPlayerTurn(player);
emit this->setCell(movePosition.first, movePosition.second, player);
emit this->endPlayerTurn();
}
this->requestNextMove();
}
/**
* Ends the current game.
*/
void GameController::endGame()
{
qDebug() << "[" << this << "::endGame ] " << "Ended game.";
this->abortRequest();
this->game.reset();
emit this->gameEnded();
}
/**
* Shows a hint for the next move a player could make.
*/
void GameController::showHint()
{
qDebug() << "[" << this << "::showHint ] " << "Show hint";
if (!this->artificialIntelligence.isComputing())
{
this->artificialIntelligence.computeNextMoveAsynchronously(*this->game->getGameLogic());
this->artificialIntelligenceTimer->start();
}
}
/**
* Undoes the last move.
*/
void GameController::undoLastMove()
{
qDebug() << "[" << this << "::undoLastMove ] " << "Undo last move";
bool gameWasOverBefore = this->game->getGameLogic()->isOver();
this->abortRequest();
if (gameWasOverBefore)
{
auto winningCells = this->game->getGameLogic()->getBoard()->findWinningCells();
for (auto it = winningCells.begin(); it != winningCells.end(); it++)
{
emit this->setCellHighlighted(it.getXPosition(), it.getYPosition(), false);
}
}
auto nMoves = this->game->getGameLogic()->getNumberOfMoves();
auto position = this->game->getGameLogic()->computeMovePosition(nMoves - 1);
this->game->getGameLogic()->undoLastMove();
emit this->removeCell(position.first, position.second);
position = this->game->getGameLogic()->computeMovePosition(nMoves - 2);
this->game->getGameLogic()->undoLastMove();
emit this->removeCell(position.first, position.second);
if (gameWasOverBefore)
{
emit this->gameNotOverAnymore();
}
this->requestNextMove();
}
/**
* Makes a move at the given position.
*
* @param x X position of the column in which the token should be dropped.
*/
void GameController::makeMove(unsigned int x)
{
qDebug() << "[" << this << "::makeMove ] " << "Player " << game->getCurrentPlayer()->getName()
<< " made a move, token dropped in column " << x;
auto currentPlayer = game->getCurrentPlayer();
this->moveRequested = false;
this->timeLimitTimer->stop();
this->game->getGameLogic()->makeMove(x);
auto moveNo = this->game->getGameLogic()->getNumberOfMoves() - 1;
auto position = this->game->getGameLogic()->computeMovePosition(moveNo);
emit this->setCell(position.first, position.second, currentPlayer);
emit this->endPlayerTurn();
if (!this->checkGameOver())
{
this->requestNextMove();
}
}
/**
* Decrements remaining seconds by one and makes a timeout move when the player's time is up.
*/
void GameController::updateRemainingTime()
{
auto RANDOM_MOVE = ::GameLogic::FourInALine::Game::TimeoutAction::RANDOM_MOVE;
this->remainingSeconds--;
emit this->remainingTimeChanged(this->game->getGameLogic()->getTimeLimit(), this->remainingSeconds);
if (0 == this->remainingSeconds)
{
qDebug() << "[" << this << "::updateRemainingTime ] " << "Player "
<< game->getCurrentPlayer()->getName() << " timed out.";
this->game->getGameLogic()->makeTimeoutMove();
if (this->game->getGameLogic()->getTimeoutAction() == RANDOM_MOVE)
{
this->moveRequested = false;
this->timeLimitTimer->stop();
auto moveNo = this->game->getGameLogic()->getNumberOfMoves() - 1;
auto position = this->game->getGameLogic()->computeMovePosition(moveNo);
emit this->endPlayerTurn();
emit this->setCell(position.first, position.second, this->game->getCurrentPlayer());
}
else
{
this->abortRequest();
}
// When the timeout action is RANDOM_MOVE, the game is probably not over after a timeout.
if (!this->checkGameOver())
{
this->requestNextMove();
}
}
}
/**
* Checks whether the game is over and if yes stops timer and emits gameOver().
*
* @return When it is over true, otherwise false.
*/
bool GameController::checkGameOver()
{
QSharedPointer< ::GameLogic::FourInALine::Game> game = this->game->getGameLogic();
if (game->isOver())
{
auto board = game->getBoard();
auto winningCells = board->findWinningCells();
qDebug() << "[" << this << "::checkGameOver ] " << "Game is over.";
this->abortRequest();
if (this->game->getGameLogic()->hasTimeLimit())
{
this->remainingSeconds = 0;
this->timeLimitTimer->stop();
}
for (auto it = winningCells.begin(); it != winningCells.end(); it++)
{
emit this->setCellHighlighted(it.getXPosition(), it.getYPosition(), true);
}
if (this->game->isSavingHighscore())
{
Database* database = ::FourInALine::getInstance()->getDatabase();
int result = 0;
if (game->isDraw())
result = 2;
else if (this->game->getWinningPlayer() == this->game->getFirstPlayer())
result = 1;
database->insertHighscore(this->game->getFirstPlayer()->getName(), this->game->getSecondPlayer()->getName(), result);
}
emit this->gameOver(game->isDraw());
// this->game could be a new game after gameOver has been emitted!
return true;
}
return false;
}
/**
* Aborts current request for the next move if there is one.
*/
void GameController::abortRequest()
{
if (!this->moveRequested)
{
return;
}
qDebug() << "[" << this << "::abortRequest ] " << "Aborting request for next move by "
<< game->getCurrentPlayer()->getName() << ".";
if (this->game->getGameLogic()->hasTimeLimit())
{
this->remainingSeconds = 0;
this->timeLimitTimer->stop();
}
emit this->endPlayerTurn();
this->game->getCurrentPlayer()->abortMove();
this->moveRequested = false;
}
/**
* Requests next move from the current player and starts timer if there is a time limit.
*/
void GameController::requestNextMove()
{
qDebug() << "[" << this << "::requestNextMove ] " << "Requesting next move from player "
<< this->game->getCurrentPlayer()->getName() << ".";
if (this->moveRequested)
{
qDebug() << "[" << this << "::requestNextMove ] " << "ERROR: There is already a move request.";
this->abortRequest();
}
emit this->startPlayerTurn(this->game->getCurrentPlayer());
this->game->getCurrentPlayer()->requestMove(this->game);
this->moveRequested = true;
if (this->game->getGameLogic()->hasTimeLimit())
{
this->remainingSeconds = this->game->getGameLogic()->getTimeLimit();
this->timeLimitTimer->start();
}
}
/**
* Checks whether the AI has finished computing the hint and emits the according signal if so.
*/
void GameController::checkHintReady()
{
if (this->artificialIntelligence.isNextMoveReady())
{
unsigned int nColumns = this->game->getGameLogic()->getBoard()->getNumberOfColumns();
std::vector<int> columnScores(nColumns);
for (unsigned int i = 0; i < nColumns; ++i)
{
columnScores[i] = -1;
}
unsigned int nextMove = this->artificialIntelligence.getNextMove();
columnScores[nextMove] = 100;
emit this->showColumnHints(columnScores);
this->artificialIntelligenceTimer->stop();
}
}
}
<|endoftext|>
|
<commit_before>#include "Context.h"
#include "Timing.h"
using namespace esp;
static ESP_TLS_DECL ThreadContext* _thread_context = nullptr;
static ProfileContext* _context = nullptr;
void ThreadContext::Zone(const char *zoneName)
{
ProfileEvent *ev = profileIntervalStack.Push();
ev->eventType = EV_ZONE_INTERVAL;
ev->timestamp = GetSystemTimestamp();
ev->frameNumber = frameNumber;
ev->eventNameRef = _context->MapStringToReference(zoneName);
}
void ThreadContext::End()
{
}
void ThreadContext::Sample(const char *probeName, const int32_t& value)
{
}
void ThreadContext::Sample(const char *probeName, const uint32_t& value)
{
}
void ThreadContext::Sample(const char *probeName, const float& value)
{
}
<commit_msg>Little bites. (I'm cooking supper.)<commit_after>#include "Context.h"
#include "Timing.h"
using namespace esp;
static ESP_TLS_DECL ThreadContext* _thread_context = nullptr;
static ProfileContext* _context = nullptr;
void ThreadContext::Zone(const char *zoneName)
{
ProfileEvent *parentZone = profileIntervalStack.Peek();
ProfileEvent *ev = profileIntervalStack.Push();
ev->eventType = EV_ZONE_INTERVAL;
ev->timestamp = GetSystemTimestamp();
ev->frameNumber = frameNumber;
ev->eventNameRef = _context->MapStringToReference(zoneName);
if (parentZone){
ev->parentEventRef = parentZone->id;
}
}
void ThreadContext::End()
{
}
void ThreadContext::Sample(const char *probeName, const int32_t& value)
{
}
void ThreadContext::Sample(const char *probeName, const uint32_t& value)
{
}
void ThreadContext::Sample(const char *probeName, const float& value)
{
}
<|endoftext|>
|
<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include "Context.hpp"
using std::map;
using std::string;
using std::endl;
using std::vector;
using std::unordered_set;
using std::unordered_map;
using namespace eddic;
vector<Context*> Context::contexts;
/*vector<OldContext*> OldContext::contexts;
unsigned int OldContext::currentVariable = 0;
OldContext::~OldContext() {
map<string, Variable*>::const_iterator it = variables.begin();
map<string, Variable*>::const_iterator end = variables.end();
for ( ; it != end; ++it) {
delete it->second;
}
}
Variable* OldContext::find(const std::string& variable) {
map<string, Variable*>::const_iterator it = variables.find(variable);
if (it == variables.end()) {
if (m_parent != NULL) {
return m_parent->find(variable);
}
return NULL;
}
return it->second;
}
bool OldContext::exists(const std::string& variable) const {
if (variables.find(variable) != variables.end()) {
return true;
}
if (m_parent != NULL) {
return m_parent->exists(variable);
}
return false;
}
unsigned int OldContext::index(const std::string& variable) const {
map<string, Variable*>::const_iterator it = variables.find(variable);
if (it == variables.end()) {
if (m_parent != NULL) {
return m_parent->index(variable);
}
return -1;
}
return it->second->index();
}
Variable* OldContext::create(const std::string& variable, Type type) {
Variable* v = new Variable(variable, type, currentVariable++);
variables[variable] = v;
return v;
}
void OldContext::write(AssemblyFileWriter& writer) {
map<string, Variable*>::const_iterator it = variables.begin();
map<string, Variable*>::const_iterator end = variables.end();
for ( ; it != end; ++it) {
if (it->second->type() == INT) {
writer.stream() << ".comm VI" << it->second->index() << ",4,4" << endl;
} else if (it->second->type() == STRING) {
writer.stream() << ".comm VS" << it->second->index() << ",8,4" << endl;
}
}
}
void OldContext::writeAll(AssemblyFileWriter& writer) {
for (vector<OldContext*>::const_iterator it = contexts.begin(); it != contexts.end(); ++it) {
(*it)->write(writer);
}
}
void OldContext::cleanup(){
for (vector<OldContext*>::const_iterator it = contexts.begin(); it != contexts.end(); ++it) {
delete *it;
}
}*/
Context::~Context() {
StoredVariables::const_iterator it = m_stored.begin();
StoredVariables::const_iterator end = m_stored.end();
for ( ; it != end; ++it) {
delete it->second;
}
}
void Context::storeVariable(const std::string& name, Variable* variable){
m_stored[name] = variable;
}
bool Context::exists(const std::string& variable) const {
bool found = m_visibles.find(variable) != m_visibles.end();
if(!found){
if(m_parent){
return m_parent->exists(variable);
}
}
return found;
}
Variable* Context::getVariable(const std::string& variable) const {
bool found = m_visibles.find(variable) != m_visibles.end();
if(!found){
if(m_parent){
return getVariable(variable);
}
}
return (*m_stored.find(variable)).second;
}
void Context::cleanup(){
for (vector<Context*>::const_iterator it = contexts.begin(); it != contexts.end(); ++it) {
delete *it;
}
}
void FunctionContext::write(AssemblyFileWriter& writer){
StoredVariables::const_iterator it = m_stored.begin();
StoredVariables::const_iterator end = m_stored.end();
int size = 0;
for ( ; it != end; ++it) {
if (it->second->type() == INT) {
size += 4;
} else if (it->second->type() == STRING) {
size += 8;
}
}
if(size > 0){
writer.stream() << "subl $" << size << " , %edx" << std::endl;
}
}
void FunctionContext::release(AssemblyFileWriter& writer){
StoredVariables::const_iterator it = m_stored.begin();
StoredVariables::const_iterator end = m_stored.end();
int size = 0;
for ( ; it != end; ++it) {
if (it->second->type() == INT) {
size += 4;
} else if (it->second->type() == STRING) {
size += 8;
}
}
if(size > 0){
writer.stream() << "addl $" << size << " , %edx" << std::endl;
}
}
void GlobalContext::write(AssemblyFileWriter& writer){
StoredVariables::const_iterator it = m_stored.begin();
StoredVariables::const_iterator end = m_stored.end();
for ( ; it != end; ++it) {
if (it->second->type() == INT) {
writer.stream() << ".comm VI" << it->second->position().name() << ",4,4" << endl;
} else if (it->second->type() == STRING) {
writer.stream() << ".comm VS" << it->second->position().name() << ",8,4" << endl;
}
}
}
Variable* GlobalContext::addVariable(const std::string& variable, Type type){
Position position(GLOBAL, variable);
Variable* v = new Variable(variable, type, position);
m_visibles.insert(variable);
storeVariable(variable, v);
return v;
}
Variable* FunctionContext::newVariable(const std::string& variable, Type type){
Position position(STACK, currentPosition);
currentPosition += type == INT ? 4 : 8;
return new Variable(variable, type, position);
}
Variable* FunctionContext::addVariable(const std::string& variable, Type type){
Variable* v = newVariable(variable, type);
m_visibles.insert(variable);
storeVariable(variable, v);
return v;
}
Variable* BlockContext::addVariable(const std::string& variable, Type type){
Variable* v = m_functionContext->newVariable(variable, type);
m_visibles.insert(variable);
m_functionContext->storeVariable(variable, v);
return v;
}
void Variable::moveToRegister(AssemblyFileWriter& writer, std::string reg){
if(m_type == INT){
if(m_position.isStack()){
writer.stream() << "movl -" << m_position.offset() << "(ebp), " << reg << endl;
} else if(m_position.isGlobal()){
writer.stream() << "movl VI" << m_position.name() << ", " << reg << endl;
}
} else if (m_type == STRING){
//TODO Should never be called
}
}
void Variable::moveToRegister(AssemblyFileWriter& writer, std::string reg1, std::string reg2){
if(m_type == INT){
//TODO Should never be called
} else if (m_type == STRING){
if(m_position.isStack()){
writer.stream() << "movl -" << m_position.offset() << "(ebp), " << reg1 << endl;
writer.stream() << "movl -" << (m_position.offset() + 4) << "(ebp), " << reg2 << endl;
} else {
writer.stream() << "movl VS" << m_position.name() << ", " << reg1 << endl;
writer.stream() << "movl VS" << m_position.name() << "+4, " << reg2 << endl;
}
}
}
void Variable::moveFromRegister(AssemblyFileWriter& writer, std::string reg){
if(m_type == INT){
if(m_position.isStack()){
writer.stream() << "movl " << reg << ", -" << m_position.offset() << "(ebp)" << endl;
} else if(m_position.isGlobal()){
writer.stream() << "movl " << reg << ", VI" << m_position.name() << endl;
}
} else if (m_type == STRING){
//TODO Should never be called
}
}
void Variable::moveFromRegister(AssemblyFileWriter& writer, std::string reg1, std::string reg2){
if(m_type == INT){
//TODO Should never be called
} else if (m_type == STRING){
if(m_position.isStack()){
writer.stream() << "movl " << reg1 << ", -" << m_position.offset() << "(ebp)" << endl;
writer.stream() << "movl " << reg2 << ", -" << (m_position.offset() + 4) << "(ebp)" << endl;
} else {
writer.stream() << "movl " << reg1 << ", VS" << m_position.name() << endl;
writer.stream() << "movl " << reg2 << ", VS" << m_position.name() << "+4" << endl;
}
}
}
void Variable::pushToStack(AssemblyFileWriter& writer){
switch (m_type) {
case INT:
if(m_position.isStack()){
writer.stream() << "pushl -" << m_position.offset() << "(ebp)" << std::endl;
} else if(m_position.isGlobal()){
writer.stream() << "pushl VI" << m_position.name() << std::endl;
}
break;
case STRING:
if(m_position.isStack()){
writer.stream() << "pushl -" << m_position.offset() << "(ebp)" << std::endl;
writer.stream() << "pushl -" << (m_position.offset() + 4) << "(ebp)" << std::endl;
} else if(m_position.isGlobal()){
writer.stream() << "pushl VS" << m_index << endl;
writer.stream() << "pushl VS" << m_index << "+4" << std::endl;
}
break;
}
}
void Variable::popFromStack(AssemblyFileWriter& writer){
switch (m_type) {
case INT:
writer.stream() << "movl (%esp), %eax" << endl;
writer.stream() << "addl $4, %esp" << endl;
moveFromRegister(writer, "%eax");
break;
case STRING:
writer.stream() << "movl (%esp), %eax" << endl;
writer.stream() << "movl 4(%esp), %ebx" << endl;
writer.stream() << "addl $8, %esp" << endl;
moveFromRegister(writer, "%eax", "%ebx");
break;
}
}
<commit_msg>Fix ASM output for variables in stack<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include "Context.hpp"
using std::map;
using std::string;
using std::endl;
using std::vector;
using std::unordered_set;
using std::unordered_map;
using namespace eddic;
vector<Context*> Context::contexts;
/*vector<OldContext*> OldContext::contexts;
unsigned int OldContext::currentVariable = 0;
OldContext::~OldContext() {
map<string, Variable*>::const_iterator it = variables.begin();
map<string, Variable*>::const_iterator end = variables.end();
for ( ; it != end; ++it) {
delete it->second;
}
}
Variable* OldContext::find(const std::string& variable) {
map<string, Variable*>::const_iterator it = variables.find(variable);
if (it == variables.end()) {
if (m_parent != NULL) {
return m_parent->find(variable);
}
return NULL;
}
return it->second;
}
bool OldContext::exists(const std::string& variable) const {
if (variables.find(variable) != variables.end()) {
return true;
}
if (m_parent != NULL) {
return m_parent->exists(variable);
}
return false;
}
unsigned int OldContext::index(const std::string& variable) const {
map<string, Variable*>::const_iterator it = variables.find(variable);
if (it == variables.end()) {
if (m_parent != NULL) {
return m_parent->index(variable);
}
return -1;
}
return it->second->index();
}
Variable* OldContext::create(const std::string& variable, Type type) {
Variable* v = new Variable(variable, type, currentVariable++);
variables[variable] = v;
return v;
}
void OldContext::write(AssemblyFileWriter& writer) {
map<string, Variable*>::const_iterator it = variables.begin();
map<string, Variable*>::const_iterator end = variables.end();
for ( ; it != end; ++it) {
if (it->second->type() == INT) {
writer.stream() << ".comm VI" << it->second->index() << ",4,4" << endl;
} else if (it->second->type() == STRING) {
writer.stream() << ".comm VS" << it->second->index() << ",8,4" << endl;
}
}
}
void OldContext::writeAll(AssemblyFileWriter& writer) {
for (vector<OldContext*>::const_iterator it = contexts.begin(); it != contexts.end(); ++it) {
(*it)->write(writer);
}
}
void OldContext::cleanup(){
for (vector<OldContext*>::const_iterator it = contexts.begin(); it != contexts.end(); ++it) {
delete *it;
}
}*/
Context::~Context() {
StoredVariables::const_iterator it = m_stored.begin();
StoredVariables::const_iterator end = m_stored.end();
for ( ; it != end; ++it) {
delete it->second;
}
}
void Context::storeVariable(const std::string& name, Variable* variable){
m_stored[name] = variable;
}
bool Context::exists(const std::string& variable) const {
bool found = m_visibles.find(variable) != m_visibles.end();
if(!found){
if(m_parent){
return m_parent->exists(variable);
}
}
return found;
}
Variable* Context::getVariable(const std::string& variable) const {
bool found = m_visibles.find(variable) != m_visibles.end();
if(!found){
if(m_parent){
return getVariable(variable);
}
}
return (*m_stored.find(variable)).second;
}
void Context::cleanup(){
for (vector<Context*>::const_iterator it = contexts.begin(); it != contexts.end(); ++it) {
delete *it;
}
}
void FunctionContext::write(AssemblyFileWriter& writer){
StoredVariables::const_iterator it = m_stored.begin();
StoredVariables::const_iterator end = m_stored.end();
int size = 0;
for ( ; it != end; ++it) {
if (it->second->type() == INT) {
size += 4;
} else if (it->second->type() == STRING) {
size += 8;
}
}
if(size > 0){
writer.stream() << "subl $" << size << " , %edx" << std::endl;
}
}
void FunctionContext::release(AssemblyFileWriter& writer){
StoredVariables::const_iterator it = m_stored.begin();
StoredVariables::const_iterator end = m_stored.end();
int size = 0;
for ( ; it != end; ++it) {
if (it->second->type() == INT) {
size += 4;
} else if (it->second->type() == STRING) {
size += 8;
}
}
if(size > 0){
writer.stream() << "addl $" << size << " , %edx" << std::endl;
}
}
void GlobalContext::write(AssemblyFileWriter& writer){
StoredVariables::const_iterator it = m_stored.begin();
StoredVariables::const_iterator end = m_stored.end();
for ( ; it != end; ++it) {
if (it->second->type() == INT) {
writer.stream() << ".comm VI" << it->second->position().name() << ",4,4" << endl;
} else if (it->second->type() == STRING) {
writer.stream() << ".comm VS" << it->second->position().name() << ",8,4" << endl;
}
}
}
Variable* GlobalContext::addVariable(const std::string& variable, Type type){
Position position(GLOBAL, variable);
Variable* v = new Variable(variable, type, position);
m_visibles.insert(variable);
storeVariable(variable, v);
return v;
}
Variable* FunctionContext::newVariable(const std::string& variable, Type type){
Position position(STACK, currentPosition);
currentPosition += type == INT ? 4 : 8;
return new Variable(variable, type, position);
}
Variable* FunctionContext::addVariable(const std::string& variable, Type type){
Variable* v = newVariable(variable, type);
m_visibles.insert(variable);
storeVariable(variable, v);
return v;
}
Variable* BlockContext::addVariable(const std::string& variable, Type type){
Variable* v = m_functionContext->newVariable(variable, type);
m_visibles.insert(variable);
m_functionContext->storeVariable(variable, v);
return v;
}
void Variable::moveToRegister(AssemblyFileWriter& writer, std::string reg){
if(m_type == INT){
if(m_position.isStack()){
writer.stream() << "movl -" << m_position.offset() << "(%ebp), " << reg << endl;
} else if(m_position.isGlobal()){
writer.stream() << "movl VI" << m_position.name() << ", " << reg << endl;
}
} else if (m_type == STRING){
//TODO Should never be called
}
}
void Variable::moveToRegister(AssemblyFileWriter& writer, std::string reg1, std::string reg2){
if(m_type == INT){
//TODO Should never be called
} else if (m_type == STRING){
if(m_position.isStack()){
writer.stream() << "movl -" << m_position.offset() << "(%ebp), " << reg1 << endl;
writer.stream() << "movl -" << (m_position.offset() + 4) << "(%ebp), " << reg2 << endl;
} else {
writer.stream() << "movl VS" << m_position.name() << ", " << reg1 << endl;
writer.stream() << "movl VS" << m_position.name() << "+4, " << reg2 << endl;
}
}
}
void Variable::moveFromRegister(AssemblyFileWriter& writer, std::string reg){
if(m_type == INT){
if(m_position.isStack()){
writer.stream() << "movl " << reg << ", -" << m_position.offset() << "(%ebp)" << endl;
} else if(m_position.isGlobal()){
writer.stream() << "movl " << reg << ", VI" << m_position.name() << endl;
}
} else if (m_type == STRING){
//TODO Should never be called
}
}
void Variable::moveFromRegister(AssemblyFileWriter& writer, std::string reg1, std::string reg2){
if(m_type == INT){
//TODO Should never be called
} else if (m_type == STRING){
if(m_position.isStack()){
writer.stream() << "movl " << reg1 << ", -" << m_position.offset() << "(%ebp)" << endl;
writer.stream() << "movl " << reg2 << ", -" << (m_position.offset() + 4) << "(%ebp)" << endl;
} else {
writer.stream() << "movl " << reg1 << ", VS" << m_position.name() << endl;
writer.stream() << "movl " << reg2 << ", VS" << m_position.name() << "+4" << endl;
}
}
}
void Variable::pushToStack(AssemblyFileWriter& writer){
switch (m_type) {
case INT:
if(m_position.isStack()){
writer.stream() << "pushl -" << m_position.offset() << "(%ebp)" << std::endl;
} else if(m_position.isGlobal()){
writer.stream() << "pushl VI" << m_position.name() << std::endl;
}
break;
case STRING:
if(m_position.isStack()){
writer.stream() << "pushl -" << m_position.offset() << "(%ebp)" << std::endl;
writer.stream() << "pushl -" << (m_position.offset() + 4) << "(%ebp)" << std::endl;
} else if(m_position.isGlobal()){
writer.stream() << "pushl VS" << m_index << endl;
writer.stream() << "pushl VS" << m_index << "+4" << std::endl;
}
break;
}
}
void Variable::popFromStack(AssemblyFileWriter& writer){
switch (m_type) {
case INT:
writer.stream() << "movl (%esp), %eax" << endl;
writer.stream() << "addl $4, %esp" << endl;
moveFromRegister(writer, "%eax");
break;
case STRING:
writer.stream() << "movl (%esp), %eax" << endl;
writer.stream() << "movl 4(%esp), %ebx" << endl;
writer.stream() << "addl $8, %esp" << endl;
moveFromRegister(writer, "%eax", "%ebx");
break;
}
}
<|endoftext|>
|
<commit_before>//////////////////////////////////////////////////////////////////////////////
// NoLifeClient - Part of the NoLifeStory project //
// Copyright © 2013 Peter Atashian //
// //
// 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 "layer.hpp"
#include "map.hpp"
#include <nx/nx.hpp>
namespace nl {
std::array<layer, 8> layers;
void layer::render() {
for (uint8_t i = 0; i < 8; ++i) {
//for (obj & o : layers[i].Objs) o.Render();
for (tile & t : layers[i].tiles) t.render();
//if (Player::Pos.layer == i) Player::Render();
}
}
void layer::load() {
for (uint8_t i = 0; i < 8; ++i) {
layer & l = layers[i];
node n = map::current[i];
node tn = nx::map["Tile"][n["info"]["tS"] + ".img"];
//l.Objs.clear();
//for (node nn : n["obj"]) l.Objs.emplace_back(nn);
//sort(l.Objs.begin(), l.Objs.end());
l.tiles.clear();
for (node nn : n["tile"]) l.tiles.emplace_back(nn, tn);
std::sort(l.tiles.begin(), l.tiles.end(), [](tile const & a, tile const & b) {
return a.z < b.z;
});
}
}
}<commit_msg>client: #include <algorithm> in layer.cpp<commit_after>//////////////////////////////////////////////////////////////////////////////
// NoLifeClient - Part of the NoLifeStory project //
// Copyright © 2013 Peter Atashian //
// //
// 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 "layer.hpp"
#include "map.hpp"
#include <nx/nx.hpp>
#include <algorithm>
namespace nl {
std::array<layer, 8> layers;
void layer::render() {
for (uint8_t i = 0; i < 8; ++i) {
//for (obj & o : layers[i].Objs) o.Render();
for (tile & t : layers[i].tiles) t.render();
//if (Player::Pos.layer == i) Player::Render();
}
}
void layer::load() {
for (uint8_t i = 0; i < 8; ++i) {
layer & l = layers[i];
node n = map::current[i];
node tn = nx::map["Tile"][n["info"]["tS"] + ".img"];
//l.Objs.clear();
//for (node nn : n["obj"]) l.Objs.emplace_back(nn);
//sort(l.Objs.begin(), l.Objs.end());
l.tiles.clear();
for (node nn : n["tile"]) l.tiles.emplace_back(nn, tn);
std::sort(l.tiles.begin(), l.tiles.end(), [](tile const & a, tile const & b) {
return a.z < b.z;
});
}
}
}
<|endoftext|>
|
<commit_before>/**
* @file Decoder.cpp
* @copyright (c) 2014 by Petr Zemek (s3rvac@gmail.com) and contributors
* @license BSD, see the @c LICENSE file for more details
* @brief Implementation of the Decoder class.
*/
#include "Decoder.h"
#include <cassert>
#include <regex>
#include <sstream>
#include "BInteger.h"
#include "BString.h"
#include "Utils.h"
namespace bencoding {
/**
* @brief Constructs a new exception with the given message.
*/
DecodingError::DecodingError(const std::string &what):
std::runtime_error(what) {}
/**
* @brief Constructs a decoder.
*/
Decoder::Decoder() {}
/**
* @brief Creates a new decoder.
*/
std::unique_ptr<Decoder> Decoder::create() {
return std::unique_ptr<Decoder>(new Decoder());
}
/**
* @brief Decodes the given bencoded data and returns them.
*/
std::unique_ptr<BItem> Decoder::decode(const std::string &data) {
std::istringstream input(data);
return decode(input);
}
/**
* @brief Reads all the data from the given @a input, decodes them and returns
* them.
*/
std::unique_ptr<BItem> Decoder::decode(std::istream &input) {
switch (input.peek()) {
case 'i':
return decodeInteger(input);
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
return decodeString(input);
default:
throw DecodingError(std::string("unexpected character: '") +
static_cast<char>(input.peek()) + "'");
}
assert(false && "should never happen");
return std::unique_ptr<BItem>();
}
/**
* @brief Decodes an integer from @a input.
*
* @par Format
* @code
* i<integer encoded in base ten ASCII>e
* @endcode
*
* @par Example
* @code
* i3e represents the integer 3
* @endcode
*
* Moreover, only the significant digits should be used, one cannot pad the
* integer with zeroes, such as @c i04e (see the <a
* href="https://wiki.theory.org/BitTorrentSpecification#Bencoding">
* specification</a>).
*/
std::unique_ptr<BInteger> Decoder::decodeInteger(std::istream &input) const {
return decodeEncodedInteger(readEncodedInteger(input));
}
/**
* @brief Reads an encoded integer from @a input.
*/
std::string Decoder::readEncodedInteger(std::istream &input) const {
// See the description of decodeInteger() for the format and example.
std::string encodedInteger;
bool encodedIntegerReadCorrectly = readUntil(input, encodedInteger, 'e');
if (!encodedIntegerReadCorrectly) {
throw DecodingError("error during the decoding of an integer near '" +
encodedInteger + "'");
}
return encodedInteger;
}
/**
* @brief Decodes the given encoded integer.
*/
std::unique_ptr<BInteger> Decoder::decodeEncodedInteger(
const std::string &encodedInteger) const {
// See the description of decodeInteger() for the format and example.
std::regex integerRegex("i([-+]?(0|[1-9][0-9]*))e");
std::smatch match;
bool valid = std::regex_match(encodedInteger, match, integerRegex);
if (!valid) {
throw DecodingError("encountered an encoded integer of invalid format: '" +
encodedInteger + "'");
}
BInteger::ValueType integerValue;
strToNum(match[1].str(), integerValue);
return BInteger::create(integerValue);
}
/**
* @brief Decodes a string from @a input.
*
* @par Format
* @code
* <string length encoded in base ten ASCII>:<string data>
* @endcode
*
* @par Example
* @code
* 4:test represents the string "test"
* @endcode
*/
std::unique_ptr<BString> Decoder::decodeString(std::istream &input) const {
std::string::size_type stringLength(readStringLength(input));
readColon(input);
std::string str(readStringOfGivenLength(input, stringLength));
return BString::create(str);
}
/**
* @brief Reads the string length from @a input, validates it, and returns it.
*/
std::string::size_type Decoder::readStringLength(std::istream &input) const {
std::string stringLengthInASCII;
bool stringLengthInASCIIReadCorrectly = readUpTo(input, stringLengthInASCII, ':');
if (!stringLengthInASCIIReadCorrectly) {
throw DecodingError("error during the decoding of a string near '" +
stringLengthInASCII + "'");
}
std::string::size_type stringLength;
bool stringLengthIsValid = strToNum(stringLengthInASCII, stringLength);
if (!stringLengthIsValid) {
throw DecodingError("invalid string length: '" + stringLengthInASCII + "'");
}
return stringLength;
}
/**
* @brief Reads a colon from @a input and discards it.
*/
void Decoder::readColon(std::istream &input) const {
int c = input.get();
if (c != ':') {
throw DecodingError("expected a colon (':'), got '" +
std::to_string(static_cast<char>(c)) + "'");
}
}
/**
* @brief Reads a string of the given @a length from @a input and returns it.
*/
std::string Decoder::readStringOfGivenLength(std::istream &input,
std::string::size_type length) const {
std::string str(length, char());
input.read(&str[0], length);
std::string::size_type numOfReadChars(input.gcount());
if (numOfReadChars != length) {
throw DecodingError("expected a string containing " + std::to_string(length) +
" characters, but read only " + std::to_string(numOfReadChars) +
" characters");
}
return str;
}
} // namespace bencoding
<commit_msg>Decoder: Enhance the formatting of the description of decode().<commit_after>/**
* @file Decoder.cpp
* @copyright (c) 2014 by Petr Zemek (s3rvac@gmail.com) and contributors
* @license BSD, see the @c LICENSE file for more details
* @brief Implementation of the Decoder class.
*/
#include "Decoder.h"
#include <cassert>
#include <regex>
#include <sstream>
#include "BInteger.h"
#include "BString.h"
#include "Utils.h"
namespace bencoding {
/**
* @brief Constructs a new exception with the given message.
*/
DecodingError::DecodingError(const std::string &what):
std::runtime_error(what) {}
/**
* @brief Constructs a decoder.
*/
Decoder::Decoder() {}
/**
* @brief Creates a new decoder.
*/
std::unique_ptr<Decoder> Decoder::create() {
return std::unique_ptr<Decoder>(new Decoder());
}
/**
* @brief Decodes the given bencoded @a data and returns them.
*/
std::unique_ptr<BItem> Decoder::decode(const std::string &data) {
std::istringstream input(data);
return decode(input);
}
/**
* @brief Reads all the data from the given @a input, decodes them and returns
* them.
*/
std::unique_ptr<BItem> Decoder::decode(std::istream &input) {
switch (input.peek()) {
case 'i':
return decodeInteger(input);
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
return decodeString(input);
default:
throw DecodingError(std::string("unexpected character: '") +
static_cast<char>(input.peek()) + "'");
}
assert(false && "should never happen");
return std::unique_ptr<BItem>();
}
/**
* @brief Decodes an integer from @a input.
*
* @par Format
* @code
* i<integer encoded in base ten ASCII>e
* @endcode
*
* @par Example
* @code
* i3e represents the integer 3
* @endcode
*
* Moreover, only the significant digits should be used, one cannot pad the
* integer with zeroes, such as @c i04e (see the <a
* href="https://wiki.theory.org/BitTorrentSpecification#Bencoding">
* specification</a>).
*/
std::unique_ptr<BInteger> Decoder::decodeInteger(std::istream &input) const {
return decodeEncodedInteger(readEncodedInteger(input));
}
/**
* @brief Reads an encoded integer from @a input.
*/
std::string Decoder::readEncodedInteger(std::istream &input) const {
// See the description of decodeInteger() for the format and example.
std::string encodedInteger;
bool encodedIntegerReadCorrectly = readUntil(input, encodedInteger, 'e');
if (!encodedIntegerReadCorrectly) {
throw DecodingError("error during the decoding of an integer near '" +
encodedInteger + "'");
}
return encodedInteger;
}
/**
* @brief Decodes the given encoded integer.
*/
std::unique_ptr<BInteger> Decoder::decodeEncodedInteger(
const std::string &encodedInteger) const {
// See the description of decodeInteger() for the format and example.
std::regex integerRegex("i([-+]?(0|[1-9][0-9]*))e");
std::smatch match;
bool valid = std::regex_match(encodedInteger, match, integerRegex);
if (!valid) {
throw DecodingError("encountered an encoded integer of invalid format: '" +
encodedInteger + "'");
}
BInteger::ValueType integerValue;
strToNum(match[1].str(), integerValue);
return BInteger::create(integerValue);
}
/**
* @brief Decodes a string from @a input.
*
* @par Format
* @code
* <string length encoded in base ten ASCII>:<string data>
* @endcode
*
* @par Example
* @code
* 4:test represents the string "test"
* @endcode
*/
std::unique_ptr<BString> Decoder::decodeString(std::istream &input) const {
std::string::size_type stringLength(readStringLength(input));
readColon(input);
std::string str(readStringOfGivenLength(input, stringLength));
return BString::create(str);
}
/**
* @brief Reads the string length from @a input, validates it, and returns it.
*/
std::string::size_type Decoder::readStringLength(std::istream &input) const {
std::string stringLengthInASCII;
bool stringLengthInASCIIReadCorrectly = readUpTo(input, stringLengthInASCII, ':');
if (!stringLengthInASCIIReadCorrectly) {
throw DecodingError("error during the decoding of a string near '" +
stringLengthInASCII + "'");
}
std::string::size_type stringLength;
bool stringLengthIsValid = strToNum(stringLengthInASCII, stringLength);
if (!stringLengthIsValid) {
throw DecodingError("invalid string length: '" + stringLengthInASCII + "'");
}
return stringLength;
}
/**
* @brief Reads a colon from @a input and discards it.
*/
void Decoder::readColon(std::istream &input) const {
int c = input.get();
if (c != ':') {
throw DecodingError("expected a colon (':'), got '" +
std::to_string(static_cast<char>(c)) + "'");
}
}
/**
* @brief Reads a string of the given @a length from @a input and returns it.
*/
std::string Decoder::readStringOfGivenLength(std::istream &input,
std::string::size_type length) const {
std::string str(length, char());
input.read(&str[0], length);
std::string::size_type numOfReadChars(input.gcount());
if (numOfReadChars != length) {
throw DecodingError("expected a string containing " + std::to_string(length) +
" characters, but read only " + std::to_string(numOfReadChars) +
" characters");
}
return str;
}
} // namespace bencoding
<|endoftext|>
|
<commit_before>/* --
* Copyright (C) 2013, George Makrydakis <irrequietus@gmail.com>
*
* This file is part of odreex.
*
* odreex 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.
*
* odreex 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
* odreex. If not, see http://www.gnu.org/licenses/.
*
*/
#ifndef _ODREEX_AMPLE_CHARSEQ_HH_
#define _ODREEX_AMPLE_CHARSEQ_HH_
#include <cstdint>
#include <type_traits>
#include <odreex/ppmpf/base.hh>
namespace odreex {
namespace ample {
/* NOTE: A prototypical template "metastring" implementation. Despite several
* advances in C++11, it is still not possible for a series of reasons to deploy
* strings as non type template parameters. Using the PPMPF_REPEAT macro family
* from the odreex ppmpf framework, we can "add" this facility without the need
* of a third party dependency. Null characters can be introduced in this
* "metastring" called charseq from now on. In a few words this macro expands
* as follows:
*
* Given : ample_charseq("hello, world")
* Equals: charseq<'h', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd'>
*
* And this is a regular type that can be used as a type parameter wherever this
* is applicable.
*/
template<char... Chars_C>
struct charseq {
static char const value[sizeof...(Chars_C)];
static std::size_t size = sizeof...(Chars_C);
template<std::size_t Z>
static constexpr uint16_t intfy_at(char const (&a)[Z], std::size_t N) {
return static_cast<uint16_t>(Z - 1 > N ? a[N] : 256);
}
template<uint16_t... Int_N>
struct intfy {
private:
template<typename, typename = intfy<>>
struct impl;
template<uint16_t X, uint16_t... A, uint16_t... B>
struct impl<intfy<X, A...>, intfy<B...>>
: std::conditional< (X == 256)
, impl< intfy<A...>, intfy<B...>>
, impl <intfy<A...>, intfy<B...,X>>>::type
{};
template<uint16_t... X>
struct impl<intfy<>, intfy<X...>> {
typedef charseq<static_cast<unsigned char>(X)...> type;
};
public:
typedef typename impl<intfy<Int_N...>>::type type;
};
};
template<char... X>
char const charseq<X...>::value[] = {
X...
};
} /* ample */
} /* odreex */
/* NOTE: ample_charseq(x) where x is a quoted string is the function macro doing
* the generation of the charsec<char...> equivalent type from the x string. The
* ample_charseq_intfy_at is left as a macro to use during generation. The
* PPMPF_HRMAX value is used for the time being as indicating the maximum string
* "length" allowed, which right now defaults to 64.
*/
#define ample_charseq_intfy_at(n,x) \
odreex::ample::charseq<>::intfy_at(x, n)
#define ample_charseq(x) \
typename odreex::ample::charseq<>::intfy< \
PPMPF_REPEATS(ample_charseq_intfy_at, PPMPF_COMMA, x) \
>::type
#endif /* _ODREEX_AMPLE_CHARSEQ_HH_ */
<commit_msg>Added a missing const specifier to charseq internals.<commit_after>/* --
* Copyright (C) 2013, George Makrydakis <irrequietus@gmail.com>
*
* This file is part of odreex.
*
* odreex 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.
*
* odreex 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
* odreex. If not, see http://www.gnu.org/licenses/.
*
*/
#ifndef _ODREEX_AMPLE_CHARSEQ_HH_
#define _ODREEX_AMPLE_CHARSEQ_HH_
#include <cstdint>
#include <type_traits>
#include <odreex/ppmpf/base.hh>
namespace odreex {
namespace ample {
/* NOTE: A prototypical template "metastring" implementation. Despite several
* advances in C++11, it is still not possible for a series of reasons to deploy
* strings as non type template parameters. Using the PPMPF_REPEAT macro family
* from the odreex ppmpf framework, we can "add" this facility without the need
* of a third party dependency. Null characters can be introduced in this
* "metastring" called charseq from now on. In a few words this macro expands
* as follows:
*
* Given : ample_charseq("hello, world")
* Equals: charseq<'h', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd'>
*
* And this is a regular type that can be used as a type parameter wherever this
* is applicable.
*/
template<char... Chars_C>
struct charseq {
static char const value[sizeof...(Chars_C)];
static std::size_t const size = sizeof...(Chars_C);
template<std::size_t Z>
static constexpr uint16_t intfy_at(char const (&a)[Z], std::size_t N) {
return static_cast<uint16_t>(Z - 1 > N ? a[N] : 256);
}
template<uint16_t... Int_N>
struct intfy {
private:
template<typename, typename = intfy<>>
struct impl;
template<uint16_t X, uint16_t... A, uint16_t... B>
struct impl<intfy<X, A...>, intfy<B...>>
: std::conditional< (X == 256)
, impl< intfy<A...>, intfy<B...>>
, impl <intfy<A...>, intfy<B...,X>>>::type
{};
template<uint16_t... X>
struct impl<intfy<>, intfy<X...>> {
typedef charseq<static_cast<unsigned char>(X)...> type;
};
public:
typedef typename impl<intfy<Int_N...>>::type type;
};
};
template<char... X>
char const charseq<X...>::value[] = {
X...
};
} /* ample */
} /* odreex */
/* NOTE: ample_charseq(x) where x is a quoted string is the function macro doing
* the generation of the charsec<char...> equivalent type from the x string. The
* ample_charseq_intfy_at is left as a macro to use during generation. The
* PPMPF_HRMAX value is used for the time being as indicating the maximum string
* "length" allowed, which right now defaults to 64.
*/
#define ample_charseq_intfy_at(n,x) \
odreex::ample::charseq<>::intfy_at(x, n)
#define ample_charseq(x) \
typename odreex::ample::charseq<>::intfy< \
PPMPF_REPEATS(ample_charseq_intfy_at, PPMPF_COMMA, x) \
>::type
#endif /* _ODREEX_AMPLE_CHARSEQ_HH_ */
<|endoftext|>
|
<commit_before>#include "foo_musicbrainz.h"
static const GUID guid_cfg_short_date = { 0x18734618, 0x7920, 0x4d24, { 0x84, 0xa1, 0xb9, 0xd6, 0x6e, 0xd8, 0x25, 0xbc } };
cfg_bool cfg_short_date(guid_cfg_short_date, false);
static const GUID guid_cfg_no_feat = { 0x98f9ce46, 0xe0c5, 0x48f4, { 0xa6, 0x3e, 0x19, 0x34, 0x39, 0x64, 0x35, 0x55 } };
cfg_bool cfg_no_feat(guid_cfg_no_feat, false);
static const GUID guid_cfg_write_ids = { 0x8c8b61e0, 0x8eea, 0x4c34, { 0x9a, 0x51, 0x4d, 0xa9, 0x9c, 0xec, 0xcb, 0xbc } };
cfg_bool cfg_write_ids(guid_cfg_write_ids, true);
static const GUID guid_cfg_albumtype = { 0xd8fdb1d8, 0xde2, 0x4f1f, { 0x85, 0x5a, 0xc0, 0x5, 0x98, 0x60, 0x9b, 0xe9 } };
cfg_bool cfg_albumtype(guid_cfg_albumtype, true);
static const GUID guid_cfg_albumstatus = { 0x57a8dddd, 0xdf24, 0x4fd3, { 0xac, 0x95, 0x6f, 0x8, 0x3, 0x26, 0x41, 0x7c } };
cfg_bool cfg_albumstatus(guid_cfg_albumstatus, true);
static const GUID guid_cfg_albumtype_data = { 0x20968c09, 0xb0d4, 0x4059, { 0xb8, 0x92, 0xda, 0x76, 0xf8, 0xe6, 0x51, 0x4e } };
cfg_string cfg_albumtype_data(guid_cfg_albumtype_data, "MUSICBRAINZ_ALBUMTYPE");
static const GUID guid_cfg_albumstatus_data = { 0x77182aac, 0x1caa, 0x4793, { 0xb7, 0x15, 0xcc, 0xf8, 0x97, 0xba, 0x11, 0x1a } };
cfg_string cfg_albumstatus_data(guid_cfg_albumstatus_data, "MUSICBRAINZ_ALBUMSTATUS");
class CPreferencesDialog : public CDialogImpl<CPreferencesDialog>
{
public:
enum { IDD = IDD_PREFERENCES };
BEGIN_MSG_MAP(CPreferencesDialog)
MSG_WM_INITDIALOG(OnInitDialog)
COMMAND_HANDLER_EX(IDC_SHORT_DATE, BN_CLICKED, OnShortDate)
COMMAND_HANDLER_EX(IDC_NO_FEAT, BN_CLICKED, OnNoFeat)
COMMAND_HANDLER_EX(IDC_WRITE_IDS, BN_CLICKED, OnWriteIDs)
COMMAND_HANDLER_EX(IDC_ALBUMTYPE, BN_CLICKED, OnAlbumType)
COMMAND_HANDLER_EX(IDC_ALBUMSTATUS, BN_CLICKED, OnAlbumStatus)
COMMAND_HANDLER_EX(IDC_ALBUMTYPE_DATA, EN_UPDATE, OnAlbumTypeUpdate)
COMMAND_HANDLER_EX(IDC_ALBUMSTATUS_DATA, EN_UPDATE, OnAlbumStatusUpdate)
END_MSG_MAP()
void OnFinalMessage(HWND hwnd)
{
delete this;
}
BOOL OnInitDialog(CWindow wndFocus, LPARAM lInitParam)
{
CEdit cfg_edit_albumtype_data = GetDlgItem(IDC_ALBUMTYPE_DATA);
CEdit cfg_edit_albumstatus_data = GetDlgItem(IDC_ALBUMSTATUS_DATA);
((CButton)GetDlgItem(IDC_SHORT_DATE)).SetCheck(cfg_short_date.get_value());
((CButton)GetDlgItem(IDC_NO_FEAT)).SetCheck(cfg_no_feat.get_value());
((CButton)GetDlgItem(IDC_WRITE_IDS)).SetCheck(cfg_write_ids.get_value());
((CButton)GetDlgItem(IDC_ALBUMTYPE)).SetCheck(cfg_albumtype.get_value());
((CButton)GetDlgItem(IDC_ALBUMSTATUS)).SetCheck(cfg_albumstatus.get_value());
uSetWindowText(cfg_edit_albumtype_data, cfg_albumtype_data);
uSetWindowText(cfg_edit_albumstatus_data, cfg_albumstatus_data);
if (cfg_albumtype.get_value()) cfg_edit_albumtype_data.EnableWindow(1);
if (cfg_albumstatus.get_value()) cfg_edit_albumstatus_data.EnableWindow(1);
return 0;
}
void OnShortDate(UINT uNotifyCode, int nID, CButton wndCtl)
{
cfg_short_date = (bool)wndCtl.GetCheck();
}
void OnNoFeat(UINT uNotifyCode, int nID, CButton wndCtl)
{
cfg_no_feat = (bool)wndCtl.GetCheck();
}
void OnWriteIDs(UINT uNotifyCode, int nID, CButton wndCtl)
{
cfg_write_ids = (bool)wndCtl.GetCheck();
}
void OnAlbumType(UINT uNotifyCode, int nID, CButton wndCtl)
{
cfg_albumtype = (bool)wndCtl.GetCheck();
GetDlgItem(IDC_ALBUMTYPE_DATA).EnableWindow(cfg_albumtype.get_value());
}
void OnAlbumStatus(UINT uNotifyCode, int nID, CButton wndCtl)
{
cfg_albumstatus = (bool)wndCtl.GetCheck();
GetDlgItem(IDC_ALBUMSTATUS_DATA).EnableWindow(cfg_albumstatus.get_value());
}
void OnAlbumTypeUpdate(UINT uNotifyCode, int nID, CWindow wndCtl)
{
uGetWindowText(wndCtl, cfg_albumtype_data);
}
void OnAlbumStatusUpdate(UINT uNotifyCode, int nID, CWindow wndCtl)
{
uGetWindowText(wndCtl, cfg_albumstatus_data);
}
};
class foo_mb_preferences_page : public preferences_page_v2
{
public:
HWND create(HWND parent)
{
CPreferencesDialog *PreferencesDialog = new CPreferencesDialog();
PreferencesDialog->Create(parent);
return PreferencesDialog->m_hWnd;
}
const char * get_name()
{
return "MusicBrainz Tagger";
}
GUID get_guid()
{
static const GUID guid_foo_mb_preferences_page = { 0x79179a37, 0x5942, 0x4fdf, { 0xbb, 0xb7, 0x93, 0xfd, 0x35, 0xfc, 0xfe, 0x97 } };
return guid_foo_mb_preferences_page;
}
GUID get_parent_guid()
{
return preferences_page::guid_tagging;
}
bool reset_query()
{
return true;
}
void reset()
{
cfg_short_date = false;
cfg_no_feat = false;
cfg_write_ids = true;
cfg_albumtype = true;
cfg_albumstatus = true;
cfg_albumtype_data = "MUSICBRAINZ_ALBUMTYPE";
cfg_albumstatus_data = "MUSICBRAINZ_ALBUMSTATUS";
}
double get_sort_priority()
{
return 0;
}
};
static preferences_page_factory_t<foo_mb_preferences_page> g_foo_mb_preferences_page_factory;
<commit_msg>Updated preferences page to use latest API<commit_after>#include "foo_musicbrainz.h"
static const GUID guid_cfg_short_date = { 0x18734618, 0x7920, 0x4d24, { 0x84, 0xa1, 0xb9, 0xd6, 0x6e, 0xd8, 0x25, 0xbc } };
cfg_bool cfg_short_date(guid_cfg_short_date, false);
static const GUID guid_cfg_no_feat = { 0x98f9ce46, 0xe0c5, 0x48f4, { 0xa6, 0x3e, 0x19, 0x34, 0x39, 0x64, 0x35, 0x55 } };
cfg_bool cfg_no_feat(guid_cfg_no_feat, false);
static const GUID guid_cfg_write_ids = { 0x8c8b61e0, 0x8eea, 0x4c34, { 0x9a, 0x51, 0x4d, 0xa9, 0x9c, 0xec, 0xcb, 0xbc } };
cfg_bool cfg_write_ids(guid_cfg_write_ids, true);
static const GUID guid_cfg_albumtype = { 0xd8fdb1d8, 0xde2, 0x4f1f, { 0x85, 0x5a, 0xc0, 0x5, 0x98, 0x60, 0x9b, 0xe9 } };
cfg_bool cfg_albumtype(guid_cfg_albumtype, true);
static const GUID guid_cfg_albumstatus = { 0x57a8dddd, 0xdf24, 0x4fd3, { 0xac, 0x95, 0x6f, 0x8, 0x3, 0x26, 0x41, 0x7c } };
cfg_bool cfg_albumstatus(guid_cfg_albumstatus, true);
static const GUID guid_cfg_albumtype_data = { 0x20968c09, 0xb0d4, 0x4059, { 0xb8, 0x92, 0xda, 0x76, 0xf8, 0xe6, 0x51, 0x4e } };
cfg_string cfg_albumtype_data(guid_cfg_albumtype_data, "MUSICBRAINZ_ALBUMTYPE");
static const GUID guid_cfg_albumstatus_data = { 0x77182aac, 0x1caa, 0x4793, { 0xb7, 0x15, 0xcc, 0xf8, 0x97, 0xba, 0x11, 0x1a } };
cfg_string cfg_albumstatus_data(guid_cfg_albumstatus_data, "MUSICBRAINZ_ALBUMSTATUS");
class PreferencesPageInstance : public CDialogImpl<PreferencesPageInstance>, public preferences_page_instance {
private:
CButton short_date_checkbox;
CButton no_feat_checkbox;
CButton write_ids_checkbox;
CButton write_albumtype_checkbox;
CButton write_albumstatus_checkbox;
CEdit albumtype;
CEdit albumstatus;
preferences_page_callback::ptr on_change_callback;
public:
PreferencesPageInstance(preferences_page_callback::ptr callback) : on_change_callback(callback) {}
enum { IDD = IDD_PREFERENCES };
BEGIN_MSG_MAP(CPreferencesDialog)
MSG_WM_INITDIALOG(OnInitDialog)
COMMAND_HANDLER_EX(IDC_SHORT_DATE, BN_CLICKED, OnChanged)
COMMAND_HANDLER_EX(IDC_NO_FEAT, BN_CLICKED, OnChanged)
COMMAND_HANDLER_EX(IDC_WRITE_IDS, BN_CLICKED, OnChanged)
COMMAND_HANDLER_EX(IDC_ALBUMTYPE, BN_CLICKED, OnAlbumType)
COMMAND_HANDLER_EX(IDC_ALBUMSTATUS, BN_CLICKED, OnAlbumStatus)
COMMAND_HANDLER_EX(IDC_ALBUMTYPE_DATA, EN_UPDATE, OnChanged)
COMMAND_HANDLER_EX(IDC_ALBUMSTATUS_DATA, EN_UPDATE, OnChanged)
END_MSG_MAP()
BOOL OnInitDialog(CWindow wndFocus, LPARAM lInitParam) {
short_date_checkbox = GetDlgItem(IDC_SHORT_DATE);
no_feat_checkbox = GetDlgItem(IDC_NO_FEAT);
write_ids_checkbox = GetDlgItem(IDC_WRITE_IDS);
write_albumtype_checkbox = GetDlgItem(IDC_ALBUMTYPE);
write_albumstatus_checkbox = GetDlgItem(IDC_ALBUMSTATUS);
albumtype = GetDlgItem(IDC_ALBUMTYPE_DATA);
albumstatus = GetDlgItem(IDC_ALBUMSTATUS_DATA);
short_date_checkbox.SetCheck(cfg_short_date.get_value());
no_feat_checkbox.SetCheck(cfg_no_feat.get_value());
write_ids_checkbox.SetCheck(cfg_write_ids.get_value());
write_albumtype_checkbox.SetCheck(cfg_albumtype.get_value());
write_albumstatus_checkbox.SetCheck(cfg_albumstatus.get_value());
uSetWindowText(albumtype, cfg_albumtype_data);
uSetWindowText(albumstatus, cfg_albumstatus_data);
if (cfg_albumtype.get_value()) albumtype.EnableWindow(true);
if (cfg_albumstatus.get_value()) albumstatus.EnableWindow(true);
return 0;
}
bool has_changed() {
if ((bool)short_date_checkbox.GetCheck() != cfg_short_date.get_value()) return true;
if ((bool)no_feat_checkbox.GetCheck() != cfg_no_feat.get_value()) return true;
if ((bool)write_ids_checkbox.GetCheck() != cfg_write_ids.get_value()) return true;
if ((bool)write_albumtype_checkbox.GetCheck() != cfg_albumtype.get_value()) return true;
if ((bool)write_albumstatus_checkbox.GetCheck() != cfg_albumstatus.get_value()) return true;
pfc::string8 temp;
uGetWindowText(albumtype, temp);
if (cfg_albumtype_data != temp) return true;
uGetWindowText(albumstatus, temp);
if (cfg_albumstatus_data != temp) return true;
return false;
}
t_uint32 get_state() {
t_uint32 state = preferences_state::resettable;
if (has_changed()) state |= preferences_state::changed;
return state;
}
void apply() {
cfg_short_date = (bool)short_date_checkbox.GetCheck();
cfg_no_feat = (bool)no_feat_checkbox.GetCheck();
cfg_write_ids = (bool)write_ids_checkbox.GetCheck();
cfg_albumtype = (bool)write_albumtype_checkbox.GetCheck();
cfg_albumstatus = (bool)write_albumstatus_checkbox.GetCheck();
uGetWindowText(albumtype, cfg_albumtype_data);
uGetWindowText(albumstatus, cfg_albumstatus_data);
}
void on_change() {
on_change_callback->on_state_changed();
}
void reset() {
short_date_checkbox.SetCheck(false);
no_feat_checkbox.SetCheck(false);
write_ids_checkbox.SetCheck(true);
write_albumtype_checkbox.SetCheck(true);
write_albumstatus_checkbox.SetCheck(true);
uSetWindowText(albumtype, "MUSICBRAINZ_ALBUMTYPE");
uSetWindowText(albumstatus, "MUSICBRAINZ_ALBUMSTATUS");
on_change();
}
void OnChanged(UINT, int, HWND) {
on_change();
}
void OnAlbumType(UINT, int, CButton) {
albumtype.EnableWindow((bool)write_albumtype_checkbox.GetCheck());
on_change();
}
void OnAlbumStatus(UINT, int, CButton) {
albumstatus.EnableWindow((bool)write_albumstatus_checkbox.GetCheck());
on_change();
}
};
class PreferencesPage : public preferences_page_impl<PreferencesPageInstance> {
public:
const char * get_name() {
return "MusicBrainz Tagger";
}
GUID get_guid() {
static const GUID guid = { 0x79179a37, 0x5942, 0x4fdf, { 0xbb, 0xb7, 0x93, 0xfd, 0x35, 0xfc, 0xfe, 0x97 } };
return guid;
}
GUID get_parent_guid() {
return preferences_page::guid_tagging;
}
};
preferences_page_factory_t<PreferencesPage> _;
<|endoftext|>
|
<commit_before>/*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* StreamingClient.cpp
* Implementation of Streaming Client
* Copyright (C) 2005-2008 Simon Newton
*/
#include <ola/BaseTypes.h>
#include <ola/Closure.h>
#include <ola/DmxBuffer.h>
#include <ola/Logging.h>
#include <ola/StreamingClient.h>
#include "common/protocol/Ola.pb.h"
#include "common/rpc/StreamRpcChannel.h"
namespace ola {
using ola::rpc::StreamRpcChannel;
using ola::proto::OlaServerService_Stub;
StreamingClient::StreamingClient()
: m_socket(NULL),
m_closure(NULL),
m_channel(NULL),
m_stub(NULL) {
}
StreamingClient::~StreamingClient() {
Stop();
}
/*
* Setup the Streaming Client
*
* @returns true on success, false on failure
*/
bool StreamingClient::Setup() {
if (!m_socket) {
m_socket = TcpSocket::Connect("127.0.0.1", OLA_DEFAULT_PORT);
if (!m_socket) {
return false;
}
}
m_socket->SetOnClose(
NewSingleClosure(this, &StreamingClient::SocketClosed));
m_channel = new StreamRpcChannel(NULL, m_socket);
if (!m_channel) {
delete m_socket;
m_socket = NULL;
return false;
}
m_stub = new OlaServerService_Stub(m_channel);
if (!m_stub) {
delete m_channel;
delete m_socket;
m_channel = NULL;
m_socket = NULL;
return false;
}
return true;
}
/*
* Close the ola connection.
* @return true on sucess, false on failure
*/
void StreamingClient::Stop() {
if (m_stub)
delete m_stub;
if (m_channel)
delete m_channel;
if (m_socket)
delete m_socket;
m_stub = NULL;
m_channel = NULL;
m_socket = NULL;
}
/*
* Send DMX to the remote OLA server
*/
bool StreamingClient::SendDmx(unsigned int universe,
const DmxBuffer &data) const {
if (!m_stub || m_socket->CheckIfClosed())
return false;
ola::proto::DmxData request;
request.set_universe(universe);
request.set_data(data.Get());
m_stub->StreamDmxData(NULL, &request, NULL, NULL);
return true;
}
/*
* Called when the socket is closed
*/
int StreamingClient::SocketClosed() {
OLA_WARN << "The RPC socket has been closed, this is more than likely due"
<< "to a framing error, perhaps you're sending too fast?";
if (m_closure)
m_closure->Run();
return 0;
}
} // ola
<commit_msg> * fix the error message<commit_after>/*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* StreamingClient.cpp
* Implementation of Streaming Client
* Copyright (C) 2005-2008 Simon Newton
*/
#include <ola/BaseTypes.h>
#include <ola/Closure.h>
#include <ola/DmxBuffer.h>
#include <ola/Logging.h>
#include <ola/StreamingClient.h>
#include "common/protocol/Ola.pb.h"
#include "common/rpc/StreamRpcChannel.h"
namespace ola {
using ola::rpc::StreamRpcChannel;
using ola::proto::OlaServerService_Stub;
StreamingClient::StreamingClient()
: m_socket(NULL),
m_closure(NULL),
m_channel(NULL),
m_stub(NULL) {
}
StreamingClient::~StreamingClient() {
Stop();
}
/*
* Setup the Streaming Client
*
* @returns true on success, false on failure
*/
bool StreamingClient::Setup() {
if (!m_socket) {
m_socket = TcpSocket::Connect("127.0.0.1", OLA_DEFAULT_PORT);
if (!m_socket) {
return false;
}
}
m_socket->SetOnClose(
NewSingleClosure(this, &StreamingClient::SocketClosed));
m_channel = new StreamRpcChannel(NULL, m_socket);
if (!m_channel) {
delete m_socket;
m_socket = NULL;
return false;
}
m_stub = new OlaServerService_Stub(m_channel);
if (!m_stub) {
delete m_channel;
delete m_socket;
m_channel = NULL;
m_socket = NULL;
return false;
}
return true;
}
/*
* Close the ola connection.
* @return true on sucess, false on failure
*/
void StreamingClient::Stop() {
if (m_stub)
delete m_stub;
if (m_channel)
delete m_channel;
if (m_socket)
delete m_socket;
m_stub = NULL;
m_channel = NULL;
m_socket = NULL;
}
/*
* Send DMX to the remote OLA server
*/
bool StreamingClient::SendDmx(unsigned int universe,
const DmxBuffer &data) const {
if (!m_stub || m_socket->CheckIfClosed())
return false;
ola::proto::DmxData request;
request.set_universe(universe);
request.set_data(data.Get());
m_stub->StreamDmxData(NULL, &request, NULL, NULL);
return true;
}
/*
* Called when the socket is closed
*/
int StreamingClient::SocketClosed() {
OLA_WARN << "The RPC socket has been closed, this is more than likely due"
<< " to a framing error, perhaps you're sending too fast?";
if (m_closure)
m_closure->Run();
return 0;
}
} // ola
<|endoftext|>
|
<commit_before>/*
* (In)Visibible Entities List Adjuster
* Copyright (c) 2014 ThirteenAG <thirteenag@gmail.com>
* Licensed under the MIT License (http://opensource.org/licenses/MIT)
*/
#include "LimitAdjuster.h"
std::vector<char> aInVisibleEntityPtrs;
std::vector<char> aVisibleEntityPtrs;
class InVisibleEntityPtrsIII : public SimpleAdjuster
{
public:
const char* GetLimitName() { return GetGVM().IsIII() ? "InVisibleEntityPtrs" : nullptr; }
void ChangeLimit(int, const std::string& value)
{
aInVisibleEntityPtrs.resize(std::stoi(value));
injector::WriteMemory(0x4A7850 + 0x3, &aInVisibleEntityPtrs[0], true);
injector::WriteMemory(0x4A78D3 + 0x3, &aInVisibleEntityPtrs[0], true);
injector::WriteMemory(0x4A7950 + 0x3, &aInVisibleEntityPtrs[0], true);
injector::WriteMemory(0x4A9300 + 0x33 + 0x3, &aInVisibleEntityPtrs[0], true);
injector::WriteMemory(0x4A9BB0 + 0xB8 + 0x3, &aInVisibleEntityPtrs[0], true);
injector::WriteMemory(0x4A9E30 + 0xC5 + 0x3, &aInVisibleEntityPtrs[0], true);
injector::WriteMemory(0x4AA0A0 + 0x6C + 0x3, &aInVisibleEntityPtrs[0], true);
}
} InVisibleEntityPtrsIII;
class VisibleEntityPtrsIII : public SimpleAdjuster
{
public:
const char* GetLimitName() { return GetGVM().IsIII() ? "VisibleEntityPtrs" : nullptr; }
void ChangeLimit(int, const std::string& value)
{
aVisibleEntityPtrs.resize(std::stoi(value));
injector::WriteMemory(0x4A7870 + 0x3, &aVisibleEntityPtrs[0], true);
injector::WriteMemory(0x4A9BB0 + 0x1C7 + 0x3, &aVisibleEntityPtrs[0], true);
injector::WriteMemory(0x4A9E30 + 0x1D7 + 0x3, &aVisibleEntityPtrs[0], true);
injector::WriteMemory(0x4AA0A0 + 0xE3 + 0x3, &aVisibleEntityPtrs[0], true);
}
} VisibleEntityPtrsIII;
class InVisibleEntityPtrsVC : public SimpleAdjuster
{
public:
const char* GetLimitName() { return GetGVM().IsVC() ? "InVisibleEntityPtrs" : nullptr; }
void ChangeLimit(int, const std::string& value)
{
aInVisibleEntityPtrs.resize(std::stoi(value));
injector::WriteMemory(0x4C7560 + 0xBE + 0x3, &aInVisibleEntityPtrs[0], true);
injector::WriteMemory(0x4C7740 + 0xB8 + 0x3, &aInVisibleEntityPtrs[0], true);
injector::WriteMemory(0x4C8540 + 0x78 + 0x3, &aInVisibleEntityPtrs[0], true);
injector::WriteMemory(0x4C9F80 + 0x3, &aInVisibleEntityPtrs[0], true);
injector::WriteMemory(0x4CA1B8 + 0x3, &aInVisibleEntityPtrs[0], true);
injector::WriteMemory(0x4CA200 + 0x3, &aInVisibleEntityPtrs[0], true);
}
} InVisibleEntityPtrsVC;
class VisibleEntityPtrsVC : public SimpleAdjuster
{
public:
const char* GetLimitName() { return GetGVM().IsVC() ? "VisibleEntityPtrs" : nullptr; }
void ChangeLimit(int, const std::string& value)
{
aVisibleEntityPtrs.resize(std::stoi(value));
injector::WriteMemory(0x4C7560 + 0x185 + 0x3, &aVisibleEntityPtrs[0], true);
injector::WriteMemory(0x4C7740 + 0x17F + 0x3, &aVisibleEntityPtrs[0], true);
injector::WriteMemory(0x4CA220 + 0x3, &aVisibleEntityPtrs[0], true);
}
} VisibleEntityPtrsVC;
class InVisibleEntityPtrsSA : public SimpleAdjuster
{
public:
const char* GetLimitName() { return GetGVM().IsSA() ? "InVisibleEntityPtrs" : nullptr; }
void ChangeLimit(int, const std::string& value)
{
aInVisibleEntityPtrs.resize(std::stoi(value));
injector::WriteMemory(0x5534B0 + 0x42 + 0x3, &aInVisibleEntityPtrs[0], true);
injector::WriteMemory(0x553920 + 0x3, &aInVisibleEntityPtrs[0], true);
injector::WriteMemory(0x553CB0 + 0x3, &aInVisibleEntityPtrs[0], true);
}
// TODO GetUsage
} InVisibleEntityPtrsSA;
class VisibleEntityPtrsSA : public SimpleAdjuster
{
public:
const char* GetLimitName() { return GetGVM().IsSA() ? "VisibleEntityPtrs" : nullptr; }
void ChangeLimit(int, const std::string& value)
{
aVisibleEntityPtrs.resize(std::stoi(value));
injector::WriteMemory(0x5534B0 + 0x76 + 0x3, &aVisibleEntityPtrs[0], true);
injector::WriteMemory(0x553941 + 0x3, &aVisibleEntityPtrs[0], true);
injector::WriteMemory(0x553A50 + 0x3, &aVisibleEntityPtrs[0], true);
injector::WriteMemory(0x553B00 + 0x3, &aVisibleEntityPtrs[0], true);
}
// TODO GetUsage
} VisibleEntityPtrsSA;
<commit_msg>Size fix<commit_after>/*
* (In)Visibible Entities List Adjuster
* Copyright (c) 2014 ThirteenAG <thirteenag@gmail.com>
* Licensed under the MIT License (http://opensource.org/licenses/MIT)
*/
#include "LimitAdjuster.h"
static std::vector<void*> aInVisibleEntityPtrs;
static std::vector<void*> aVisibleEntityPtrs;
class InVisibleEntityPtrsIII : public SimpleAdjuster
{
public:
const char* GetLimitName() { return GetGVM().IsIII() ? "InVisibleEntityPtrs" : nullptr; }
void ChangeLimit(int, const std::string& value)
{
aInVisibleEntityPtrs.resize(std::stoi(value));
injector::WriteMemory(0x4A7850 + 0x3, &aInVisibleEntityPtrs[0], true);
injector::WriteMemory(0x4A78D3 + 0x3, &aInVisibleEntityPtrs[0], true);
injector::WriteMemory(0x4A7950 + 0x3, &aInVisibleEntityPtrs[0], true);
injector::WriteMemory(0x4A9300 + 0x33 + 0x3, &aInVisibleEntityPtrs[0], true);
injector::WriteMemory(0x4A9BB0 + 0xB8 + 0x3, &aInVisibleEntityPtrs[0], true);
injector::WriteMemory(0x4A9E30 + 0xC5 + 0x3, &aInVisibleEntityPtrs[0], true);
injector::WriteMemory(0x4AA0A0 + 0x6C + 0x3, &aInVisibleEntityPtrs[0], true);
}
} InVisibleEntityPtrsIII;
class VisibleEntityPtrsIII : public SimpleAdjuster
{
public:
const char* GetLimitName() { return GetGVM().IsIII() ? "VisibleEntityPtrs" : nullptr; }
void ChangeLimit(int, const std::string& value)
{
aVisibleEntityPtrs.resize(std::stoi(value));
injector::WriteMemory(0x4A7870 + 0x3, &aVisibleEntityPtrs[0], true);
injector::WriteMemory(0x4A9BB0 + 0x1C7 + 0x3, &aVisibleEntityPtrs[0], true);
injector::WriteMemory(0x4A9E30 + 0x1D7 + 0x3, &aVisibleEntityPtrs[0], true);
injector::WriteMemory(0x4AA0A0 + 0xE3 + 0x3, &aVisibleEntityPtrs[0], true);
}
} VisibleEntityPtrsIII;
class InVisibleEntityPtrsVC : public SimpleAdjuster
{
public:
const char* GetLimitName() { return GetGVM().IsVC() ? "InVisibleEntityPtrs" : nullptr; }
void ChangeLimit(int, const std::string& value)
{
aInVisibleEntityPtrs.resize(std::stoi(value));
injector::WriteMemory(0x4C7560 + 0xBE + 0x3, &aInVisibleEntityPtrs[0], true);
injector::WriteMemory(0x4C7740 + 0xB8 + 0x3, &aInVisibleEntityPtrs[0], true);
injector::WriteMemory(0x4C8540 + 0x78 + 0x3, &aInVisibleEntityPtrs[0], true);
injector::WriteMemory(0x4C9F80 + 0x3, &aInVisibleEntityPtrs[0], true);
injector::WriteMemory(0x4CA1B8 + 0x3, &aInVisibleEntityPtrs[0], true);
injector::WriteMemory(0x4CA200 + 0x3, &aInVisibleEntityPtrs[0], true);
}
} InVisibleEntityPtrsVC;
class VisibleEntityPtrsVC : public SimpleAdjuster
{
public:
const char* GetLimitName() { return GetGVM().IsVC() ? "VisibleEntityPtrs" : nullptr; }
void ChangeLimit(int, const std::string& value)
{
aVisibleEntityPtrs.resize(std::stoi(value));
injector::WriteMemory(0x4C7560 + 0x185 + 0x3, &aVisibleEntityPtrs[0], true);
injector::WriteMemory(0x4C7740 + 0x17F + 0x3, &aVisibleEntityPtrs[0], true);
injector::WriteMemory(0x4CA220 + 0x3, &aVisibleEntityPtrs[0], true);
}
} VisibleEntityPtrsVC;
class InVisibleEntityPtrsSA : public SimpleAdjuster
{
public:
const char* GetLimitName() { return GetGVM().IsSA() ? "InVisibleEntityPtrs" : nullptr; }
void ChangeLimit(int, const std::string& value)
{
aInVisibleEntityPtrs.resize(std::stoi(value));
injector::WriteMemory(0x5534B0 + 0x42 + 0x3, &aInVisibleEntityPtrs[0], true);
injector::WriteMemory(0x553920 + 0x3, &aInVisibleEntityPtrs[0], true);
injector::WriteMemory(0x553CB0 + 0x3, &aInVisibleEntityPtrs[0], true);
}
// TODO GetUsage
} InVisibleEntityPtrsSA;
class VisibleEntityPtrsSA : public SimpleAdjuster
{
public:
const char* GetLimitName() { return GetGVM().IsSA() ? "VisibleEntityPtrs" : nullptr; }
void ChangeLimit(int, const std::string& value)
{
aVisibleEntityPtrs.resize(std::stoi(value));
injector::WriteMemory(0x5534B0 + 0x76 + 0x3, &aVisibleEntityPtrs[0], true);
injector::WriteMemory(0x553941 + 0x3, &aVisibleEntityPtrs[0], true);
injector::WriteMemory(0x553A50 + 0x3, &aVisibleEntityPtrs[0], true);
injector::WriteMemory(0x553B00 + 0x3, &aVisibleEntityPtrs[0], true);
}
// TODO GetUsage
} VisibleEntityPtrsSA;
<|endoftext|>
|
<commit_before>#define FASTLED_INTERNAL
#include "FastLED.h"
#if defined(__SAM3X8E__)
volatile uint32_t fuckit;
#endif
FASTLED_NAMESPACE_BEGIN
void *pSmartMatrix = NULL;
CFastLED FastLED;
CLEDController *CLEDController::m_pHead = NULL;
CLEDController *CLEDController::m_pTail = NULL;
static uint32_t lastshow = 0;
uint32_t _frame_cnt=0;
uint32_t _retry_cnt=0;
// uint32_t CRGB::Squant = ((uint32_t)((__TIME__[4]-'0') * 28))<<16 | ((__TIME__[6]-'0')*50)<<8 | ((__TIME__[7]-'0')*28);
CFastLED::CFastLED() {
// clear out the array of led controllers
// m_nControllers = 0;
m_Scale = 255;
m_nFPS = 0;
m_pPowerFunc = NULL;
m_nPowerData = 0xFFFFFFFF;
}
CLEDController &CFastLED::addLeds(CLEDController *pLed,
struct CRGB *data,
int nLedsOrOffset, int nLedsIfOffset) {
int nOffset = (nLedsIfOffset > 0) ? nLedsOrOffset : 0;
int nLeds = (nLedsIfOffset > 0) ? nLedsIfOffset : nLedsOrOffset;
pLed->init();
pLed->setLeds(data + nOffset, nLeds);
FastLED.setMaxRefreshRate(pLed->getMaxRefreshRate(),true);
return *pLed;
}
void CFastLED::show(uint8_t scale) {
// guard against showing too rapidly
while(m_nMinMicros && ((micros()-lastshow) < m_nMinMicros));
lastshow = micros();
// If we have a function for computing power, use it!
if(m_pPowerFunc) {
scale = (*m_pPowerFunc)(scale, m_nPowerData);
}
CLEDController *pCur = CLEDController::head();
while(pCur) {
uint8_t d = pCur->getDither();
if(m_nFPS < 100) { pCur->setDither(0); }
pCur->showLeds(scale);
pCur->setDither(d);
pCur = pCur->next();
}
countFPS();
}
int CFastLED::count() {
int x = 0;
CLEDController *pCur = CLEDController::head();
while( pCur) {
++x;
pCur = pCur->next();
}
return x;
}
CLEDController & CFastLED::operator[](int x) {
CLEDController *pCur = CLEDController::head();
while(x-- && pCur) {
pCur = pCur->next();
}
if(pCur == NULL) {
return *(CLEDController::head());
} else {
return *pCur;
}
}
void CFastLED::showColor(const struct CRGB & color, uint8_t scale) {
while(m_nMinMicros && ((micros()-lastshow) < m_nMinMicros));
lastshow = micros();
// If we have a function for computing power, use it!
if(m_pPowerFunc) {
scale = (*m_pPowerFunc)(scale, m_nPowerData);
}
CLEDController *pCur = CLEDController::head();
while(pCur) {
uint8_t d = pCur->getDither();
if(m_nFPS < 100) { pCur->setDither(0); }
pCur->showColor(color, scale);
pCur->setDither(d);
pCur = pCur->next();
}
countFPS();
}
void CFastLED::clear(bool writeData) {
if(writeData) {
showColor(CRGB(0,0,0), 0);
}
clearData();
}
void CFastLED::clearData() {
CLEDController *pCur = CLEDController::head();
while(pCur) {
pCur->clearLedData();
pCur = pCur->next();
}
}
void CFastLED::delay(unsigned long ms) {
unsigned long start = millis();
do {
#ifndef FASTLED_ACCURATE_CLOCK
// make sure to allow at least one ms to pass to ensure the clock moves
// forward
::delay(1);
#endif
show();
yield();
}
while((millis()-start) < ms);
}
void CFastLED::setTemperature(const struct CRGB & temp) {
CLEDController *pCur = CLEDController::head();
while(pCur) {
pCur->setTemperature(temp);
pCur = pCur->next();
}
}
void CFastLED::setCorrection(const struct CRGB & correction) {
CLEDController *pCur = CLEDController::head();
while(pCur) {
pCur->setCorrection(correction);
pCur = pCur->next();
}
}
void CFastLED::setDither(uint8_t ditherMode) {
CLEDController *pCur = CLEDController::head();
while(pCur) {
pCur->setDither(ditherMode);
pCur = pCur->next();
}
}
//
// template<int m, int n> void transpose8(unsigned char A[8], unsigned char B[8]) {
// uint32_t x, y, t;
//
// // Load the array and pack it into x and y.
// y = *(unsigned int*)(A);
// x = *(unsigned int*)(A+4);
//
// // x = (A[0]<<24) | (A[m]<<16) | (A[2*m]<<8) | A[3*m];
// // y = (A[4*m]<<24) | (A[5*m]<<16) | (A[6*m]<<8) | A[7*m];
//
// // pre-transform x
// t = (x ^ (x >> 7)) & 0x00AA00AA; x = x ^ t ^ (t << 7);
// t = (x ^ (x >>14)) & 0x0000CCCC; x = x ^ t ^ (t <<14);
//
// // pre-transform y
// t = (y ^ (y >> 7)) & 0x00AA00AA; y = y ^ t ^ (t << 7);
// t = (y ^ (y >>14)) & 0x0000CCCC; y = y ^ t ^ (t <<14);
//
// // final transform
// t = (x & 0xF0F0F0F0) | ((y >> 4) & 0x0F0F0F0F);
// y = ((x << 4) & 0xF0F0F0F0) | (y & 0x0F0F0F0F);
// x = t;
//
// B[7*n] = y; y >>= 8;
// B[6*n] = y; y >>= 8;
// B[5*n] = y; y >>= 8;
// B[4*n] = y;
//
// B[3*n] = x; x >>= 8;
// B[2*n] = x; x >>= 8;
// B[n] = x; x >>= 8;
// B[0] = x;
// // B[0]=x>>24; B[n]=x>>16; B[2*n]=x>>8; B[3*n]=x>>0;
// // B[4*n]=y>>24; B[5*n]=y>>16; B[6*n]=y>>8; B[7*n]=y>>0;
// }
//
// void transposeLines(Lines & out, Lines & in) {
// transpose8<1,2>(in.bytes, out.bytes);
// transpose8<1,2>(in.bytes + 8, out.bytes + 1);
// }
extern int noise_min;
extern int noise_max;
void CFastLED::countFPS(int nFrames) {
static int br = 0;
static uint32_t lastframe = 0; // millis();
if(br++ >= nFrames) {
uint32_t now = millis();
now -= lastframe;
if(now == 0) {
now = 1; // prevent division by zero below
}
m_nFPS = (br * 1000) / now;
br = 0;
lastframe = millis();
}
}
void CFastLED::setMaxRefreshRate(uint16_t refresh, bool constrain) {
if(constrain) {
// if we're constraining, the new value of m_nMinMicros _must_ be higher than previously (because we're only
// allowed to slow things down if constraining)
if(refresh > 0) {
m_nMinMicros = ((1000000 / refresh) > m_nMinMicros) ? (1000000 / refresh) : m_nMinMicros;
}
} else if(refresh > 0) {
m_nMinMicros = 1000000 / refresh;
} else {
m_nMinMicros = 0;
}
}
extern "C" int atexit(void (* /*func*/ )()) { return 0; }
#ifdef FASTLED_NEEDS_YIELD
extern "C" void yield(void) { }
#endif
#ifdef NEED_CXX_BITS
namespace __cxxabiv1
{
#if !defined(ESP8266) && !defined(ESP32)
extern "C" void __cxa_pure_virtual (void) {}
#endif
/* guard variables */
/* The ABI requires a 64-bit type. */
__extension__ typedef int __guard __attribute__((mode(__DI__)));
extern "C" int __cxa_guard_acquire (__guard *) __attribute__((weak));
extern "C" void __cxa_guard_release (__guard *) __attribute__((weak));
extern "C" void __cxa_guard_abort (__guard *) __attribute__((weak));
extern "C" int __cxa_guard_acquire (__guard *g)
{
return !*(char *)(g);
}
extern "C" void __cxa_guard_release (__guard *g)
{
*(char *)g = 1;
}
extern "C" void __cxa_guard_abort (__guard *)
{
}
}
#endif
FASTLED_NAMESPACE_END
<commit_msg>Update FastLED.cpp documentation<commit_after>#define FASTLED_INTERNAL
#include "FastLED.h"
/// @file FastLED.cpp
/// Central source file for FastLED, implements the CFastLED class/object
#if defined(__SAM3X8E__)
volatile uint32_t fuckit;
#endif
FASTLED_NAMESPACE_BEGIN
/// Pointer to the matrix object when using the Smart Matrix Library
/// @see https://github.com/pixelmatix/SmartMatrix
void *pSmartMatrix = NULL;
CFastLED FastLED;
CLEDController *CLEDController::m_pHead = NULL;
CLEDController *CLEDController::m_pTail = NULL;
static uint32_t lastshow = 0;
/// Global frame counter, used for debugging ESP implementations
/// @todo Include in FASTLED_DEBUG_COUNT_FRAME_RETRIES block?
uint32_t _frame_cnt=0;
/// Global frame retry counter, used for debugging ESP implementations
/// @todo Include in FASTLED_DEBUG_COUNT_FRAME_RETRIES block?
uint32_t _retry_cnt=0;
// uint32_t CRGB::Squant = ((uint32_t)((__TIME__[4]-'0') * 28))<<16 | ((__TIME__[6]-'0')*50)<<8 | ((__TIME__[7]-'0')*28);
CFastLED::CFastLED() {
// clear out the array of led controllers
// m_nControllers = 0;
m_Scale = 255;
m_nFPS = 0;
m_pPowerFunc = NULL;
m_nPowerData = 0xFFFFFFFF;
}
CLEDController &CFastLED::addLeds(CLEDController *pLed,
struct CRGB *data,
int nLedsOrOffset, int nLedsIfOffset) {
int nOffset = (nLedsIfOffset > 0) ? nLedsOrOffset : 0;
int nLeds = (nLedsIfOffset > 0) ? nLedsIfOffset : nLedsOrOffset;
pLed->init();
pLed->setLeds(data + nOffset, nLeds);
FastLED.setMaxRefreshRate(pLed->getMaxRefreshRate(),true);
return *pLed;
}
void CFastLED::show(uint8_t scale) {
// guard against showing too rapidly
while(m_nMinMicros && ((micros()-lastshow) < m_nMinMicros));
lastshow = micros();
// If we have a function for computing power, use it!
if(m_pPowerFunc) {
scale = (*m_pPowerFunc)(scale, m_nPowerData);
}
CLEDController *pCur = CLEDController::head();
while(pCur) {
uint8_t d = pCur->getDither();
if(m_nFPS < 100) { pCur->setDither(0); }
pCur->showLeds(scale);
pCur->setDither(d);
pCur = pCur->next();
}
countFPS();
}
int CFastLED::count() {
int x = 0;
CLEDController *pCur = CLEDController::head();
while( pCur) {
++x;
pCur = pCur->next();
}
return x;
}
CLEDController & CFastLED::operator[](int x) {
CLEDController *pCur = CLEDController::head();
while(x-- && pCur) {
pCur = pCur->next();
}
if(pCur == NULL) {
return *(CLEDController::head());
} else {
return *pCur;
}
}
void CFastLED::showColor(const struct CRGB & color, uint8_t scale) {
while(m_nMinMicros && ((micros()-lastshow) < m_nMinMicros));
lastshow = micros();
// If we have a function for computing power, use it!
if(m_pPowerFunc) {
scale = (*m_pPowerFunc)(scale, m_nPowerData);
}
CLEDController *pCur = CLEDController::head();
while(pCur) {
uint8_t d = pCur->getDither();
if(m_nFPS < 100) { pCur->setDither(0); }
pCur->showColor(color, scale);
pCur->setDither(d);
pCur = pCur->next();
}
countFPS();
}
void CFastLED::clear(bool writeData) {
if(writeData) {
showColor(CRGB(0,0,0), 0);
}
clearData();
}
void CFastLED::clearData() {
CLEDController *pCur = CLEDController::head();
while(pCur) {
pCur->clearLedData();
pCur = pCur->next();
}
}
void CFastLED::delay(unsigned long ms) {
unsigned long start = millis();
do {
#ifndef FASTLED_ACCURATE_CLOCK
// make sure to allow at least one ms to pass to ensure the clock moves
// forward
::delay(1);
#endif
show();
yield();
}
while((millis()-start) < ms);
}
void CFastLED::setTemperature(const struct CRGB & temp) {
CLEDController *pCur = CLEDController::head();
while(pCur) {
pCur->setTemperature(temp);
pCur = pCur->next();
}
}
void CFastLED::setCorrection(const struct CRGB & correction) {
CLEDController *pCur = CLEDController::head();
while(pCur) {
pCur->setCorrection(correction);
pCur = pCur->next();
}
}
void CFastLED::setDither(uint8_t ditherMode) {
CLEDController *pCur = CLEDController::head();
while(pCur) {
pCur->setDither(ditherMode);
pCur = pCur->next();
}
}
//
// template<int m, int n> void transpose8(unsigned char A[8], unsigned char B[8]) {
// uint32_t x, y, t;
//
// // Load the array and pack it into x and y.
// y = *(unsigned int*)(A);
// x = *(unsigned int*)(A+4);
//
// // x = (A[0]<<24) | (A[m]<<16) | (A[2*m]<<8) | A[3*m];
// // y = (A[4*m]<<24) | (A[5*m]<<16) | (A[6*m]<<8) | A[7*m];
//
// // pre-transform x
// t = (x ^ (x >> 7)) & 0x00AA00AA; x = x ^ t ^ (t << 7);
// t = (x ^ (x >>14)) & 0x0000CCCC; x = x ^ t ^ (t <<14);
//
// // pre-transform y
// t = (y ^ (y >> 7)) & 0x00AA00AA; y = y ^ t ^ (t << 7);
// t = (y ^ (y >>14)) & 0x0000CCCC; y = y ^ t ^ (t <<14);
//
// // final transform
// t = (x & 0xF0F0F0F0) | ((y >> 4) & 0x0F0F0F0F);
// y = ((x << 4) & 0xF0F0F0F0) | (y & 0x0F0F0F0F);
// x = t;
//
// B[7*n] = y; y >>= 8;
// B[6*n] = y; y >>= 8;
// B[5*n] = y; y >>= 8;
// B[4*n] = y;
//
// B[3*n] = x; x >>= 8;
// B[2*n] = x; x >>= 8;
// B[n] = x; x >>= 8;
// B[0] = x;
// // B[0]=x>>24; B[n]=x>>16; B[2*n]=x>>8; B[3*n]=x>>0;
// // B[4*n]=y>>24; B[5*n]=y>>16; B[6*n]=y>>8; B[7*n]=y>>0;
// }
//
// void transposeLines(Lines & out, Lines & in) {
// transpose8<1,2>(in.bytes, out.bytes);
// transpose8<1,2>(in.bytes + 8, out.bytes + 1);
// }
/// Unused value
/// @todo Remove?
extern int noise_min;
/// Unused value
/// @todo Remove?
extern int noise_max;
void CFastLED::countFPS(int nFrames) {
static int br = 0;
static uint32_t lastframe = 0; // millis();
if(br++ >= nFrames) {
uint32_t now = millis();
now -= lastframe;
if(now == 0) {
now = 1; // prevent division by zero below
}
m_nFPS = (br * 1000) / now;
br = 0;
lastframe = millis();
}
}
void CFastLED::setMaxRefreshRate(uint16_t refresh, bool constrain) {
if(constrain) {
// if we're constraining, the new value of m_nMinMicros _must_ be higher than previously (because we're only
// allowed to slow things down if constraining)
if(refresh > 0) {
m_nMinMicros = ((1000000 / refresh) > m_nMinMicros) ? (1000000 / refresh) : m_nMinMicros;
}
} else if(refresh > 0) {
m_nMinMicros = 1000000 / refresh;
} else {
m_nMinMicros = 0;
}
}
/// Called at program exit when run in a desktop environment.
/// Extra C definition that some environments may need.
/// @returns 0 to indicate success
extern "C" int atexit(void (* /*func*/ )()) { return 0; }
#ifdef FASTLED_NEEDS_YIELD
extern "C" void yield(void) { }
#endif
#ifdef NEED_CXX_BITS
namespace __cxxabiv1
{
#if !defined(ESP8266) && !defined(ESP32)
extern "C" void __cxa_pure_virtual (void) {}
#endif
/* guard variables */
/* The ABI requires a 64-bit type. */
__extension__ typedef int __guard __attribute__((mode(__DI__)));
extern "C" int __cxa_guard_acquire (__guard *) __attribute__((weak));
extern "C" void __cxa_guard_release (__guard *) __attribute__((weak));
extern "C" void __cxa_guard_abort (__guard *) __attribute__((weak));
extern "C" int __cxa_guard_acquire (__guard *g)
{
return !*(char *)(g);
}
extern "C" void __cxa_guard_release (__guard *g)
{
*(char *)g = 1;
}
extern "C" void __cxa_guard_abort (__guard *)
{
}
}
#endif
FASTLED_NAMESPACE_END
<|endoftext|>
|
<commit_before>#include <opencv2/highgui/highgui.hpp>
#include <opencv2/opencv.hpp>
#include <iostream>
#include <string>
using namespace std;
int main()
{
while(cin)
{
string path;
getline(cin, path);
cv::Mat input = cv::imread(path+".jpg");
cv::Mat hsv_filtered15;//画像の初期化
cv::Mat hsv_filtered180;//画像の初期化
cv::Mat hsv;
cv::Mat output;
cv::cvtColor(input,hsv,CV_BGR2HSV);//入力画像(src)をhsv色空間(dst)に変換
//inRange(入力画像,下界画像,上界画像,出力画像)
//「HSV」は、色を色相(Hue)・彩度(Saturation)・明度(Value)
cv::inRange(hsv,cv::Scalar(0,120,97),cv::Scalar(13,255,255),hsv_filtered15);
cv::inRange(hsv,cv::Scalar(175,120,97),cv::Scalar(180,255,255),hsv_filtered180);
cv::add(hsv_filtered15,hsv_filtered180,output);
cv::imwrite(path+"BINARY"+".jpg",output);
}
return 0;
}
<commit_msg>debug<commit_after>#include <opencv2/highgui/highgui.hpp>
#include <opencv2/opencv.hpp>
#include <iostream>
#include <string>
using namespace std;
int main()
{
while(1)
{
string path;
getline(cin, path);
cv::Mat input = cv::imread(path+".jpg");
cv::Mat hsv_filtered15;//画像の初期化
cv::Mat hsv_filtered180;//画像の初期化
cv::Mat hsv;
cv::Mat output;
cv::cvtColor(input,hsv,CV_BGR2HSV);//入力画像(src)をhsv色空間(dst)に変換
//inRange(入力画像,下界画像,上界画像,出力画像)
//「HSV」は、色を色相(Hue)・彩度(Saturation)・明度(Value)
cv::inRange(hsv,cv::Scalar(0,120,97),cv::Scalar(13,255,255),hsv_filtered15);
cv::inRange(hsv,cv::Scalar(175,120,97),cv::Scalar(180,255,255),hsv_filtered180);
cv::add(hsv_filtered15,hsv_filtered180,output);
cv::imwrite(path+"BINARY"+".jpg",output);
}
return 0;
}
<|endoftext|>
|
<commit_before><?hh //strict
namespace hhpack\migrate;
use hhpack\publisher\Message;
final class MigrationLoadedEvent implements Message
{
public function __construct(
private ImmVector<Migration> $migrations
)
{
}
public function queries(): ImmVector<string>
{
return $this->migrations->map(($migration) ==> $migration->query());
}
}
<commit_msg>add migrationCount method<commit_after><?hh //strict
namespace hhpack\migrate;
use hhpack\publisher\Message;
final class MigrationLoadedEvent implements Message
{
public function __construct(
private ImmVector<Migration> $migrations
)
{
}
public function queries(): ImmVector<string>
{
return $this->migrations->map(($migration) ==> $migration->query());
}
public function migrationCount(): ImmVector<string>
{
return $this->migrations->count();
}
}
<|endoftext|>
|
<commit_before>/*
Copyright 2012 <copyright holder> <email>
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 "asset.hpp"
#include <boost/foreach.hpp>
#include <boost/smart_ptr/make_shared.hpp>
#include <utility>
#include <lib/weak_fn.hpp>
#include <log4cplus/logger.h>
#include <log4cplus/loggingmacros.h>
using namespace bithorded::router;
using namespace std;
namespace bithorded { namespace router {
log4cplus::Logger assetLogger = log4cplus::Logger::getInstance("router");
} }
UpstreamAsset::UpstreamAsset(const bithorde::ReadAsset::ClientPointer& client, const BitHordeIds& requestIds)
: ReadAsset(client, requestIds)
{}
void UpstreamAsset::handleMessage(const bithorde::Read::Response& resp)
{
auto self_ref = shared_from_this();
bithorde::ReadAsset::handleMessage(resp);
}
bool bithorded::router::ForwardedAsset::hasUpstream(const std::string peername)
{
return _upstream.count(peername);
}
void bithorded::router::ForwardedAsset::bindUpstreams(const std::map< string, bithorded::Client::Ptr >& friends, uint64_t uuid, int timeout)
{
BOOST_FOREACH(auto f_, friends) {
auto f = f_.second;
if (f->requestsAsset(_ids)) // This path surely doesn't have the asset.
continue;
auto peername = f->peerName();
auto& upstream = _upstream[peername] = make_shared<UpstreamAsset>(f, _ids);
auto self = boost::weak_ptr<ForwardedAsset>(shared_from_this());
upstream->statusUpdate.connect(boost::bind(boost::weak_fn(&ForwardedAsset::onUpstreamStatus, self), peername, bithorde::ASSET_ARG_STATUS));
upstream->dataArrived.connect(boost::bind(boost::weak_fn(&ForwardedAsset::onData, self),
bithorde::ASSET_ARG_OFFSET, bithorde::ASSET_ARG_DATA, bithorde::ASSET_ARG_TAG));
if (!f->bind(*upstream, timeout, uuid))
dropUpstream(peername);
}
updateStatus();
}
void bithorded::router::ForwardedAsset::onUpstreamStatus(const string& peername, const bithorde::AssetStatus& status)
{
if (status.status() == bithorde::Status::SUCCESS) {
LOG4CPLUS_DEBUG(assetLogger, _ids << " Found upstream " << peername);
if (status.has_size()) {
if (_size == -1) {
_size = status.size();
} else if (_size != (int64_t)status.size()) {
LOG4CPLUS_WARN(assetLogger, peername << " " << _ids << " responded with mismatching size, ignoring...");
dropUpstream(peername);
}
} else {
LOG4CPLUS_WARN(assetLogger, peername << " " << _ids << " SUCCESS response not accompanied with asset-size.");
}
} else {
LOG4CPLUS_DEBUG(assetLogger, _ids << "Failed upstream " << peername);
dropUpstream(peername);
}
updateStatus();
}
void bithorded::router::ForwardedAsset::updateStatus() {
bithorde::Status status = _upstream.empty() ? bithorde::Status::NOTFOUND : bithorde::Status::NONE;
for (auto iter=_upstream.begin(); iter!=_upstream.end(); iter++) {
auto& asset = iter->second;
if (asset->status == bithorde::Status::SUCCESS)
status = bithorde::Status::SUCCESS;
}
setStatus(status);
}
size_t bithorded::router::ForwardedAsset::can_read(uint64_t offset, size_t size)
{
return size;
}
bool bithorded::router::ForwardedAsset::getIds(BitHordeIds& ids) const
{
ids = _ids;
return true;
}
void bithorded::router::ForwardedAsset::async_read(uint64_t offset, size_t& size, uint32_t timeout, ReadCallback cb)
{
if (_upstream.empty())
return cb(-1, string());
auto chosen = _upstream.begin();
uint32_t current_best = 1000*60*60*24;
for (auto iter = _upstream.begin(); iter != _upstream.end(); iter++) {
auto& a = iter->second;
if (current_best > a->readResponseTime.value()) {
current_best = a->readResponseTime.value();
chosen = iter;
}
}
PendingRead read;
read.offset = offset;
read.size = size;
read.cb = cb;
_pendingReads.push_back(read);
chosen->second->aSyncRead(offset, size, timeout);
}
void bithorded::router::ForwardedAsset::onData(uint64_t offset, const std::string& data, int tag) {
for (auto iter=_pendingReads.begin(); iter != _pendingReads.end(); ) {
if (iter->offset == offset) {
iter->cb(offset, data);
iter = _pendingReads.erase(iter); // Will increase the iterator
} else {
iter++; // Move to next
}
}
}
uint64_t bithorded::router::ForwardedAsset::size()
{
return _size;
}
void ForwardedAsset::inspect(bithorded::management::InfoList& target) const
{
target.append("type") << "forwarded";
}
void ForwardedAsset::inspect_upstreams(bithorded::management::InfoList& target) const
{
for (auto iter = _upstream.begin(); iter != _upstream.end(); iter++) {
ostringstream buf;
buf << "upstream_" << iter->first;
target.append(buf.str()) << bithorde::Status_Name(iter->second->status) << ", responseTime: " << iter->second->readResponseTime;
}
}
void ForwardedAsset::dropUpstream(const string& peername)
{
auto upstream = _upstream.find(peername);
if (upstream != _upstream.end()) {
upstream->second->statusUpdate.disconnect(boost::bind(&ForwardedAsset::onUpstreamStatus, this, peername, bithorde::ASSET_ARG_STATUS));
upstream->second->dataArrived.disconnect(boost::bind(&ForwardedAsset::onData, this,
bithorde::ASSET_ARG_OFFSET, bithorde::ASSET_ARG_DATA, bithorde::ASSET_ARG_TAG));
_upstream.erase(upstream);
}
}
<commit_msg>[bithorded/router/asset]Ignore assets without successful binding. Kudos to Adam for reporting and identifying the problem.<commit_after>/*
Copyright 2012 <copyright holder> <email>
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 "asset.hpp"
#include <boost/foreach.hpp>
#include <boost/smart_ptr/make_shared.hpp>
#include <utility>
#include <lib/weak_fn.hpp>
#include <log4cplus/logger.h>
#include <log4cplus/loggingmacros.h>
using namespace bithorded::router;
using namespace std;
namespace bithorded { namespace router {
log4cplus::Logger assetLogger = log4cplus::Logger::getInstance("router");
} }
UpstreamAsset::UpstreamAsset(const bithorde::ReadAsset::ClientPointer& client, const BitHordeIds& requestIds)
: ReadAsset(client, requestIds)
{}
void UpstreamAsset::handleMessage(const bithorde::Read::Response& resp)
{
auto self_ref = shared_from_this();
bithorde::ReadAsset::handleMessage(resp);
}
bool bithorded::router::ForwardedAsset::hasUpstream(const std::string peername)
{
return _upstream.count(peername);
}
void bithorded::router::ForwardedAsset::bindUpstreams(const std::map< string, bithorded::Client::Ptr >& friends, uint64_t uuid, int timeout)
{
BOOST_FOREACH(auto f_, friends) {
auto f = f_.second;
if (f->requestsAsset(_ids)) // This path surely doesn't have the asset.
continue;
auto peername = f->peerName();
auto& upstream = _upstream[peername] = make_shared<UpstreamAsset>(f, _ids);
auto self = boost::weak_ptr<ForwardedAsset>(shared_from_this());
upstream->statusUpdate.connect(boost::bind(boost::weak_fn(&ForwardedAsset::onUpstreamStatus, self), peername, bithorde::ASSET_ARG_STATUS));
upstream->dataArrived.connect(boost::bind(boost::weak_fn(&ForwardedAsset::onData, self),
bithorde::ASSET_ARG_OFFSET, bithorde::ASSET_ARG_DATA, bithorde::ASSET_ARG_TAG));
if (!f->bind(*upstream, timeout, uuid))
dropUpstream(peername);
}
updateStatus();
}
void bithorded::router::ForwardedAsset::onUpstreamStatus(const string& peername, const bithorde::AssetStatus& status)
{
if (status.status() == bithorde::Status::SUCCESS) {
LOG4CPLUS_DEBUG(assetLogger, _ids << " Found upstream " << peername);
if (status.has_size()) {
if (_size == -1) {
_size = status.size();
} else if (_size != (int64_t)status.size()) {
LOG4CPLUS_WARN(assetLogger, peername << " " << _ids << " responded with mismatching size, ignoring...");
dropUpstream(peername);
}
} else {
LOG4CPLUS_WARN(assetLogger, peername << " " << _ids << " SUCCESS response not accompanied with asset-size.");
}
} else {
LOG4CPLUS_DEBUG(assetLogger, _ids << "Failed upstream " << peername);
dropUpstream(peername);
}
updateStatus();
}
void bithorded::router::ForwardedAsset::updateStatus() {
bithorde::Status status = _upstream.empty() ? bithorde::Status::NOTFOUND : bithorde::Status::NONE;
for (auto iter=_upstream.begin(); iter!=_upstream.end(); iter++) {
auto& asset = iter->second;
if (asset->status == bithorde::Status::SUCCESS)
status = bithorde::Status::SUCCESS;
}
setStatus(status);
}
size_t bithorded::router::ForwardedAsset::can_read(uint64_t offset, size_t size)
{
return size;
}
bool bithorded::router::ForwardedAsset::getIds(BitHordeIds& ids) const
{
ids = _ids;
return true;
}
void bithorded::router::ForwardedAsset::async_read(uint64_t offset, size_t& size, uint32_t timeout, ReadCallback cb)
{
if (_upstream.empty())
return cb(-1, string());
auto chosen = _upstream.begin();
uint32_t current_best = 1000*60*60*24;
for (auto iter = _upstream.begin(); iter != _upstream.end(); iter++) {
auto& a = iter->second;
if (a->status != bithorde::SUCCESS)
continue;
if (current_best > a->readResponseTime.value()) {
current_best = a->readResponseTime.value();
chosen = iter;
}
}
PendingRead read;
read.offset = offset;
read.size = size;
read.cb = cb;
_pendingReads.push_back(read);
chosen->second->aSyncRead(offset, size, timeout);
}
void bithorded::router::ForwardedAsset::onData(uint64_t offset, const std::string& data, int tag) {
for (auto iter=_pendingReads.begin(); iter != _pendingReads.end(); ) {
if (iter->offset == offset) {
iter->cb(offset, data);
iter = _pendingReads.erase(iter); // Will increase the iterator
} else {
iter++; // Move to next
}
}
}
uint64_t bithorded::router::ForwardedAsset::size()
{
return _size;
}
void ForwardedAsset::inspect(bithorded::management::InfoList& target) const
{
target.append("type") << "forwarded";
}
void ForwardedAsset::inspect_upstreams(bithorded::management::InfoList& target) const
{
for (auto iter = _upstream.begin(); iter != _upstream.end(); iter++) {
ostringstream buf;
buf << "upstream_" << iter->first;
target.append(buf.str()) << bithorde::Status_Name(iter->second->status) << ", responseTime: " << iter->second->readResponseTime;
}
}
void ForwardedAsset::dropUpstream(const string& peername)
{
auto upstream = _upstream.find(peername);
if (upstream != _upstream.end()) {
upstream->second->statusUpdate.disconnect(boost::bind(&ForwardedAsset::onUpstreamStatus, this, peername, bithorde::ASSET_ARG_STATUS));
upstream->second->dataArrived.disconnect(boost::bind(&ForwardedAsset::onData, this,
bithorde::ASSET_ARG_OFFSET, bithorde::ASSET_ARG_DATA, bithorde::ASSET_ARG_TAG));
_upstream.erase(upstream);
}
}
<|endoftext|>
|
<commit_before>#ifndef __RMOL_RMOL_TYPES_HPP
#define __RMOL_RMOL_TYPES_HPP
// //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// STL
#include <vector>
#include <list>
// Boost
#include <boost/shared_ptr.hpp>
namespace RMOL {
// Forward declarations
class RMOL_Service;
// ///////// Exceptions ///////////
class RootException : public std::exception {
};
class FileNotFoundException : public RootException {
};
class NonInitialisedServiceException : public RootException {
};
class MemoryAllocationException : public RootException {
};
class ObjectNotFoundException : public RootException {
};
class DocumentNotFoundException : public RootException {
};
// /////////////// Log /////////////
/** Level of logs. */
namespace LOG {
typedef enum {
CRITICAL = 0,
ERROR,
NOTIFICATION,
WARNING,
DEBUG,
VERBOSE,
LAST_VALUE
} EN_LogLevel;
}
// //////// Type definitions /////////
/** Pointer on the RMOL Service handler. */
typedef boost::shared_ptr<RMOL_Service> RMOL_ServicePtr_T;
}
#endif // __RMOL_RMOL_TYPES_HPP
<commit_msg>[RMOL][Dev] Fixed a merge issue in RMOL_Types.<commit_after>#ifndef __RMOL_RMOL_TYPES_HPP
#define __RMOL_RMOL_TYPES_HPP
// //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// Boost
#include <boost/shared_ptr.hpp>
// StdAir
#include <stdair/stdair_exceptions.hpp>
namespace RMOL {
// Forward declarations
class RMOL_Service;
// ///////// Exceptions ///////////
/**
* @brief Overbooking-related exception.
*/
class OverbookingException : public stdair::RootException {
public:
/** Constructor. */
OverbookingException (const std::string& iWhat)
: stdair::RootException (iWhat) {}
};
/**
* @brief Unconstraining-related exception.
*/
class UnconstrainingException : public stdair::RootException {
public:
/** Constructor. */
UnconstrainingException (const std::string& iWhat)
: stdair::RootException (iWhat) {}
};
/**
* @brief Forecast-related exception.
*/
class ForecastException : public stdair::RootException {
public:
/** Constructor. */
ForecastException (const std::string& iWhat)
: stdair::RootException (iWhat) {}
};
/**
* @brief Optimisation-related exception.
*/
class OptimisationException : public stdair::RootException {
public:
/** Constructor. */
OptimisationException (const std::string& iWhat)
: stdair::RootException (iWhat) {}
};
// //////// Type definitions /////////
/**
* Pointer on the RMOL Service handler.
*/
typedef boost::shared_ptr<RMOL_Service> RMOL_ServicePtr_T;
}
#endif // __RMOL_RMOL_TYPES_HPP
<|endoftext|>
|
<commit_before>#include <stdio.h>
#include <stdint.h>
#include <time.h>
#include <v8.h>
#include <node.h>
#include "nan.h"
using namespace node;
using namespace v8;
class Time {
public:
static void Init(Handle<Object> target) {
NanScope();
// time(3)
NODE_SET_METHOD(target, "time", Time_);
// tzset(3)
NODE_SET_METHOD(target, "tzset", Tzset);
// localtime
NODE_SET_METHOD(target, "localtime", Localtime);
// mktime
NODE_SET_METHOD(target, "mktime", Mktime);
}
static NAN_METHOD(Time_) {
NanReturnValue(Integer::New(time(NULL)));
}
static NAN_METHOD(Tzset) {
NanScope();
// Set up the timezone info from the current TZ environ variable
tzset();
// Set up a return object that will hold the results of the timezone change
Local<Object> obj = Object::New();
// The 'tzname' char * [] gets put into a JS Array
int tznameLength = 2;
Local<Array> tznameArray = Array::New( tznameLength );
for (int i=0; i < tznameLength; i++) {
tznameArray->Set(Number::New(i), String::NewSymbol( tzname[i] ));
}
obj->Set(String::NewSymbol("tzname"), tznameArray);
// The 'timezone' long is the "seconds West of UTC"
obj->Set(String::NewSymbol("timezone"), Number::New( timezone ));
// The 'daylight' int is obselete actually, but I'll include it here for
// curiosity's sake. See the "Notes" section of "man tzset"
obj->Set(String::NewSymbol("daylight"), Number::New( daylight ));
NanReturnValue(obj);
}
static NAN_METHOD(Localtime) {
NanScope();
// Construct the 'tm' struct
time_t rawtime = static_cast<time_t>(args[0]->IntegerValue());
struct tm *timeinfo = localtime( &rawtime );
// Create the return "Object"
Local<Object> obj = Object::New();
if (timeinfo) {
obj->Set(String::NewSymbol("seconds"), Integer::New(timeinfo->tm_sec) );
obj->Set(String::NewSymbol("minutes"), Integer::New(timeinfo->tm_min) );
obj->Set(String::NewSymbol("hours"), Integer::New(timeinfo->tm_hour) );
obj->Set(String::NewSymbol("dayOfMonth"), Integer::New(timeinfo->tm_mday) );
obj->Set(String::NewSymbol("month"), Integer::New(timeinfo->tm_mon) );
obj->Set(String::NewSymbol("year"), Integer::New(timeinfo->tm_year) );
obj->Set(String::NewSymbol("dayOfWeek"), Integer::New(timeinfo->tm_wday) );
obj->Set(String::NewSymbol("dayOfYear"), Integer::New(timeinfo->tm_yday) );
obj->Set(String::NewSymbol("isDaylightSavings"), Boolean::New(timeinfo->tm_isdst > 0) );
#if defined HAVE_TM_GMTOFF
// Only available with glibc's "tm" struct. Most Linuxes, Mac OS X...
obj->Set(String::NewSymbol("gmtOffset"), Integer::New(timeinfo->tm_gmtoff) );
obj->Set(String::NewSymbol("timezone"), String::NewSymbol(timeinfo->tm_zone) );
#elif defined HAVE_TIMEZONE
// Compatibility for Cygwin, Solaris, probably others...
long scd;
if (timeinfo->tm_isdst > 0) {
#ifdef HAVE_ALTZONE
scd = -altzone;
#else
scd = -timezone + 3600;
#endif // HAVE_ALTZONE
} else {
scd = -timezone;
}
obj->Set(String::NewSymbol("gmtOffset"), Integer::New(scd));
obj->Set(String::NewSymbol("timezone"), String::NewSymbol(tzname[timeinfo->tm_isdst]));
#endif // HAVE_TM_GMTOFF
} else {
obj->Set(String::NewSymbol("invalid"), True());
}
NanReturnValue(obj);
}
static NAN_METHOD(Mktime) {
NanScope();
if (args.Length() < 1) {
return NanThrowTypeError("localtime() Object expected");
}
Local<Object> arg = args[0]->ToObject();
struct tm tmstr;
tmstr.tm_sec = arg->Get(String::NewSymbol("seconds"))->Int32Value();
tmstr.tm_min = arg->Get(String::NewSymbol("minutes"))->Int32Value();
tmstr.tm_hour = arg->Get(String::NewSymbol("hours"))->Int32Value();
tmstr.tm_mday = arg->Get(String::NewSymbol("dayOfMonth"))->Int32Value();
tmstr.tm_mon = arg->Get(String::NewSymbol("month"))->Int32Value();
tmstr.tm_year = arg->Get(String::NewSymbol("year"))->Int32Value();
tmstr.tm_isdst = arg->Get(String::NewSymbol("isDaylightSavings"))->Int32Value();
// tm_wday and tm_yday are ignored for input, but properly set after 'mktime' is called
NanReturnValue(Number::New(static_cast<double>(mktime( &tmstr ))));
}
};
extern "C" {
static void init (Handle<Object> target) {
Time::Init(target);
}
NODE_MODULE(time, init)
}
<commit_msg>Fix of missing scope.<commit_after>#include <stdio.h>
#include <stdint.h>
#include <time.h>
#include <v8.h>
#include <node.h>
#include "nan.h"
using namespace node;
using namespace v8;
class Time {
public:
static void Init(Handle<Object> target) {
NanScope();
// time(3)
NODE_SET_METHOD(target, "time", Time_);
// tzset(3)
NODE_SET_METHOD(target, "tzset", Tzset);
// localtime
NODE_SET_METHOD(target, "localtime", Localtime);
// mktime
NODE_SET_METHOD(target, "mktime", Mktime);
}
static NAN_METHOD(Time_) {
NanScope();
NanReturnValue(Integer::New(time(NULL)));
}
static NAN_METHOD(Tzset) {
NanScope();
// Set up the timezone info from the current TZ environ variable
tzset();
// Set up a return object that will hold the results of the timezone change
Local<Object> obj = Object::New();
// The 'tzname' char * [] gets put into a JS Array
int tznameLength = 2;
Local<Array> tznameArray = Array::New( tznameLength );
for (int i=0; i < tznameLength; i++) {
tznameArray->Set(Number::New(i), String::NewSymbol( tzname[i] ));
}
obj->Set(String::NewSymbol("tzname"), tznameArray);
// The 'timezone' long is the "seconds West of UTC"
obj->Set(String::NewSymbol("timezone"), Number::New( timezone ));
// The 'daylight' int is obselete actually, but I'll include it here for
// curiosity's sake. See the "Notes" section of "man tzset"
obj->Set(String::NewSymbol("daylight"), Number::New( daylight ));
NanReturnValue(obj);
}
static NAN_METHOD(Localtime) {
NanScope();
// Construct the 'tm' struct
time_t rawtime = static_cast<time_t>(args[0]->IntegerValue());
struct tm *timeinfo = localtime( &rawtime );
// Create the return "Object"
Local<Object> obj = Object::New();
if (timeinfo) {
obj->Set(String::NewSymbol("seconds"), Integer::New(timeinfo->tm_sec) );
obj->Set(String::NewSymbol("minutes"), Integer::New(timeinfo->tm_min) );
obj->Set(String::NewSymbol("hours"), Integer::New(timeinfo->tm_hour) );
obj->Set(String::NewSymbol("dayOfMonth"), Integer::New(timeinfo->tm_mday) );
obj->Set(String::NewSymbol("month"), Integer::New(timeinfo->tm_mon) );
obj->Set(String::NewSymbol("year"), Integer::New(timeinfo->tm_year) );
obj->Set(String::NewSymbol("dayOfWeek"), Integer::New(timeinfo->tm_wday) );
obj->Set(String::NewSymbol("dayOfYear"), Integer::New(timeinfo->tm_yday) );
obj->Set(String::NewSymbol("isDaylightSavings"), Boolean::New(timeinfo->tm_isdst > 0) );
#if defined HAVE_TM_GMTOFF
// Only available with glibc's "tm" struct. Most Linuxes, Mac OS X...
obj->Set(String::NewSymbol("gmtOffset"), Integer::New(timeinfo->tm_gmtoff) );
obj->Set(String::NewSymbol("timezone"), String::NewSymbol(timeinfo->tm_zone) );
#elif defined HAVE_TIMEZONE
// Compatibility for Cygwin, Solaris, probably others...
long scd;
if (timeinfo->tm_isdst > 0) {
#ifdef HAVE_ALTZONE
scd = -altzone;
#else
scd = -timezone + 3600;
#endif // HAVE_ALTZONE
} else {
scd = -timezone;
}
obj->Set(String::NewSymbol("gmtOffset"), Integer::New(scd));
obj->Set(String::NewSymbol("timezone"), String::NewSymbol(tzname[timeinfo->tm_isdst]));
#endif // HAVE_TM_GMTOFF
} else {
obj->Set(String::NewSymbol("invalid"), True());
}
NanReturnValue(obj);
}
static NAN_METHOD(Mktime) {
NanScope();
if (args.Length() < 1) {
return NanThrowTypeError("localtime() Object expected");
}
Local<Object> arg = args[0]->ToObject();
struct tm tmstr;
tmstr.tm_sec = arg->Get(String::NewSymbol("seconds"))->Int32Value();
tmstr.tm_min = arg->Get(String::NewSymbol("minutes"))->Int32Value();
tmstr.tm_hour = arg->Get(String::NewSymbol("hours"))->Int32Value();
tmstr.tm_mday = arg->Get(String::NewSymbol("dayOfMonth"))->Int32Value();
tmstr.tm_mon = arg->Get(String::NewSymbol("month"))->Int32Value();
tmstr.tm_year = arg->Get(String::NewSymbol("year"))->Int32Value();
tmstr.tm_isdst = arg->Get(String::NewSymbol("isDaylightSavings"))->Int32Value();
// tm_wday and tm_yday are ignored for input, but properly set after 'mktime' is called
NanReturnValue(Number::New(static_cast<double>(mktime( &tmstr ))));
}
};
extern "C" {
static void init (Handle<Object> target) {
Time::Init(target);
}
NODE_MODULE(time, init)
}
<|endoftext|>
|
<commit_before>/*
** Copyright (C) - Triton
**
** This program is under the terms of the LGPLv3 License.
*/
#include <SymbolicEngine.h>
#include <Registers.h>
SymbolicEngine::SymbolicEngine() {
/* Init all symbolic registers/flags to UNSET (init state) */
for (uint64 i = 0; i < ID_LAST_ITEM; i++)
this->symbolicReg[i] = UNSET;
this->uniqueID = 0;
}
void SymbolicEngine::init(const SymbolicEngine &other) {
for (uint64 i = 0; i < ID_LAST_ITEM; i++)
this->symbolicReg[i] = other.symbolicReg[i];
this->uniqueID = other.uniqueID;
this->memoryReference = other.memoryReference;
this->pathConstaints = other.pathConstaints;
this->symbolicExpressions = other.symbolicExpressions;
this->symbolicVariables = other.symbolicVariables;
}
SymbolicEngine::SymbolicEngine(const SymbolicEngine ©) {
this->init(copy);
}
void SymbolicEngine::operator=(const SymbolicEngine &other) {
this->init(other);
}
SymbolicEngine::~SymbolicEngine() {
std::vector<SymbolicExpression *>::iterator it1 = this->symbolicExpressions.begin();
std::vector<SymbolicVariable *>::iterator it2 = this->symbolicVariables.begin();
/* Delete all symbolic expressions */
for (; it1 != this->symbolicExpressions.end(); ++it1)
delete *it1;
/* Delete all symbolic variables */
for (; it2 != this->symbolicVariables.end(); ++it2)
delete *it2;
}
/*
* Concretize a register. If the register is setup at UNSETthe next assignment
* will be over the concretization. This method must be called before symbolic
* processing.
*/
void SymbolicEngine::concretizeReg(uint64 regID) {
if (regID >= ID_LAST_ITEM)
return ;
this->symbolicReg[regID] = UNSET;
}
/* Same as concretizeReg but with all registers */
void SymbolicEngine::concretizeAllReg(void) {
for (uint64 i = 0; i < ID_LAST_ITEM; i++)
this->symbolicReg[i] = UNSET;
}
/*
* Concretize a memory. If the memory is not found into the map, the next
* assignment will be over the concretization. This method must be called
* before symbolic processing.
*/
void SymbolicEngine::concretizeMem(uint64 mem) {
this->memoryReference.erase(mem);
}
/* Same as concretizeMem but with all address memory */
void SymbolicEngine::concretizeAllMem(void) {
this->memoryReference.clear();
}
/* Returns the reference memory if it's referenced otherwise returns UNSET */
uint64 SymbolicEngine::getMemSymbolicID(uint64 addr) {
std::map<uint64, uint64>::iterator it;
if ((it = this->memoryReference.find(addr)) != this->memoryReference.end())
return it->second;
return UNSET;
}
/* Returns the symbolic variable otherwise returns nullptr */
SymbolicVariable *SymbolicEngine::getSymVar(uint64 symVarId) {
if (symVarId >= this->symbolicVariables.size())
return nullptr;
return this->symbolicVariables[symVarId];
}
/* Returns the symbolic variable otherwise returns nullptr */
SymbolicVariable *SymbolicEngine::getSymVar(std::string symVarName) {
std::vector<SymbolicVariable *>::iterator it;
for (it = this->symbolicVariables.begin(); it != this->symbolicVariables.end(); it++){
if ((*it)->getSymVarName() == symVarName)
return *it;
}
return nullptr;
}
/* Returns all symbolic variables */
std::vector<SymbolicVariable *> SymbolicEngine::getSymVars(void) {
return this->symbolicVariables;
}
/* Return the reg reference or UNSET */
uint64 SymbolicEngine::getRegSymbolicID(uint64 regID) {
if (regID >= ID_LAST_ITEM)
return UNSET;
return this->symbolicReg[regID];
}
/* Create a new symbolic expression */
/* Get an unique ID.
* Mainly used when a new symbolic expression is created */
uint64 SymbolicEngine::getUniqueID() {
return this->uniqueID++;
}
/* Create a new symbolic expression with comment */
SymbolicExpression *SymbolicEngine::newSymbolicExpression(smt2lib::smtAstAbstractNode *node, std::string comment) {
uint64 id = this->getUniqueID();
SymbolicExpression *expr = new SymbolicExpression(node, id, comment);
this->symbolicExpressions.push_back(expr);
return expr;
}
/* Get the symbolic expression pointer from a symbolic ID */
SymbolicExpression *SymbolicEngine::getExpressionFromId(uint64 id) {
if (id >= this->symbolicExpressions.size())
return nullptr;
return this->symbolicExpressions[id];
}
/* Returns all symbolic expressions */
std::vector<SymbolicExpression *> SymbolicEngine::getExpressions(void) {
return this->symbolicExpressions;
}
/* Returns the full symbolic expression backtracked. */
smt2lib::smtAstAbstractNode *SymbolicEngine::getFullExpression(smt2lib::smtAstAbstractNode *node) {
uint64 index = 0;
std::vector<smt2lib::smtAstAbstractNode *> &childs = node->getChilds();
for ( ; index < childs.size(); index++) {
if (childs[index]->getKind() == smt2lib::REFERENCE_NODE) {
uint64 id = reinterpret_cast<smt2lib::smtAstReferenceNode*>(childs[index])->getValue();
smt2lib::smtAstAbstractNode *ref = this->getExpressionFromId(id)->getExpression();
childs[index] = smt2lib::newInstance(ref);
}
this->getFullExpression(childs[index]);
}
return node;
}
/* Returns a list which contains all tainted expressions */
std::list<SymbolicExpression *> SymbolicEngine::getTaintedExpressions(void) {
uint64 index = 0;
std::list<SymbolicExpression *> taintedExprs;
for ( ; index < this->symbolicExpressions.size(); index++) {
if (symbolicExpressions[index]->isTainted == true)
taintedExprs.push_back(symbolicExpressions[index]);
}
return taintedExprs;
}
/* Returns the list of the symbolic variables declared in the trace */
std::string SymbolicEngine::getVariablesDeclaration(void) {
std::vector<SymbolicVariable*>::iterator it;
std::stringstream stream;
for(it = this->symbolicVariables.begin(); it != this->symbolicVariables.end(); it++)
stream << smt2lib::declare((*it)->getSymVarName(), (*it)->getSymVarSize());
return stream.str();
}
/*
* Converts an expression ID to a symbolic variable.
* e.g:
* #43 = (_ bv10 8)
* convertExprToSymVar(43, 8)
* #43 = SymVar_4
*/
SymbolicVariable *SymbolicEngine::convertExprToSymVar(uint64 exprId, uint64 symVarSize, std::string symVarComment) {
SymbolicVariable *symVar = nullptr;
SymbolicExpression *expression = this->getExpressionFromId(exprId);
if (expression == nullptr)
return nullptr;
symVar = this->addSymbolicVariable(SymVar::kind::UNDEF, 0, symVarSize, symVarComment);
expression->setExpression(smt2lib::variable(symVar->getSymVarName()));
return symVar;
}
SymbolicVariable *SymbolicEngine::convertMemToSymVar(uint64 memAddr, uint64 symVarSize, std::string symVarComment) {
SymbolicVariable *symVar = nullptr;
SymbolicExpression *expression = nullptr;
uint64 memSymId = UNSET;
memSymId = this->getMemSymbolicID(memAddr);
if (memSymId == UNSET)
throw std::runtime_error("SymbolicEngine::convertMemToSymVar() - This memory address is UNSET");
expression = this->getExpressionFromId(memSymId);
if (expression == nullptr)
return nullptr;
symVar = this->addSymbolicVariable(SymVar::kind::MEM, memAddr, symVarSize, symVarComment);
expression->setExpression(smt2lib::variable(symVar->getSymVarName()));
return symVar;
}
SymbolicVariable *SymbolicEngine::convertRegToSymVar(uint64 regId, uint64 symVarSize, std::string symVarComment) {
SymbolicVariable *symVar = nullptr;
SymbolicExpression *expression = nullptr;
uint64 regSymId = UNSET;
if (regId >= ID_LAST_ITEM)
throw std::runtime_error("SymbolicEngine::convertRegToSymVar() - Invalid register ID");
regSymId = this->getRegSymbolicID(regId);
if (regSymId == UNSET)
throw std::runtime_error("SymbolicEngine::convertRegToSymVar() - This register ID is UNSET");
expression = this->getExpressionFromId(regSymId);
if (expression == nullptr)
return nullptr;
symVar = this->addSymbolicVariable(SymVar::kind::REG, regId, symVarSize, symVarComment);
expression->setExpression(smt2lib::variable(symVar->getSymVarName()));
return symVar;
}
/* Add a new symbolic variable */
SymbolicVariable *SymbolicEngine::addSymbolicVariable(SymVar::kind kind, uint64 kindValue, uint64 size, std::string comment) {
uint64 uniqueID = this->symbolicVariables.size();
SymbolicVariable *symVar = new SymbolicVariable(kind, kindValue, uniqueID, size, comment);
if (symVar == nullptr)
throw std::runtime_error("SymbolicEngine::addSymbolicVariable() - Cannot allocate a new symbolic variable");
this->symbolicVariables.push_back(symVar);
return symVar;
}
/* Add and assign a new memory reference */
void SymbolicEngine::addMemoryReference(uint64 mem, uint64 id) {
this->memoryReference[mem] = id;
}
/* The a path constraint in the PC list */
void SymbolicEngine::addPathConstraint(uint64 exprId) {
this->pathConstaints.push_back(exprId);
}
/* Returns the path constrains list */
std::list<uint64> SymbolicEngine::getPathConstraints(void) {
return this->pathConstaints;
}
<commit_msg>#109 in progress - Create symVar when it is UNSET<commit_after>/*
** Copyright (C) - Triton
**
** This program is under the terms of the LGPLv3 License.
*/
#include <SymbolicEngine.h>
#include <Registers.h>
SymbolicEngine::SymbolicEngine() {
/* Init all symbolic registers/flags to UNSET (init state) */
for (uint64 i = 0; i < ID_LAST_ITEM; i++)
this->symbolicReg[i] = UNSET;
this->uniqueID = 0;
}
void SymbolicEngine::init(const SymbolicEngine &other) {
for (uint64 i = 0; i < ID_LAST_ITEM; i++)
this->symbolicReg[i] = other.symbolicReg[i];
this->uniqueID = other.uniqueID;
this->memoryReference = other.memoryReference;
this->pathConstaints = other.pathConstaints;
this->symbolicExpressions = other.symbolicExpressions;
this->symbolicVariables = other.symbolicVariables;
}
SymbolicEngine::SymbolicEngine(const SymbolicEngine ©) {
this->init(copy);
}
void SymbolicEngine::operator=(const SymbolicEngine &other) {
this->init(other);
}
SymbolicEngine::~SymbolicEngine() {
std::vector<SymbolicExpression *>::iterator it1 = this->symbolicExpressions.begin();
std::vector<SymbolicVariable *>::iterator it2 = this->symbolicVariables.begin();
/* Delete all symbolic expressions */
for (; it1 != this->symbolicExpressions.end(); ++it1)
delete *it1;
/* Delete all symbolic variables */
for (; it2 != this->symbolicVariables.end(); ++it2)
delete *it2;
}
/*
* Concretize a register. If the register is setup at UNSETthe next assignment
* will be over the concretization. This method must be called before symbolic
* processing.
*/
void SymbolicEngine::concretizeReg(uint64 regID) {
if (regID >= ID_LAST_ITEM)
return ;
this->symbolicReg[regID] = UNSET;
}
/* Same as concretizeReg but with all registers */
void SymbolicEngine::concretizeAllReg(void) {
for (uint64 i = 0; i < ID_LAST_ITEM; i++)
this->symbolicReg[i] = UNSET;
}
/*
* Concretize a memory. If the memory is not found into the map, the next
* assignment will be over the concretization. This method must be called
* before symbolic processing.
*/
void SymbolicEngine::concretizeMem(uint64 mem) {
this->memoryReference.erase(mem);
}
/* Same as concretizeMem but with all address memory */
void SymbolicEngine::concretizeAllMem(void) {
this->memoryReference.clear();
}
/* Returns the reference memory if it's referenced otherwise returns UNSET */
uint64 SymbolicEngine::getMemSymbolicID(uint64 addr) {
std::map<uint64, uint64>::iterator it;
if ((it = this->memoryReference.find(addr)) != this->memoryReference.end())
return it->second;
return UNSET;
}
/* Returns the symbolic variable otherwise returns nullptr */
SymbolicVariable *SymbolicEngine::getSymVar(uint64 symVarId) {
if (symVarId >= this->symbolicVariables.size())
return nullptr;
return this->symbolicVariables[symVarId];
}
/* Returns the symbolic variable otherwise returns nullptr */
SymbolicVariable *SymbolicEngine::getSymVar(std::string symVarName) {
std::vector<SymbolicVariable *>::iterator it;
for (it = this->symbolicVariables.begin(); it != this->symbolicVariables.end(); it++){
if ((*it)->getSymVarName() == symVarName)
return *it;
}
return nullptr;
}
/* Returns all symbolic variables */
std::vector<SymbolicVariable *> SymbolicEngine::getSymVars(void) {
return this->symbolicVariables;
}
/* Return the reg reference or UNSET */
uint64 SymbolicEngine::getRegSymbolicID(uint64 regID) {
if (regID >= ID_LAST_ITEM)
return UNSET;
return this->symbolicReg[regID];
}
/* Create a new symbolic expression */
/* Get an unique ID.
* Mainly used when a new symbolic expression is created */
uint64 SymbolicEngine::getUniqueID() {
return this->uniqueID++;
}
/* Create a new symbolic expression with comment */
SymbolicExpression *SymbolicEngine::newSymbolicExpression(smt2lib::smtAstAbstractNode *node, std::string comment) {
uint64 id = this->getUniqueID();
SymbolicExpression *expr = new SymbolicExpression(node, id, comment);
this->symbolicExpressions.push_back(expr);
return expr;
}
/* Get the symbolic expression pointer from a symbolic ID */
SymbolicExpression *SymbolicEngine::getExpressionFromId(uint64 id) {
if (id >= this->symbolicExpressions.size())
return nullptr;
return this->symbolicExpressions[id];
}
/* Returns all symbolic expressions */
std::vector<SymbolicExpression *> SymbolicEngine::getExpressions(void) {
return this->symbolicExpressions;
}
/* Returns the full symbolic expression backtracked. */
smt2lib::smtAstAbstractNode *SymbolicEngine::getFullExpression(smt2lib::smtAstAbstractNode *node) {
uint64 index = 0;
std::vector<smt2lib::smtAstAbstractNode *> &childs = node->getChilds();
for ( ; index < childs.size(); index++) {
if (childs[index]->getKind() == smt2lib::REFERENCE_NODE) {
uint64 id = reinterpret_cast<smt2lib::smtAstReferenceNode*>(childs[index])->getValue();
smt2lib::smtAstAbstractNode *ref = this->getExpressionFromId(id)->getExpression();
childs[index] = smt2lib::newInstance(ref);
}
this->getFullExpression(childs[index]);
}
return node;
}
/* Returns a list which contains all tainted expressions */
std::list<SymbolicExpression *> SymbolicEngine::getTaintedExpressions(void) {
uint64 index = 0;
std::list<SymbolicExpression *> taintedExprs;
for ( ; index < this->symbolicExpressions.size(); index++) {
if (symbolicExpressions[index]->isTainted == true)
taintedExprs.push_back(symbolicExpressions[index]);
}
return taintedExprs;
}
/* Returns the list of the symbolic variables declared in the trace */
std::string SymbolicEngine::getVariablesDeclaration(void) {
std::vector<SymbolicVariable*>::iterator it;
std::stringstream stream;
for(it = this->symbolicVariables.begin(); it != this->symbolicVariables.end(); it++)
stream << smt2lib::declare((*it)->getSymVarName(), (*it)->getSymVarSize());
return stream.str();
}
/*
* Converts an expression ID to a symbolic variable.
* e.g:
* #43 = (_ bv10 8)
* convertExprToSymVar(43, 8)
* #43 = SymVar_4
*/
SymbolicVariable *SymbolicEngine::convertExprToSymVar(uint64 exprId, uint64 symVarSize, std::string symVarComment) {
SymbolicVariable *symVar = nullptr;
SymbolicExpression *expression = this->getExpressionFromId(exprId);
if (expression == nullptr)
return nullptr;
symVar = this->addSymbolicVariable(SymVar::kind::UNDEF, 0, symVarSize, symVarComment);
expression->setExpression(smt2lib::variable(symVar->getSymVarName()));
return symVar;
}
SymbolicVariable *SymbolicEngine::convertMemToSymVar(uint64 memAddr, uint64 symVarSize, std::string symVarComment) {
SymbolicVariable *symVar = nullptr;
SymbolicExpression *expression = nullptr;
uint64 memSymId = UNSET;
memSymId = this->getMemSymbolicID(memAddr);
if (memSymId == UNSET)
/* TODO #109: Create it if UNSET */
throw std::runtime_error("SymbolicEngine::convertMemToSymVar() - This memory address is UNSET");
expression = this->getExpressionFromId(memSymId);
if (expression == nullptr)
return nullptr;
symVar = this->addSymbolicVariable(SymVar::kind::MEM, memAddr, symVarSize, symVarComment);
expression->setExpression(smt2lib::variable(symVar->getSymVarName()));
return symVar;
}
SymbolicVariable *SymbolicEngine::convertRegToSymVar(uint64 regId, uint64 symVarSize, std::string symVarComment) {
SymbolicVariable *symVar = nullptr;
SymbolicExpression *expression = nullptr;
uint64 regSymId = UNSET;
if (regId >= ID_LAST_ITEM)
throw std::runtime_error("SymbolicEngine::convertRegToSymVar() - Invalid register ID");
regSymId = this->getRegSymbolicID(regId);
if (regSymId == UNSET) {
symVar = this->addSymbolicVariable(SymVar::kind::REG, regId, symVarSize, symVarComment);
smt2lib::smtAstAbstractNode *tmp = smt2lib::variable(symVar->getSymVarName());
if (tmp == nullptr)
throw std::runtime_error("convertRegToSymVar can't create smtAstAbstractNode (nullptr)");
SymbolicExpression *se = this->newSymbolicExpression(tmp);
if (se == nullptr)
throw std::runtime_error("convertRegToSymVar can't create symbolic expression (nullptr)");
this->symbolicReg[regId] = se->getID();
}
else {
expression = this->getExpressionFromId(regSymId);
if (expression == nullptr)
return nullptr;
symVar = this->addSymbolicVariable(SymVar::kind::REG, regId, symVarSize, symVarComment);
expression->setExpression(smt2lib::variable(symVar->getSymVarName()));
}
return symVar;
}
/* Add a new symbolic variable */
SymbolicVariable *SymbolicEngine::addSymbolicVariable(SymVar::kind kind, uint64 kindValue, uint64 size, std::string comment) {
uint64 uniqueID = this->symbolicVariables.size();
SymbolicVariable *symVar = new SymbolicVariable(kind, kindValue, uniqueID, size, comment);
if (symVar == nullptr)
throw std::runtime_error("SymbolicEngine::addSymbolicVariable() - Cannot allocate a new symbolic variable");
this->symbolicVariables.push_back(symVar);
return symVar;
}
/* Add and assign a new memory reference */
void SymbolicEngine::addMemoryReference(uint64 mem, uint64 id) {
this->memoryReference[mem] = id;
}
/* The a path constraint in the PC list */
void SymbolicEngine::addPathConstraint(uint64 exprId) {
this->pathConstaints.push_back(exprId);
}
/* Returns the path constrains list */
std::list<uint64> SymbolicEngine::getPathConstraints(void) {
return this->pathConstaints;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
//
// File contains modifications by: The Gulden developers
// All modifications:
// Copyright (c) 2016-2018 The Gulden developers
// Authored by: Malcolm MacLeod (mmacleod@webmail.co.za)
// Distributed under the GULDEN software license, see the accompanying
// file COPYING
#if defined(HAVE_CONFIG_H)
#include "config/gulden-config.h"
#endif
#include "chainparams.h"
#include "clientversion.h"
#include "compat.h"
#include "fs.h"
#include "rpc/server.h"
#include "init.h"
#include "noui.h"
#include "scheduler.h"
#include "util.h"
#include "httpserver.h"
#include "httprpc.h"
#include "utilstrencodings.h"
#include "net.h"
#include <unity/appmanager.h>
#include <boost/thread.hpp>
#include <boost/interprocess/sync/file_lock.hpp>
#include <stdio.h>
#define _(x) std::string(x)/* Keep the _() around in case gettext or such will be used later to translate non-UI */
/* Introduction text for doxygen: */
/*! \mainpage Developer documentation
*
* \section intro_sec Introduction
*
* This is the developer documentation of the reference client for an experimental new digital currency called Gulden (https://www.gulden.com),
* which enables instant payments to anyone, anywhere in the world. Gulden uses peer-to-peer technology to operate
* with no central authority: managing transactions and issuing money are carried out collectively by the network.
*
* The software is a community-driven open source project, released under the MIT license.
*
* \section Navigation
* Use the buttons <code>Namespaces</code>, <code>Classes</code> or <code>Files</code> at the top of the page to start navigating the code.
*/
int exitStatus = EXIT_SUCCESS;
bool shutDownFinalised = false;
static void handleFinalShutdown()
{
shutDownFinalised = true;
}
static void WaitForShutdown()
{
while (!shutDownFinalised)
{
MilliSleep(200);
}
}
static void handlePostInitMain()
{
//fixme: (UNITY) - This is now duplicated, factor this out into a common helper.
//Also shouldn't this happen earlier in the init process?
// Make sure only a single Gulden process is using the data directory.
fs::path pathLockFile = GetDataDir() / ".lock";
FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist.
if (file) fclose(file);
try
{
static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
if (!lock.try_lock())
{
fprintf(stderr, "Cannot obtain a lock on data directory %s. %s is probably already running.", GetDataDir().string().c_str(), _(PACKAGE_NAME).c_str());
exitStatus = EXIT_FAILURE;
GuldenAppManager::gApp->shutdown();
return;
}
}
catch(const boost::interprocess::interprocess_exception& e)
{
fprintf(stderr, "Cannot obtain a lock on data directory %s. %s is probably already running.", GetDataDir().string().c_str(), _(PACKAGE_NAME).c_str());
exitStatus = EXIT_FAILURE;
GuldenAppManager::gApp->shutdown();
return;
}
}
static void handleAppInitResult(bool bResult)
{
if (!bResult)
{
// InitError will have been called with detailed error, which ends up on console
exitStatus = EXIT_FAILURE;
GuldenAppManager::gApp->shutdown();
return;
}
handlePostInitMain();
}
static bool handlePreInitMain()
{
return true;
}
//////////////////////////////////////////////////////////////////////////////
//
// Start
//
static void AppInit(int argc, char* argv[])
{
GuldenAppManager appManager;
appManager.signalAppInitializeResult.connect(boost::bind(handleAppInitResult, _1));
appManager.signalAboutToInitMain.connect(&handlePreInitMain);
appManager.signalAppShutdownFinished.connect(&handleFinalShutdown);
//fixme: (UNITY) - refactor this some more so that init is taken care of inside the app manager (like with qt app)
//
// Parameters
//
// If Qt is used, parameters/Gulden.conf are parsed in qt/Gulden.cpp's main()
ParseParameters(argc, argv);
// Process help and version before taking care about datadir
if (IsArgSet("-?") || IsArgSet("-h") || IsArgSet("-help") || IsArgSet("-version"))
{
std::string strUsage = strprintf(_("%s Daemon"), _(PACKAGE_NAME)) + " " + _("version") + " " + FormatFullVersion() + "\n";
if (IsArgSet("-version"))
{
strUsage += FormatParagraph(LicenseInfo());
}
else
{
strUsage += "\n" + _("Usage:") + "\n" + " GuldenD [options] " + strprintf(_("Start %s Daemon"), _(PACKAGE_NAME)) + "\n";
strUsage += "\n" + HelpMessage(HMM_GULDEND);
}
fprintf(stdout, "%s", strUsage.c_str());
return;
}
//NB! Must be set before AppInitMain.
fNoUI = true;
try
{
if (!fs::is_directory(GetDataDir(false)))
{
fprintf(stderr, "Error: Specified data directory \"%s\" does not exist.\n", GetArg("-datadir", "").c_str());
exitStatus = EXIT_FAILURE;
return;
}
try
{
ReadConfigFile(GetArg("-conf", GULDEN_CONF_FILENAME));
}
catch (const std::exception& e)
{
fprintf(stderr,"Error reading configuration file: %s\n", e.what());
exitStatus = EXIT_FAILURE;
return;
}
// Check for -testnet or -regtest parameter (Params() calls are only valid after this clause)
try
{
SelectParams(ChainNameFromCommandLine());
}
catch (const std::exception& e)
{
fprintf(stderr, "Error: %s\n", e.what());
exitStatus = EXIT_FAILURE;
return;
}
// Error out when loose non-argument tokens are encountered on command line
for (int i = 1; i < argc; i++)
{
if (!IsSwitchChar(argv[i][0]))
{
fprintf(stderr, "Error: Command line contains unexpected token '%s', see GuldenD -h for a list of options.\n", argv[i]);
exitStatus = EXIT_FAILURE;
return;
}
}
// -server defaults to true for GuldenD but not for the GUI so do this here
SoftSetBoolArg("-server", true);
// Set this early so that parameter interactions go to console
InitLogging();
InitParameterInteraction();
if (GetBoolArg("-daemon", false))
{
fprintf(stdout, "Gulden server starting\n");
if (!GuldenAppManager::gApp->daemonise())
{
LogPrintf("Failed to daemonise\n");
exitStatus = EXIT_FAILURE;
return;
}
}
appManager.initialize();
}
catch (const std::exception& e)
{
PrintExceptionContinue(&e, "AppInit()");
}
catch (...)
{
PrintExceptionContinue(NULL, "AppInit()");
}
//fixme: (UNITY) - It would be much better to wait on a condition variable here.
// Busy poll for shutdown and allow app to exit when we reach there.
WaitForShutdown();
}
int main(int argc, char* argv[])
{
SetupEnvironment();
// Connect GuldenD signal handlers
noui_connect();
AppInit(argc, argv);
return exitStatus;
}
<commit_msg>Fix an issue with GuldenD not checking lock early enough when -daemon flag is passed.<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
//
// File contains modifications by: The Gulden developers
// All modifications:
// Copyright (c) 2016-2018 The Gulden developers
// Authored by: Malcolm MacLeod (mmacleod@webmail.co.za)
// Distributed under the GULDEN software license, see the accompanying
// file COPYING
#if defined(HAVE_CONFIG_H)
#include "config/gulden-config.h"
#endif
#include "chainparams.h"
#include "clientversion.h"
#include "compat.h"
#include "fs.h"
#include "rpc/server.h"
#include "init.h"
#include "noui.h"
#include "scheduler.h"
#include "util.h"
#include "httpserver.h"
#include "httprpc.h"
#include "utilstrencodings.h"
#include "net.h"
#include <unity/appmanager.h>
#include <boost/thread.hpp>
#include <boost/interprocess/sync/file_lock.hpp>
#include <stdio.h>
#define _(x) std::string(x)/* Keep the _() around in case gettext or such will be used later to translate non-UI */
/* Introduction text for doxygen: */
/*! \mainpage Developer documentation
*
* \section intro_sec Introduction
*
* This is the developer documentation of the reference client for an experimental new digital currency called Gulden (https://www.gulden.com),
* which enables instant payments to anyone, anywhere in the world. Gulden uses peer-to-peer technology to operate
* with no central authority: managing transactions and issuing money are carried out collectively by the network.
*
* The software is a community-driven open source project, released under the MIT license.
*
* \section Navigation
* Use the buttons <code>Namespaces</code>, <code>Classes</code> or <code>Files</code> at the top of the page to start navigating the code.
*/
int exitStatus = EXIT_SUCCESS;
bool shutDownFinalised = false;
static void handleFinalShutdown()
{
shutDownFinalised = true;
}
static void WaitForShutdown()
{
while (!shutDownFinalised)
{
MilliSleep(200);
}
}
static void handlePostInitMain()
{
}
static void handleAppInitResult(bool bResult)
{
if (!bResult)
{
// InitError will have been called with detailed error, which ends up on console
exitStatus = EXIT_FAILURE;
GuldenAppManager::gApp->shutdown();
return;
}
handlePostInitMain();
}
static bool handlePreInitMain()
{
return true;
}
//////////////////////////////////////////////////////////////////////////////
//
// Start
//
static void AppInit(int argc, char* argv[])
{
GuldenAppManager appManager;
appManager.signalAppInitializeResult.connect(boost::bind(handleAppInitResult, _1));
appManager.signalAboutToInitMain.connect(&handlePreInitMain);
appManager.signalAppShutdownFinished.connect(&handleFinalShutdown);
//fixme: (UNITY) - refactor this some more so that init is taken care of inside the app manager (like with qt app)
//
// Parameters
//
// If Qt is used, parameters/Gulden.conf are parsed in qt/Gulden.cpp's main()
ParseParameters(argc, argv);
// Process help and version before taking care about datadir
if (IsArgSet("-?") || IsArgSet("-h") || IsArgSet("-help") || IsArgSet("-version"))
{
std::string strUsage = strprintf(_("%s Daemon"), _(PACKAGE_NAME)) + " " + _("version") + " " + FormatFullVersion() + "\n";
if (IsArgSet("-version"))
{
strUsage += FormatParagraph(LicenseInfo());
}
else
{
strUsage += "\n" + _("Usage:") + "\n" + " GuldenD [options] " + strprintf(_("Start %s Daemon"), _(PACKAGE_NAME)) + "\n";
strUsage += "\n" + HelpMessage(HMM_GULDEND);
}
fprintf(stdout, "%s", strUsage.c_str());
return;
}
//NB! Must be set before AppInitMain.
fNoUI = true;
try
{
if (!fs::is_directory(GetDataDir(false)))
{
fprintf(stderr, "Error: Specified data directory \"%s\" does not exist.\n", GetArg("-datadir", "").c_str());
exitStatus = EXIT_FAILURE;
return;
}
try
{
ReadConfigFile(GetArg("-conf", GULDEN_CONF_FILENAME));
}
catch (const std::exception& e)
{
fprintf(stderr,"Error reading configuration file: %s\n", e.what());
exitStatus = EXIT_FAILURE;
return;
}
// Check for -testnet or -regtest parameter (Params() calls are only valid after this clause)
try
{
SelectParams(ChainNameFromCommandLine());
}
catch (const std::exception& e)
{
fprintf(stderr, "Error: %s\n", e.what());
exitStatus = EXIT_FAILURE;
return;
}
// Error out when loose non-argument tokens are encountered on command line
for (int i = 1; i < argc; i++)
{
if (!IsSwitchChar(argv[i][0]))
{
fprintf(stderr, "Error: Command line contains unexpected token '%s', see GuldenD -h for a list of options.\n", argv[i]);
exitStatus = EXIT_FAILURE;
return;
}
}
// -server defaults to true for GuldenD but not for the GUI so do this here
SoftSetBoolArg("-server", true);
// Set this early so that parameter interactions go to console
InitLogging();
InitParameterInteraction();
//fixme: (UNITY) - This is now duplicated, factor this out into a common helper.
// NB! This has to happen before we deamonise
// Make sure only a single Gulden process is using the data directory.
{
fs::path pathLockFile = GetDataDir() / ".lock";
FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist.
if (file)
fclose(file);
try
{
static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
if (!lock.try_lock())
{
fprintf(stderr, "Cannot obtain a lock on data directory %s. %s is probably already running.", GetDataDir().string().c_str(), _(PACKAGE_NAME).c_str());
exitStatus = EXIT_FAILURE;
GuldenAppManager::gApp->shutdown();
return;
}
}
catch(const boost::interprocess::interprocess_exception& e)
{
fprintf(stderr, "Cannot obtain a lock on data directory %s. %s is probably already running.", GetDataDir().string().c_str(), _(PACKAGE_NAME).c_str());
exitStatus = EXIT_FAILURE;
GuldenAppManager::gApp->shutdown();
return;
}
}
if (GetBoolArg("-daemon", false))
{
fprintf(stdout, "Gulden server starting\n");
if (!GuldenAppManager::gApp->daemonise())
{
LogPrintf("Failed to daemonise\n");
exitStatus = EXIT_FAILURE;
return;
}
}
appManager.initialize();
}
catch (const std::exception& e)
{
PrintExceptionContinue(&e, "AppInit()");
}
catch (...)
{
PrintExceptionContinue(NULL, "AppInit()");
}
//fixme: (UNITY) - It would be much better to wait on a condition variable here.
// Busy poll for shutdown and allow app to exit when we reach there.
WaitForShutdown();
}
int main(int argc, char* argv[])
{
SetupEnvironment();
// Connect GuldenD signal handlers
noui_connect();
AppInit(argc, argv);
return exitStatus;
}
<|endoftext|>
|
<commit_before>/**
Copyright (c) 2016, Philip Deegan.
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 Philip Deegan nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _KUL_DB_HPP_
#define _KUL_DB_HPP_
#include <vector>
#include <sstream>
#include "kul/map.hpp"
#include "kul/except.hpp"
#include "kul/db/def.hpp"
namespace kul{
namespace db{
class Exception : public kul::Exception{
public:
Exception(const char*f, const uint16_t& l, std::string s) : kul::Exception(f, l, s){}
};
}
class ORM;
class DB{
protected:
const std::string n;
DB(const std::string& n = "") : n(n){}
friend class kul::ORM;
public:
virtual std::string exec_return(const std::string& sql) throw(db::Exception) = 0;
virtual void exec(const std::string& s) throw(db::Exception) = 0;
};
namespace orm{
template <class T>
class AObject{
private:
bool n = 0;
kul::hash::set::String di;
kul::hash::map::S2S fs;
template <class R> friend std::ostream& operator<<(std::ostream&, const AObject<R>&);
protected:
const std::string& field(const std::string& s) const{
if(!fs.count(s)) KEXCEPTION("ORM error, no field: " + s);
return (*fs.find(s)).second;
}
template<class R>
const R field(const std::string& s) const{
std::stringstream ss(field(s));
R r;
ss >> r;
return r;
}
public:
const std::string& created() const { return (*fs.find(_KUL_DB_CREATED_COL_)).second; }
const std::string& updated() const { return (*fs.find(_KUL_DB_UPDATED_COL_)).second; }
template<class V = std::string>
AObject<T>& set(const std::string& s, const V& v){
std::stringstream ss;
ss << v;
fs[s] = ss.str();
di.insert(s);
return *this;
}
const std::string& operator[](const std::string& s) const{
return field(s);
}
template<class R>
R get(const std::string& s) const{
return this->template field<R>(s);
}
friend class kul::ORM;
};
template <class T> std::ostream& operator<<(std::ostream &s, const kul::orm::AObject<T>& o);
}
class ORM{
protected:
DB& db;
virtual void populate(const std::string& s, std::vector<kul::hash::map::S2S>& vals) = 0;
template <class T>
std::string table(){
return db.n.size() ? (db.n+"."+T::TABLE()) : T::TABLE();
}
template <class T>
void update(orm::AObject<T>& o){
if(o.di.size() == 0) return;
std::time_t now = std::time(0);
std::stringstream ss;
ss << "UPDATE " << table<T>() << " SET ";
for(const auto& d : o.di)
ss << d << "='" << o.fs[d] << "',";
ss << " updated = " << now;
ss << " WHERE id = '" << o.fs[_KUL_DB_ID_COL_] << "'";
db.exec(ss.str());
o.set(_KUL_DB_UPDATED_COL_, now);
o.di.clear();
}
template <class T>
void insert(orm::AObject<T>& o){
std::time_t now = std::time(0);
std::stringstream ss;
ss << "INSERT INTO " << table<T>() << "(";
for(const auto& p : o.fs) ss << p.first << ", ";
ss << _KUL_DB_CREATED_COL_ << " ," << _KUL_DB_UPDATED_COL_ << ") VALUES(";
for(const auto& p : o.fs) ss << "'" << p.second << "', ";
ss << now << ", " << now << ") RETURNING " << _KUL_DB_ID_COL_;
o.set(_KUL_DB_ID_COL_ , db.exec_return(ss.str()));
o.set(_KUL_DB_CREATED_COL_, now);
o.set(_KUL_DB_UPDATED_COL_, now);
o.n = 0;
o.di.clear();
}
public:
ORM(DB& db) : db(db){}
template <class T>
void commit(orm::AObject<T>& o){
if(o.n) insert(o);
else update(o);
}
template <class T>
void remove(const orm::AObject<T>& o){
std::stringstream ss;
ss << "DELETE FROM " << table<T>() << " t WHERE t." << _KUL_DB_ID_COL_ << " = '" << o[_KUL_DB_ID_COL_] << "'";
db.exec(ss.str());
}
template <class T>
void remove(const std::string& w){
std::stringstream ss;
ss << "DELETE FROM " << table<T>() << " t WHERE t." << w;
db.exec(ss.str());
}
template <class T>
void get(std::vector<T>& ts, const std::string& w = "", const uint16_t& l = 100, const uint16_t& o = 0, const std::string& g = ""){
std::stringstream ss;
ss << "SELECT * FROM " << table<T>() << " t ";
if(!w.empty()) ss << " WHERE " << w;
ss << " LIMIT " << l << " OFFSET " << o;
if(!g.empty()) ss << " GROUP BY " << g;
for(auto& t : ts) t.n = 0;
std::vector<kul::hash::map::S2S> vals;
populate(ss.str(), vals);
for(const auto& v : vals){
T t;
for(const auto& m : v) t.fs.insert(m.first, m.second);
ts.push_back(t);
}
}
template <class T, class V = std::string>
T by(const std::string& c, const V& v) throw(db::Exception) {
std::vector<T> ts;
std::stringstream ss, id;
id << v;
ss << "t." << c << " = '" << v << "'";
get(ts, ss.str(), 2, 0);
if(ts.size() == 0) KEXCEPT(db::Exception, "Table("+table<T>()+") : "+ _KUL_DB_ID_COL_ +":"+ id.str() +" does not exist");
if(ts.size() > 1) KEXCEPT(db::Exception, "Table("+table<T>()+") : "+ _KUL_DB_ID_COL_ +":"+ id.str() +" is a duplicate");
return ts[0];
}
template <class T>
T id(const _KUL_DB_ID_TYPE_& id) throw(db::Exception) {
return by<T, _KUL_DB_ID_TYPE_>(_KUL_DB_ID_COL_, id);
}
};
}
template <class T> std::ostream& kul::orm::operator<<(std::ostream &s, const kul::orm::AObject<T>& o){
std::stringstream ss;
for(const auto& p : o.fs)
ss << p.first << " : " << p.second << std::endl;
return s << ss.str();
}
#endif /* _KUL_DB_HPP_ */
<commit_msg>insert instead of []<commit_after>/**
Copyright (c) 2016, Philip Deegan.
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 Philip Deegan nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _KUL_DB_HPP_
#define _KUL_DB_HPP_
#include <vector>
#include <sstream>
#include "kul/map.hpp"
#include "kul/except.hpp"
#include "kul/db/def.hpp"
namespace kul{
namespace db{
class Exception : public kul::Exception{
public:
Exception(const char*f, const uint16_t& l, std::string s) : kul::Exception(f, l, s){}
};
}
class ORM;
class DB{
protected:
const std::string n;
DB(const std::string& n = "") : n(n){}
friend class kul::ORM;
public:
virtual std::string exec_return(const std::string& sql) throw(db::Exception) = 0;
virtual void exec(const std::string& s) throw(db::Exception) = 0;
};
namespace orm{
template <class T>
class AObject{
private:
bool n = 1;
kul::hash::set::String di;
kul::hash::map::S2S fs;
template <class R> friend std::ostream& operator<<(std::ostream&, const AObject<R>&);
protected:
const std::string& field(const std::string& s) const{
if(!fs.count(s)) KEXCEPTION("ORM error, no field: " + s);
return (*fs.find(s)).second;
}
template<class R>
const R field(const std::string& s) const{
std::stringstream ss(field(s));
R r;
ss >> r;
return r;
}
public:
const std::string& created() const { return (*fs.find(_KUL_DB_CREATED_COL_)).second; }
const std::string& updated() const { return (*fs.find(_KUL_DB_UPDATED_COL_)).second; }
template<class V = std::string>
AObject<T>& set(const std::string& s, const V& v){
std::stringstream ss;
ss << v;
fs.insert(s, ss.str());
di.insert(s);
return *this;
}
const std::string& operator[](const std::string& s) const{
return field(s);
}
template<class R>
R get(const std::string& s) const{
return this->template field<R>(s);
}
friend class kul::ORM;
};
template <class T> std::ostream& operator<<(std::ostream &s, const kul::orm::AObject<T>& o);
}
class ORM{
protected:
DB& db;
virtual void populate(const std::string& s, std::vector<kul::hash::map::S2S>& vals) = 0;
template <class T>
std::string table(){
return db.n.size() ? (db.n+"."+T::TABLE()) : T::TABLE();
}
template <class T>
void update(orm::AObject<T>& o){
if(o.di.size() == 0) return;
std::time_t now = std::time(0);
std::stringstream ss;
ss << "UPDATE " << table<T>() << " SET ";
for(const auto& d : o.di)
ss << d << "='" << o.fs[d] << "',";
ss << " updated = " << now;
ss << " WHERE id = '" << o.fs[_KUL_DB_ID_COL_] << "'";
db.exec(ss.str());
o.set(_KUL_DB_UPDATED_COL_, now);
o.di.clear();
}
template <class T>
void insert(orm::AObject<T>& o){
std::time_t now = std::time(0);
std::string nsw = std::to_string(now);
std::stringstream ss;
ss << "INSERT INTO " << table<T>() << "(";
for(const auto& p : o.fs) ss << p.first << ", ";
ss << _KUL_DB_CREATED_COL_ << " ," << _KUL_DB_UPDATED_COL_ << ") VALUES(";
for(const auto& p : o.fs) ss << "'" << p.second << "', ";
ss << now << ", " << now << ") RETURNING " << _KUL_DB_ID_COL_;
o.fs.insert(_KUL_DB_ID_COL_ , db.exec_return(ss.str()));
o.fs.insert(_KUL_DB_CREATED_COL_, nsw);
o.fs.insert(_KUL_DB_UPDATED_COL_, nsw);
o.n = 0;
o.di.clear();
}
public:
ORM(DB& db) : db(db){}
template <class T>
void commit(orm::AObject<T>& o){
if(o.n) insert(o);
else update(o);
}
template <class T>
void remove(const orm::AObject<T>& o){
std::stringstream ss;
ss << "DELETE FROM " << table<T>() << " t WHERE t." << _KUL_DB_ID_COL_ << " = '" << o[_KUL_DB_ID_COL_] << "'";
db.exec(ss.str());
}
template <class T>
void remove(const std::string& w){
std::stringstream ss;
ss << "DELETE FROM " << table<T>() << " t WHERE t." << w;
db.exec(ss.str());
}
template <class T>
void get(std::vector<T>& ts, const std::string& w = "", const uint16_t& l = 100, const uint16_t& o = 0, const std::string& g = ""){
std::stringstream ss;
ss << "SELECT * FROM " << table<T>() << " t ";
if(!w.empty()) ss << " WHERE " << w;
ss << " LIMIT " << l << " OFFSET " << o;
if(!g.empty()) ss << " GROUP BY " << g;
for(auto& t : ts) t.n = 0;
std::vector<kul::hash::map::S2S> vals;
populate(ss.str(), vals);
for(const auto& v : vals){
T t;
for(const auto& m : v) t.fs.insert(m.first, m.second);
ts.push_back(t);
}
}
template <class T, class V = std::string>
T by(const std::string& c, const V& v) throw(db::Exception) {
std::vector<T> ts;
std::stringstream ss, id;
id << v;
ss << "t." << c << " = '" << v << "'";
get(ts, ss.str(), 2, 0);
if(ts.size() == 0) KEXCEPT(db::Exception, "Table("+table<T>()+") : "+ _KUL_DB_ID_COL_ +":"+ id.str() +" does not exist");
if(ts.size() > 1) KEXCEPT(db::Exception, "Table("+table<T>()+") : "+ _KUL_DB_ID_COL_ +":"+ id.str() +" is a duplicate");
return ts[0];
}
template <class T>
T id(const _KUL_DB_ID_TYPE_& id) throw(db::Exception) {
return by<T, _KUL_DB_ID_TYPE_>(_KUL_DB_ID_COL_, id);
}
};
}
template <class T> std::ostream& kul::orm::operator<<(std::ostream &s, const kul::orm::AObject<T>& o){
std::stringstream ss;
for(const auto& p : o.fs)
ss << p.first << " : " << p.second << std::endl;
return s << ss.str();
}
#endif /* _KUL_DB_HPP_ */
<|endoftext|>
|
<commit_before>#include <uri.hpp>
#include <iostream>
using namespace uri;
///////////////////////////////////////////////////////////////////////////////
const URI::Span_t URI::zero_span_;
URI::URI(const std::string&& data) :
uri_str_ {std::forward<const std::string>(data)}
{
init_spans();
}
URI::URI(const char* data) :
uri_str_ {data}
{
init_spans();
}
std::string URI::path() const {
return uri_str_.substr(path_.begin, path_.end);
}
std::string URI::to_string() const{
return uri_str_;
}
///////////////////////////////////////////////////////////////////////////////
void URI::parse(const std::string& uri) {
static const std::regex uri_pattern_matcher
{
"^([\\w]+)?(\\://)?" //< scheme
"(([^:@]+)(\\:([^@]+))?@)?" //< username && password
"([^/:?#]+)?(\\:(\\d+))?" //< hostname && port
"([^?#]+)" //< path
"(\\?([^#]*))?" //< query
"(#(.*))?$" //< fragment
};
std::smatch uri_parts;
if (std::regex_match(uri, uri_parts, uri_pattern_matcher)) {
path_ = Span_t(uri_parts.position(10), uri_parts.length(10));
userinfo_ = uri_parts.length(3) ? Span_t(uri_parts.position(3), uri_parts.length(3)) : zero_span_;
host_ = uri_parts.length(7) ? Span_t(uri_parts.position(7), uri_parts.length(7)) : zero_span_;
port_str_ = uri_parts.length(9) ? Span_t(uri_parts.position(9), uri_parts.length(9)) : zero_span_;
query_ = uri_parts.length(11) ? Span_t(uri_parts.position(11), uri_parts.length(11)) : zero_span_;
fragment_ = uri_parts.length(12) ? Span_t(uri_parts.position(12), uri_parts.length(12)) : zero_span_;
}
}
std::ostream& uri::operator<< (std::ostream& out, const URI& uri) {
out << uri.to_string();
return out;
}
<commit_msg>Added seperators between method definitions<commit_after>#include <uri.hpp>
#include <iostream>
using namespace uri;
///////////////////////////////////////////////////////////////////////////////
const URI::Span_t URI::zero_span_;
///////////////////////////////////////////////////////////////////////////////
URI::URI(const std::string&& data) :
uri_str_ {std::forward<const std::string>(data)}
{
init_spans();
}
///////////////////////////////////////////////////////////////////////////////
URI::URI(const char* data) :
uri_str_ {data}
{
init_spans();
}
///////////////////////////////////////////////////////////////////////////////
std::string URI::path() const {
return uri_str_.substr(path_.begin, path_.end);
}
///////////////////////////////////////////////////////////////////////////////
std::string URI::to_string() const{
return uri_str_;
}
///////////////////////////////////////////////////////////////////////////////
void URI::parse(const std::string& uri) {
static const std::regex uri_pattern_matcher
{
"^([\\w]+)?(\\://)?" //< scheme
"(([^:@]+)(\\:([^@]+))?@)?" //< username && password
"([^/:?#]+)?(\\:(\\d+))?" //< hostname && port
"([^?#]+)" //< path
"(\\?([^#]*))?" //< query
"(#(.*))?$" //< fragment
};
std::smatch uri_parts;
if (std::regex_match(uri, uri_parts, uri_pattern_matcher)) {
path_ = Span_t(uri_parts.position(10), uri_parts.length(10));
userinfo_ = uri_parts.length(3) ? Span_t(uri_parts.position(3), uri_parts.length(3)) : zero_span_;
host_ = uri_parts.length(7) ? Span_t(uri_parts.position(7), uri_parts.length(7)) : zero_span_;
port_str_ = uri_parts.length(9) ? Span_t(uri_parts.position(9), uri_parts.length(9)) : zero_span_;
query_ = uri_parts.length(11) ? Span_t(uri_parts.position(11), uri_parts.length(11)) : zero_span_;
fragment_ = uri_parts.length(12) ? Span_t(uri_parts.position(12), uri_parts.length(12)) : zero_span_;
}
}
///////////////////////////////////////////////////////////////////////////////
std::ostream& uri::operator<< (std::ostream& out, const URI& uri) {
out << uri.to_string();
return out;
}
<|endoftext|>
|
<commit_before>/*
* This program is just for personal experiments here on AVR features and C++ stuff
* This one is a proof of concept on I2C asynchronous handling specificaloly for
* ATtiny architecture.
* As a matter of fact, ATtiny USI feature is not very well suited for asynchronous
* I2C handling as I2C master (this is easier for slaves).
* This PoC will try to demonstrate working with DS1307 RTC chip from an ATtiny84 MCU,
* using Timer0 as clock source for USI SCL clock.
*/
#include <util/delay_basic.h>
#include <fastarduino/boards/board.h>
#include <fastarduino/i2c.h>
#include <fastarduino/queue.h>
#include <fastarduino/time.h>
#include <fastarduino/interrupts.h>
#include <fastarduino/bits.h>
#include <fastarduino/utilities.h>
#include <fastarduino/iomanip.h>
#ifdef ARDUINO_UNO
#define HARD_UART
#include <fastarduino/uart.h>
static constexpr const board::USART UART = board::USART::USART0;
static constexpr const uint8_t OUTPUT_BUFFER_SIZE = 128;
static constexpr uint8_t I2C_BUFFER_SIZE = 32;
static constexpr uint8_t MAX_FUTURES = 128;
static i2c::I2CCommand i2c_buffer[I2C_BUFFER_SIZE];
// Define vectors we need in the example
REGISTER_UATX_ISR(0)
#elif defined (BREADBOARD_ATTINYX4)
#include <fastarduino/soft_uart.h>
static constexpr const board::DigitalPin TX = board::DigitalPin::D8_PB0;
static constexpr const uint8_t OUTPUT_BUFFER_SIZE = 64;
static constexpr uint8_t MAX_FUTURES = 8;
#else
#error "Current target is not yet supported!"
#endif
#include "i2c_handler.h"
#include "ds1307.h"
// Setup debugging stuff
// #define DEBUG_STEPS
// #define DEBUG_SEND_OK
// #define DEBUG_SEND_ERR
// #define DEBUG_RECV_OK
// #define DEBUG_RECV_ERR
#include "debug.h"
#if defined(DEBUG_STEPS) || defined(DEBUG_SEND_OK) || defined(DEBUG_SEND_ERR) || defined(DEBUG_RECV_OK) || defined(DEBUG_RECV_ERR)
#define DEBUG_STATUS
#endif
// This is used when nothing works at all and this reduces the tests to only once get_ram() call
#define BASIC_DEBUG
// Actual test example
//=====================
#ifdef TWCR
REGISTER_I2C_ISR(i2c::I2CMode::STANDARD)
#endif
// Add utility ostream manipulator for FutureStatus
static const flash::FlashStorage* convert(future::FutureStatus s)
{
switch (s)
{
case future::FutureStatus::INVALID:
return F("INVALID");
case future::FutureStatus::NOT_READY:
return F("NOT_READY");
case future::FutureStatus::READY:
return F("READY");
case future::FutureStatus::ERROR:
return F("ERROR");
}
}
streams::ostream& operator<<(streams::ostream& out, future::FutureStatus s)
{
return out << convert(s);
}
void trace(streams::ostream& out)
{
#ifdef DEBUG_STATUS
trace_states(out);
#endif
}
static char output_buffer[OUTPUT_BUFFER_SIZE];
using I2CHANDLER = i2c::I2CHandler<i2c::I2CMode::STANDARD>;
using namespace streams;
ostream* pout = nullptr;
#define OUT (*pout)
static void i2c_hook(i2c::DebugStatus status, uint8_t data)
{
switch (status)
{
case i2c::DebugStatus::START:
OUT << F("St ") << flush;
break;
case i2c::DebugStatus::REPEAT_START:
OUT << F("RS ") << flush;
break;
case i2c::DebugStatus::STOP:
OUT << F("Sp ") << flush;
break;
case i2c::DebugStatus::SLAW:
OUT << F("AW ") << hex << data << ' ' << flush;
break;
case i2c::DebugStatus::SLAR:
OUT << F("AR ") << hex << data << ' ' << flush;
break;
case i2c::DebugStatus::SEND:
OUT << F("S ") << hex << data << ' ' << flush;
break;
case i2c::DebugStatus::SEND_OK:
OUT << F("So ") << flush;
break;
case i2c::DebugStatus::SEND_ERROR:
OUT << F("Se ") << flush;
break;
case i2c::DebugStatus::RECV:
OUT << F("R ") << flush;
break;
case i2c::DebugStatus::RECV_LAST:
OUT << F("RL ") << flush;
break;
case i2c::DebugStatus::RECV_OK:
OUT << F("Ro ") << flush;
break;
case i2c::DebugStatus::RECV_ERROR:
OUT << F("Re ") << flush;
break;
}
}
//TODO add call hook
int main() __attribute__((OS_main));
int main()
{
board::init();
// Enable interrupts at startup time
sei();
// Initialize debugging output
#ifdef HARD_UART
serial::hard::UATX<UART> uatx{output_buffer};
#else
serial::soft::UATX<TX> uatx{output_buffer};
#endif
// Start UART
uatx.begin(115200);
ostream out = uatx.out();
pout = &out;
out << F("Starting...") << endl;
// Initialize FutureManager
future::FutureManager<MAX_FUTURES> future_manager;
// Initialize I2C async handler
#ifdef TWCR
I2CHANDLER handler{i2c_buffer, i2c::I2CErrorPolicy::CLEAR_ALL_COMMANDS, debug_hook};
#else
I2CHANDLER handler{i2c::I2CErrorPolicy::CLEAR_ALL_COMMANDS, i2c_hook};
#endif
RTC rtc{handler};
out << F("Before handler.begin()") << endl;
out << boolalpha << showbase;
handler.begin();
constexpr uint8_t RAM_SIZE = rtc.ram_size();
#ifdef BASIC_DEBUG
// INITIAL debug test with only one call, normally not part of complete unit tests
{
out << F("\nTEST #0 read one RAM byte") << endl;
RTC::GET_RAM1 data{0};
int ok = rtc.get_ram(data);
out << F("get_ram()=") << dec << ok << endl;
out << F("handler.status()=") << hex << handler.status() << endl;
uint8_t id = data.id();
future::FutureStatus status = data.status();
out << F("id=") << dec << id << F(" status=") << status << endl;
// out << F("id=") << dec << data.id() << F(" status=") << data.status() << endl;
// time::delay_ms(1000);
out << F("data await()=") << data.await() << endl;
out << F("error()=") << dec << data.error() << endl;
uint8_t result = 0;
data.get(result);
out << F("get()=") << hex << result << endl;
trace(out);
}
#else
{
out << F("\nTEST #0 read all RAM bytes, one by one") << endl;
RTC::GET_RAM1 data[10];
for (uint8_t i = 0; i < 10; ++i)
{
data[i] = RTC::GET_RAM1{i};
int error = rtc.get_ram(data[i]);
if (error)
out << F("F") << dec << i << F(" ") << flush;
// This delay is needed to give time to I2C transactions to finish
// and free I2C commands in buffer (only 32)
time::delay_us(200);
}
out << endl;
for (uint8_t i = 0 ; i < 10; ++i)
{
out << F("data[") << dec << i << F("] await()=") << data[i].await() << endl;
out << F("error()=") << dec << data[i].error() << endl;
uint8_t result = 0;
data[i].get(result);
out << F("get()=") << hex << result << endl;
}
trace(out);
}
#endif
handler.end();
}
<commit_msg>Remove obsolete comment<commit_after>/*
* This program is just for personal experiments here on AVR features and C++ stuff
* This one is a proof of concept on I2C asynchronous handling specificaloly for
* ATtiny architecture.
* As a matter of fact, ATtiny USI feature is not very well suited for asynchronous
* I2C handling as I2C master (this is easier for slaves).
* This PoC will try to demonstrate working with DS1307 RTC chip from an ATtiny84 MCU,
* using Timer0 as clock source for USI SCL clock.
*/
#include <util/delay_basic.h>
#include <fastarduino/boards/board.h>
#include <fastarduino/i2c.h>
#include <fastarduino/queue.h>
#include <fastarduino/time.h>
#include <fastarduino/interrupts.h>
#include <fastarduino/bits.h>
#include <fastarduino/utilities.h>
#include <fastarduino/iomanip.h>
#ifdef ARDUINO_UNO
#define HARD_UART
#include <fastarduino/uart.h>
static constexpr const board::USART UART = board::USART::USART0;
static constexpr const uint8_t OUTPUT_BUFFER_SIZE = 128;
static constexpr uint8_t I2C_BUFFER_SIZE = 32;
static constexpr uint8_t MAX_FUTURES = 128;
static i2c::I2CCommand i2c_buffer[I2C_BUFFER_SIZE];
// Define vectors we need in the example
REGISTER_UATX_ISR(0)
#elif defined (BREADBOARD_ATTINYX4)
#include <fastarduino/soft_uart.h>
static constexpr const board::DigitalPin TX = board::DigitalPin::D8_PB0;
static constexpr const uint8_t OUTPUT_BUFFER_SIZE = 64;
static constexpr uint8_t MAX_FUTURES = 8;
#else
#error "Current target is not yet supported!"
#endif
#include "i2c_handler.h"
#include "ds1307.h"
// Setup debugging stuff
// #define DEBUG_STEPS
// #define DEBUG_SEND_OK
// #define DEBUG_SEND_ERR
// #define DEBUG_RECV_OK
// #define DEBUG_RECV_ERR
#include "debug.h"
#if defined(DEBUG_STEPS) || defined(DEBUG_SEND_OK) || defined(DEBUG_SEND_ERR) || defined(DEBUG_RECV_OK) || defined(DEBUG_RECV_ERR)
#define DEBUG_STATUS
#endif
// This is used when nothing works at all and this reduces the tests to only once get_ram() call
#define BASIC_DEBUG
// Actual test example
//=====================
#ifdef TWCR
REGISTER_I2C_ISR(i2c::I2CMode::STANDARD)
#endif
// Add utility ostream manipulator for FutureStatus
static const flash::FlashStorage* convert(future::FutureStatus s)
{
switch (s)
{
case future::FutureStatus::INVALID:
return F("INVALID");
case future::FutureStatus::NOT_READY:
return F("NOT_READY");
case future::FutureStatus::READY:
return F("READY");
case future::FutureStatus::ERROR:
return F("ERROR");
}
}
streams::ostream& operator<<(streams::ostream& out, future::FutureStatus s)
{
return out << convert(s);
}
void trace(streams::ostream& out)
{
#ifdef DEBUG_STATUS
trace_states(out);
#endif
}
static char output_buffer[OUTPUT_BUFFER_SIZE];
using I2CHANDLER = i2c::I2CHandler<i2c::I2CMode::STANDARD>;
using namespace streams;
ostream* pout = nullptr;
#define OUT (*pout)
static void i2c_hook(i2c::DebugStatus status, uint8_t data)
{
switch (status)
{
case i2c::DebugStatus::START:
OUT << F("St ") << flush;
break;
case i2c::DebugStatus::REPEAT_START:
OUT << F("RS ") << flush;
break;
case i2c::DebugStatus::STOP:
OUT << F("Sp ") << flush;
break;
case i2c::DebugStatus::SLAW:
OUT << F("AW ") << hex << data << ' ' << flush;
break;
case i2c::DebugStatus::SLAR:
OUT << F("AR ") << hex << data << ' ' << flush;
break;
case i2c::DebugStatus::SEND:
OUT << F("S ") << hex << data << ' ' << flush;
break;
case i2c::DebugStatus::SEND_OK:
OUT << F("So ") << flush;
break;
case i2c::DebugStatus::SEND_ERROR:
OUT << F("Se ") << flush;
break;
case i2c::DebugStatus::RECV:
OUT << F("R ") << flush;
break;
case i2c::DebugStatus::RECV_LAST:
OUT << F("RL ") << flush;
break;
case i2c::DebugStatus::RECV_OK:
OUT << F("Ro ") << flush;
break;
case i2c::DebugStatus::RECV_ERROR:
OUT << F("Re ") << flush;
break;
}
}
int main() __attribute__((OS_main));
int main()
{
board::init();
// Enable interrupts at startup time
sei();
// Initialize debugging output
#ifdef HARD_UART
serial::hard::UATX<UART> uatx{output_buffer};
#else
serial::soft::UATX<TX> uatx{output_buffer};
#endif
// Start UART
uatx.begin(115200);
ostream out = uatx.out();
pout = &out;
out << F("Starting...") << endl;
// Initialize FutureManager
future::FutureManager<MAX_FUTURES> future_manager;
// Initialize I2C async handler
#ifdef TWCR
I2CHANDLER handler{i2c_buffer, i2c::I2CErrorPolicy::CLEAR_ALL_COMMANDS, debug_hook};
#else
I2CHANDLER handler{i2c::I2CErrorPolicy::CLEAR_ALL_COMMANDS, i2c_hook};
#endif
RTC rtc{handler};
out << F("Before handler.begin()") << endl;
out << boolalpha << showbase;
handler.begin();
constexpr uint8_t RAM_SIZE = rtc.ram_size();
#ifdef BASIC_DEBUG
// INITIAL debug test with only one call, normally not part of complete unit tests
{
out << F("\nTEST #0 read one RAM byte") << endl;
RTC::GET_RAM1 data{0};
int ok = rtc.get_ram(data);
out << F("get_ram()=") << dec << ok << endl;
out << F("handler.status()=") << hex << handler.status() << endl;
uint8_t id = data.id();
future::FutureStatus status = data.status();
out << F("id=") << dec << id << F(" status=") << status << endl;
// out << F("id=") << dec << data.id() << F(" status=") << data.status() << endl;
// time::delay_ms(1000);
out << F("data await()=") << data.await() << endl;
out << F("error()=") << dec << data.error() << endl;
uint8_t result = 0;
data.get(result);
out << F("get()=") << hex << result << endl;
trace(out);
}
#else
{
out << F("\nTEST #0 read all RAM bytes, one by one") << endl;
RTC::GET_RAM1 data[10];
for (uint8_t i = 0; i < 10; ++i)
{
data[i] = RTC::GET_RAM1{i};
int error = rtc.get_ram(data[i]);
if (error)
out << F("F") << dec << i << F(" ") << flush;
// This delay is needed to give time to I2C transactions to finish
// and free I2C commands in buffer (only 32)
time::delay_us(200);
}
out << endl;
for (uint8_t i = 0 ; i < 10; ++i)
{
out << F("data[") << dec << i << F("] await()=") << data[i].await() << endl;
out << F("error()=") << dec << data[i].error() << endl;
uint8_t result = 0;
data[i].get(result);
out << F("get()=") << hex << result << endl;
}
trace(out);
}
#endif
handler.end();
}
<|endoftext|>
|
<commit_before>// Message.cpp
// Implements the Message class.
#include "Message.h"
#include "CycException.h"
#include "Communicator.h"
#include "FacilityModel.h"
#include "MarketModel.h"
#include "InstModel.h"
#include "GenericResource.h"
#include "Logger.h"
#include "BookKeeper.h"
#include <iostream>
// initialize static variables
int Message::nextID_ = 1;
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Message::Message(Communicator* sender) {
dir_ = UP_MSG;
sender_ = sender;
recipient_ = NULL;
path_stack_ = vector<Communicator*>();
current_owner_ = sender;
trans_.supplier = NULL;
trans_.requester = NULL;
trans_.is_offer = NULL;
trans_.resource = NULL;
trans_.minfrac = 0;
trans_.price = 0;
setRealParticipant(sender);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Message::Message(Communicator* sender, Communicator* receiver) {
dir_ = UP_MSG;
sender_ = sender;
recipient_ = receiver;
trans_.supplier = NULL;
trans_.requester = NULL;
trans_.is_offer = NULL;
trans_.resource = NULL;
trans_.minfrac = 0;
trans_.price = 0;
setRealParticipant(sender);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Message::Message(Communicator* sender, Communicator* receiver,
Transaction thisTrans) {
dir_ = UP_MSG;
trans_ = thisTrans;
sender_ = sender;
recipient_ = receiver;
setResource(thisTrans.resource);
if (trans_.is_offer) {
// if this message is an offer, the sender is the supplier
setSupplier(dynamic_cast<Model*>(sender_));
} else if (!trans_.is_offer) {
// if this message is a request, the sender is the requester
setRequester(dynamic_cast<Model*>(sender_));
}
setRealParticipant(sender);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Message::setRealParticipant(Communicator* who) {
try {
dynamic_cast<Model*>(who)->isTemplate() = false;
} catch(...) {
}
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Message::printTrans() {
std::cout << "Transaction info (via Message):" << std::endl <<
" Transaction ID: " << trans_.ID << std::endl <<
" Requester ID: " << trans_.requester->ID() << std::endl <<
" Supplier ID: " << trans_.supplier->ID() << std::endl <<
" Price: " << trans_.price << std::endl;
};
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Message* Message::clone() {
Message* new_msg = new Message(*this);
new_msg->setResource(getResource());
return new_msg;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Message::sendOn() {
validateForSend();
if (dir_ == DOWN_MSG) {
path_stack_.pop_back();
}
Communicator* next_stop = path_stack_.back();
setRealParticipant(next_stop);
current_owner_ = next_stop;
next_stop->receiveMessage(this);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Message::validateForSend() {
int next_stop_index = -1;
bool receiver_specified = false;
Communicator* next_stop;
if (dir_ == UP_MSG) {
receiver_specified = (path_stack_.size() > 0);
next_stop_index = path_stack_.size() - 1;
} else if (dir_ == DOWN_MSG) {
receiver_specified = (path_stack_.size() > 1);
next_stop_index = path_stack_.size() - 2;
}
if (!receiver_specified) {
string err_msg = "Can't send the message: next dest is unspecified.";
throw CycMessageException(err_msg);
}
next_stop = path_stack_[next_stop_index];
if (next_stop == current_owner_) {
string err_msg = "Message receiver and sender are the same.";
throw CycMessageException(err_msg);
}
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Message::setNextDest(Communicator* next_stop) {
if (dir_ == UP_MSG) {
if (path_stack_.size() == 0) {
path_stack_.push_back(sender_);
}
path_stack_.push_back(next_stop);
}
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Message::reverseDirection() {
if (DOWN_MSG == dir_) {
dir_ = UP_MSG;
} else {
dir_ = DOWN_MSG;
}
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
MessageDir Message::getDir() const {
return dir_;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Message::setDir(MessageDir newDir) {
dir_ = newDir;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Communicator* Message::getMarket() {
MarketModel* market = MarketModel::marketForCommod(trans_.commod);
return dynamic_cast<Communicator*>(market);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Communicator* Message::getRecipient() const {
if (recipient_ == NULL) {
string err_msg = "Uninitilized message recipient.";
throw CycMessageException(err_msg);
}
return recipient_;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Model* Message::getSupplier() const {
if (trans_.supplier == NULL) {
string err_msg = "Uninitilized message supplier.";
throw CycMessageException(err_msg);
}
return trans_.supplier;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Model* Message::getRequester() const {
if (trans_.requester == NULL) {
string err_msg = "Uninitilized message requester.";
throw CycMessageException(err_msg);
}
return trans_.requester;
}
void Message::approveTransfer() {
Model* requester = getRequester();
Model* supplier = getSupplier();
vector<Resource*> manifest = supplier->removeResource(this);
requester->addResource(getTrans(), manifest);
BI->registerTrans(this, manifest);
for (int i = 0; i < manifest.size(); i++) {
try {
BI->registerMatState(getTrans().ID, dynamic_cast<Material*>(manifest.at(i)));
} catch (...) {}
}
LOG(LEV_DEBUG2) << "Material sent from " << supplier->ID() << " to "
<< requester->ID() << ".";
}
<commit_msg>fixed bug introduced in r636 that caused segfault in message class tests.<commit_after>// Message.cpp
// Implements the Message class.
#include "Message.h"
#include "CycException.h"
#include "Communicator.h"
#include "FacilityModel.h"
#include "MarketModel.h"
#include "InstModel.h"
#include "GenericResource.h"
#include "Logger.h"
#include "BookKeeper.h"
#include <iostream>
// initialize static variables
int Message::nextID_ = 1;
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Message::Message(Communicator* sender) {
dir_ = UP_MSG;
sender_ = sender;
recipient_ = NULL;
path_stack_ = vector<Communicator*>();
current_owner_ = sender;
trans_.supplier = NULL;
trans_.requester = NULL;
trans_.is_offer = NULL;
trans_.resource = NULL;
trans_.minfrac = 0;
trans_.price = 0;
setRealParticipant(sender);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Message::Message(Communicator* sender, Communicator* receiver) {
dir_ = UP_MSG;
sender_ = sender;
recipient_ = receiver;
trans_.supplier = NULL;
trans_.requester = NULL;
trans_.is_offer = NULL;
trans_.resource = NULL;
trans_.minfrac = 0;
trans_.price = 0;
setRealParticipant(sender);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Message::Message(Communicator* sender, Communicator* receiver,
Transaction thisTrans) {
dir_ = UP_MSG;
trans_ = thisTrans;
sender_ = sender;
recipient_ = receiver;
setResource(thisTrans.resource);
if (trans_.is_offer) {
// if this message is an offer, the sender is the supplier
setSupplier(dynamic_cast<Model*>(sender_));
} else if (!trans_.is_offer) {
// if this message is a request, the sender is the requester
setRequester(dynamic_cast<Model*>(sender_));
}
setRealParticipant(sender);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Message::setRealParticipant(Communicator* who) {
Model* model = NULL;
model = dynamic_cast<Model*>(who);
if (model != NULL) {model->isTemplate() = false;}
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Message::printTrans() {
std::cout << "Transaction info (via Message):" << std::endl <<
" Transaction ID: " << trans_.ID << std::endl <<
" Requester ID: " << trans_.requester->ID() << std::endl <<
" Supplier ID: " << trans_.supplier->ID() << std::endl <<
" Price: " << trans_.price << std::endl;
};
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Message* Message::clone() {
Message* new_msg = new Message(*this);
new_msg->setResource(getResource());
return new_msg;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Message::sendOn() {
validateForSend();
if (dir_ == DOWN_MSG) {
path_stack_.pop_back();
}
Communicator* next_stop = path_stack_.back();
setRealParticipant(next_stop);
current_owner_ = next_stop;
next_stop->receiveMessage(this);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Message::validateForSend() {
int next_stop_index = -1;
bool receiver_specified = false;
Communicator* next_stop;
if (dir_ == UP_MSG) {
receiver_specified = (path_stack_.size() > 0);
next_stop_index = path_stack_.size() - 1;
} else if (dir_ == DOWN_MSG) {
receiver_specified = (path_stack_.size() > 1);
next_stop_index = path_stack_.size() - 2;
}
if (!receiver_specified) {
string err_msg = "Can't send the message: next dest is unspecified.";
throw CycMessageException(err_msg);
}
next_stop = path_stack_[next_stop_index];
if (next_stop == current_owner_) {
string err_msg = "Message receiver and sender are the same.";
throw CycMessageException(err_msg);
}
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Message::setNextDest(Communicator* next_stop) {
if (dir_ == UP_MSG) {
if (path_stack_.size() == 0) {
path_stack_.push_back(sender_);
}
path_stack_.push_back(next_stop);
}
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Message::reverseDirection() {
if (DOWN_MSG == dir_) {
dir_ = UP_MSG;
} else {
dir_ = DOWN_MSG;
}
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
MessageDir Message::getDir() const {
return dir_;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Message::setDir(MessageDir newDir) {
dir_ = newDir;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Communicator* Message::getMarket() {
MarketModel* market = MarketModel::marketForCommod(trans_.commod);
return dynamic_cast<Communicator*>(market);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Communicator* Message::getRecipient() const {
if (recipient_ == NULL) {
string err_msg = "Uninitilized message recipient.";
throw CycMessageException(err_msg);
}
return recipient_;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Model* Message::getSupplier() const {
if (trans_.supplier == NULL) {
string err_msg = "Uninitilized message supplier.";
throw CycMessageException(err_msg);
}
return trans_.supplier;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Model* Message::getRequester() const {
if (trans_.requester == NULL) {
string err_msg = "Uninitilized message requester.";
throw CycMessageException(err_msg);
}
return trans_.requester;
}
void Message::approveTransfer() {
Model* requester = getRequester();
Model* supplier = getSupplier();
vector<Resource*> manifest = supplier->removeResource(this);
requester->addResource(getTrans(), manifest);
BI->registerTrans(this, manifest);
for (int i = 0; i < manifest.size(); i++) {
try {
BI->registerMatState(getTrans().ID, dynamic_cast<Material*>(manifest.at(i)));
} catch (...) {}
}
LOG(LEV_DEBUG2) << "Material sent from " << supplier->ID() << " to "
<< requester->ID() << ".";
}
<|endoftext|>
|
<commit_before>//===- GdbIndex.cpp -------------------------------------------------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// The -gdb-index option instructs the linker to emit a .gdb_index section.
// The section contains information to make gdb startup faster.
// The format of the section is described at
// https://sourceware.org/gdb/onlinedocs/gdb/Index-Section-Format.html.
//
//===----------------------------------------------------------------------===//
#include "GdbIndex.h"
#include "Memory.h"
#include "llvm/DebugInfo/DWARF/DWARFDebugPubTable.h"
#include "llvm/Object/ELFObjectFile.h"
using namespace llvm;
using namespace llvm::object;
using namespace lld;
using namespace lld::elf;
std::pair<bool, GdbSymbol *> GdbHashTab::add(uint32_t Hash, size_t Offset) {
GdbSymbol *&Sym = Map[Offset];
if (Sym)
return {false, Sym};
Sym = make<GdbSymbol>(Hash, Offset);
return {true, Sym};
}
void GdbHashTab::finalizeContents() {
uint32_t Size = std::max<uint32_t>(1024, NextPowerOf2(Map.size() * 4 / 3));
uint32_t Mask = Size - 1;
Table.resize(Size);
for (auto &P : Map) {
GdbSymbol *Sym = P.second;
uint32_t I = Sym->NameHash & Mask;
uint32_t Step = ((Sym->NameHash * 17) & Mask) | 1;
while (Table[I])
I = (I + Step) & Mask;
Table[I] = Sym;
}
}
template <class ELFT>
LLDDwarfObj<ELFT>::LLDDwarfObj(ObjFile<ELFT> *Obj) : Obj(Obj) {
for (InputSectionBase *Sec : Obj->getSections()) {
if (!Sec)
continue;
if (LLDDWARFSection *M = StringSwitch<LLDDWARFSection *>(Sec->Name)
.Case(".debug_info", &InfoSection)
.Case(".debug_ranges", &RangeSection)
.Case(".debug_line", &LineSection)
.Default(nullptr)) {
M->Data = toStringRef(Sec->Data);
M->Sec = Sec;
continue;
}
if (Sec->Name == ".debug_abbrev")
AbbrevSection = toStringRef(Sec->Data);
else if (Sec->Name == ".debug_gnu_pubnames")
GnuPubNamesSection = toStringRef(Sec->Data);
else if (Sec->Name == ".debug_gnu_pubtypes")
GnuPubTypesSection = toStringRef(Sec->Data);
}
}
// Find if there is a relocation at Pos in Sec. The code is a bit
// more complicated than usual because we need to pass a section index
// to llvm since it has no idea about InputSection.
template <class ELFT>
template <class RelTy>
Optional<RelocAddrEntry>
LLDDwarfObj<ELFT>::findAux(const InputSectionBase &Sec, uint64_t Pos,
ArrayRef<RelTy> Rels) const {
auto I = llvm::find_if(Rels,
[=](const RelTy &Rel) { return Rel.r_offset == Pos; });
if (I == Rels.end())
return None;
const RelTy &Rel = *I;
const ObjFile<ELFT> *File = Sec.getFile<ELFT>();
uint32_t SymIndex = Rel.getSymbol(Config->IsMips64EL);
const typename ELFT::Sym &Sym = File->getELFSymbols()[SymIndex];
uint32_t SecIndex = File->getSectionIndex(Sym);
SymbolBody &B = File->getRelocTargetSym(Rel);
auto &DR = cast<DefinedRegular>(B);
uint64_t Val = DR.Value + getAddend<ELFT>(Rel);
// FIXME: We should be consistent about always adding the file
// offset or not.
if (DR.Section->Flags & ELF::SHF_ALLOC)
Val += cast<InputSection>(DR.Section)->getOffsetInFile();
RelocAddrEntry Ret{SecIndex, Val};
return Ret;
}
template <class ELFT>
Optional<RelocAddrEntry> LLDDwarfObj<ELFT>::find(const llvm::DWARFSection &S,
uint64_t Pos) const {
auto &Sec = static_cast<const LLDDWARFSection &>(S);
if (Sec.Sec->AreRelocsRela)
return findAux(*Sec.Sec, Pos, Sec.Sec->template relas<ELFT>());
return findAux(*Sec.Sec, Pos, Sec.Sec->template rels<ELFT>());
}
template class elf::LLDDwarfObj<ELF32LE>;
template class elf::LLDDwarfObj<ELF32BE>;
template class elf::LLDDwarfObj<ELF64LE>;
template class elf::LLDDwarfObj<ELF64BE>;
<commit_msg>Binary search to find a relocation.<commit_after>//===- GdbIndex.cpp -------------------------------------------------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// The -gdb-index option instructs the linker to emit a .gdb_index section.
// The section contains information to make gdb startup faster.
// The format of the section is described at
// https://sourceware.org/gdb/onlinedocs/gdb/Index-Section-Format.html.
//
//===----------------------------------------------------------------------===//
#include "GdbIndex.h"
#include "Memory.h"
#include "llvm/DebugInfo/DWARF/DWARFDebugPubTable.h"
#include "llvm/Object/ELFObjectFile.h"
using namespace llvm;
using namespace llvm::object;
using namespace lld;
using namespace lld::elf;
std::pair<bool, GdbSymbol *> GdbHashTab::add(uint32_t Hash, size_t Offset) {
GdbSymbol *&Sym = Map[Offset];
if (Sym)
return {false, Sym};
Sym = make<GdbSymbol>(Hash, Offset);
return {true, Sym};
}
void GdbHashTab::finalizeContents() {
uint32_t Size = std::max<uint32_t>(1024, NextPowerOf2(Map.size() * 4 / 3));
uint32_t Mask = Size - 1;
Table.resize(Size);
for (auto &P : Map) {
GdbSymbol *Sym = P.second;
uint32_t I = Sym->NameHash & Mask;
uint32_t Step = ((Sym->NameHash * 17) & Mask) | 1;
while (Table[I])
I = (I + Step) & Mask;
Table[I] = Sym;
}
}
template <class ELFT>
LLDDwarfObj<ELFT>::LLDDwarfObj(ObjFile<ELFT> *Obj) : Obj(Obj) {
for (InputSectionBase *Sec : Obj->getSections()) {
if (!Sec)
continue;
if (LLDDWARFSection *M = StringSwitch<LLDDWARFSection *>(Sec->Name)
.Case(".debug_info", &InfoSection)
.Case(".debug_ranges", &RangeSection)
.Case(".debug_line", &LineSection)
.Default(nullptr)) {
M->Data = toStringRef(Sec->Data);
M->Sec = Sec;
continue;
}
if (Sec->Name == ".debug_abbrev")
AbbrevSection = toStringRef(Sec->Data);
else if (Sec->Name == ".debug_gnu_pubnames")
GnuPubNamesSection = toStringRef(Sec->Data);
else if (Sec->Name == ".debug_gnu_pubtypes")
GnuPubTypesSection = toStringRef(Sec->Data);
}
}
// Find if there is a relocation at Pos in Sec. The code is a bit
// more complicated than usual because we need to pass a section index
// to llvm since it has no idea about InputSection.
template <class ELFT>
template <class RelTy>
Optional<RelocAddrEntry>
LLDDwarfObj<ELFT>::findAux(const InputSectionBase &Sec, uint64_t Pos,
ArrayRef<RelTy> Rels) const {
auto It = std::lower_bound(
Rels.begin(), Rels.end(), Pos,
[](const RelTy &A, uint64_t B) { return A.r_offset < B; });
if (It == Rels.end() || It->r_offset != Pos)
return None;
const RelTy &Rel = *It;
const ObjFile<ELFT> *File = Sec.getFile<ELFT>();
uint32_t SymIndex = Rel.getSymbol(Config->IsMips64EL);
const typename ELFT::Sym &Sym = File->getELFSymbols()[SymIndex];
uint32_t SecIndex = File->getSectionIndex(Sym);
SymbolBody &B = File->getRelocTargetSym(Rel);
auto &DR = cast<DefinedRegular>(B);
uint64_t Val = DR.Value + getAddend<ELFT>(Rel);
// FIXME: We should be consistent about always adding the file
// offset or not.
if (DR.Section->Flags & ELF::SHF_ALLOC)
Val += cast<InputSection>(DR.Section)->getOffsetInFile();
RelocAddrEntry Ret{SecIndex, Val};
return Ret;
}
template <class ELFT>
Optional<RelocAddrEntry> LLDDwarfObj<ELFT>::find(const llvm::DWARFSection &S,
uint64_t Pos) const {
auto &Sec = static_cast<const LLDDWARFSection &>(S);
if (Sec.Sec->AreRelocsRela)
return findAux(*Sec.Sec, Pos, Sec.Sec->template relas<ELFT>());
return findAux(*Sec.Sec, Pos, Sec.Sec->template rels<ELFT>());
}
template class elf::LLDDwarfObj<ELF32LE>;
template class elf::LLDDwarfObj<ELF32BE>;
template class elf::LLDDwarfObj<ELF64LE>;
template class elf::LLDDwarfObj<ELF64BE>;
<|endoftext|>
|
<commit_before>#include "Input.h"
#include <SDL/SDL.h>
#include <SDL/SDL_OpenGL.h>
#include <queue>
namespace Input
{
namespace Internal
{
std::string MapKey ( SDLKey k )
{
switch (k)
{
#define KEYCASE(sym, string) case SDLK_ ## sym: return string
#define DIRECTCASE(sym) KEYCASE(sym, #sym)
DIRECTCASE(a);
DIRECTCASE(b);
DIRECTCASE(c);
DIRECTCASE(d);
DIRECTCASE(e);
DIRECTCASE(f);
DIRECTCASE(g);
DIRECTCASE(h);
DIRECTCASE(i);
DIRECTCASE(j);
DIRECTCASE(k);
DIRECTCASE(l);
DIRECTCASE(m);
DIRECTCASE(n);
DIRECTCASE(o);
DIRECTCASE(p);
DIRECTCASE(q);
DIRECTCASE(r);
DIRECTCASE(s);
DIRECTCASE(t);
DIRECTCASE(u);
DIRECTCASE(v);
DIRECTCASE(w);
DIRECTCASE(x);
DIRECTCASE(y);
DIRECTCASE(z);
DIRECTCASE(0);
DIRECTCASE(1);
DIRECTCASE(2);
DIRECTCASE(3);
DIRECTCASE(4);
DIRECTCASE(5);
DIRECTCASE(6);
DIRECTCASE(7);
DIRECTCASE(8);
DIRECTCASE(9);
DIRECTCASE(F1);
DIRECTCASE(F2);
DIRECTCASE(F3);
DIRECTCASE(F4);
DIRECTCASE(F5);
DIRECTCASE(F6);
DIRECTCASE(F7);
DIRECTCASE(F8);
DIRECTCASE(F9);
DIRECTCASE(F10);
DIRECTCASE(F11);
DIRECTCASE(F12);
DIRECTCASE(KP0);
DIRECTCASE(KP1);
DIRECTCASE(KP2);
DIRECTCASE(KP3);
DIRECTCASE(KP4);
DIRECTCASE(KP5);
DIRECTCASE(KP6);
DIRECTCASE(KP7);
DIRECTCASE(KP8);
DIRECTCASE(KP9);
KEYCASE(BACKSPACE, "backspace");
KEYCASE(TAB, "tab");
KEYCASE(RETURN, "return");
KEYCASE(ESCAPE, "escape");
KEYCASE(SPACE, " ");
KEYCASE(QUOTE, "\'");
KEYCASE(LEFTPAREN, "(");
KEYCASE(RIGHTPAREN, ")");
KEYCASE(ASTERISK, "*");
KEYCASE(PLUS, "+");
KEYCASE(COMMA, ",");
KEYCASE(MINUS, "-");
KEYCASE(PERIOD, ".");
KEYCASE(SLASH, "/");
KEYCASE(COLON, ":");
KEYCASE(SEMICOLON, ";");
KEYCASE(AT, "at_sign");
KEYCASE(LESS, "<");
KEYCASE(EQUALS, "=");
KEYCASE(GREATER, ">");
KEYCASE(QUESTION, "?");
KEYCASE(LEFTBRACKET, "[");
KEYCASE(RIGHTBRACKET, "]");
KEYCASE(BACKSLASH, "backslash");
KEYCASE(CARET, "^");
KEYCASE(UNDERSCORE, "_");
KEYCASE(LEFT, "left");
KEYCASE(RIGHT, "right");
KEYCASE(UP, "up");
KEYCASE(DOWN, "down");
KEYCASE(KP_PERIOD, "KPperiod");
KEYCASE(KP_DIVIDE, "KPdivide");
KEYCASE(KP_MULTIPLY, "KPmultiply");
KEYCASE(KP_MINUS, "KPminus");
KEYCASE(KP_PLUS, "KPplus");
KEYCASE(KP_ENTER, "KPenter");
KEYCASE(KP_EQUALS, "KPequals");
KEYCASE(INSERT, "ins");
KEYCASE(HOME, "home");
KEYCASE(END, "end");
KEYCASE(PAGEUP, "pgup");
KEYCASE(PAGEDOWN, "pgdn");
KEYCASE(DELETE, "del");
//modifier keys
KEYCASE(CAPSLOCK, "Mcaps");
KEYCASE(RSHIFT, "MshiftR");
KEYCASE(LSHIFT, "MshiftL");
KEYCASE(RCTRL, "MctrlR");
KEYCASE(LCTRL, "MctrlL");
KEYCASE(RALT, "MaltR");
KEYCASE(LALT, "MaltL");
KEYCASE(RMETA, "MmetaR");
KEYCASE(LMETA, "MmetaL");
}
return "unhandled";
}
std::queue<Event*> events;
Event* currentEvent = NULL;
vec2 mousePosition;
double xdest = 0.0;
double ydest = 0.0;
double zdest = 0.0;
bool lmbPressed = false;
void UpdateMouse ( Sint16 px, Sint16 py )
{
SDL_Surface* screen = SDL_GetVideoSurface();
mousePosition.X() = float(px) / float(screen->w);
mousePosition.Y() = 1.0f - (float(py) / float(screen->h));
}
std::string MouseButtonName ( Uint32 button )
{
switch (button)
{
case SDL_BUTTON_LEFT:
return "left";
break;
case SDL_BUTTON_MIDDLE:
return "middle";
break;
case SDL_BUTTON_RIGHT:
return "right";
break;
}
return "unknown";
}
}
using namespace Internal;
void Pump ()
{
SDL_Event evt;
while (SDL_PollEvent(&evt))
{
switch (evt.type)
{
case SDL_KEYDOWN:
events.push(new Event(Event::KEYDOWN, MapKey(evt.key.keysym.sym), mousePosition));
break;
case SDL_KEYUP:
events.push(new Event(Event::KEYUP, MapKey(evt.key.keysym.sym), mousePosition));
break;
case SDL_QUIT:
events.push(new Event(Event::QUIT, "", mousePosition));
break;
case SDL_MOUSEMOTION:
UpdateMouse(evt.button.x, evt.button.y);
break;
case SDL_MOUSEBUTTONDOWN:
UpdateMouse(evt.button.x, evt.button.y);
events.push(new Event(Event::CLICK, MouseButtonName(evt.button.button), mousePosition));
break;
case SDL_MOUSEBUTTONUP:
UpdateMouse(evt.button.x, evt.button.y);
events.push(new Event(Event::RELEASE, MouseButtonName(evt.button.button), mousePosition));
break;
}
}
}
Event* Next ()
{
if (currentEvent)
delete currentEvent;
if (events.empty())
{
currentEvent = NULL;
return NULL;
}
else
{
currentEvent = events.front();
events.pop();
return currentEvent;
}
}
vec2 MousePosition ()
{
return mousePosition;
}
}
<commit_msg>Created a somewhat kludgy system for zooming with the scroll wheel.<commit_after>#include "Input.h"
#include <SDL/SDL.h>
#include <SDL/SDL_OpenGL.h>
#include <queue>
namespace Input
{
namespace Internal
{
std::string MapKey ( SDLKey k )
{
switch (k)
{
#define KEYCASE(sym, string) case SDLK_ ## sym: return string
#define DIRECTCASE(sym) KEYCASE(sym, #sym)
DIRECTCASE(a);
DIRECTCASE(b);
DIRECTCASE(c);
DIRECTCASE(d);
DIRECTCASE(e);
DIRECTCASE(f);
DIRECTCASE(g);
DIRECTCASE(h);
DIRECTCASE(i);
DIRECTCASE(j);
DIRECTCASE(k);
DIRECTCASE(l);
DIRECTCASE(m);
DIRECTCASE(n);
DIRECTCASE(o);
DIRECTCASE(p);
DIRECTCASE(q);
DIRECTCASE(r);
DIRECTCASE(s);
DIRECTCASE(t);
DIRECTCASE(u);
DIRECTCASE(v);
DIRECTCASE(w);
DIRECTCASE(x);
DIRECTCASE(y);
DIRECTCASE(z);
DIRECTCASE(0);
DIRECTCASE(1);
DIRECTCASE(2);
DIRECTCASE(3);
DIRECTCASE(4);
DIRECTCASE(5);
DIRECTCASE(6);
DIRECTCASE(7);
DIRECTCASE(8);
DIRECTCASE(9);
DIRECTCASE(F1);
DIRECTCASE(F2);
DIRECTCASE(F3);
DIRECTCASE(F4);
DIRECTCASE(F5);
DIRECTCASE(F6);
DIRECTCASE(F7);
DIRECTCASE(F8);
DIRECTCASE(F9);
DIRECTCASE(F10);
DIRECTCASE(F11);
DIRECTCASE(F12);
DIRECTCASE(KP0);
DIRECTCASE(KP1);
DIRECTCASE(KP2);
DIRECTCASE(KP3);
DIRECTCASE(KP4);
DIRECTCASE(KP5);
DIRECTCASE(KP6);
DIRECTCASE(KP7);
DIRECTCASE(KP8);
DIRECTCASE(KP9);
KEYCASE(BACKSPACE, "backspace");
KEYCASE(TAB, "tab");
KEYCASE(RETURN, "return");
KEYCASE(ESCAPE, "escape");
KEYCASE(SPACE, " ");
KEYCASE(QUOTE, "\'");
KEYCASE(LEFTPAREN, "(");
KEYCASE(RIGHTPAREN, ")");
KEYCASE(ASTERISK, "*");
KEYCASE(PLUS, "+");
KEYCASE(COMMA, ",");
KEYCASE(MINUS, "-");
KEYCASE(PERIOD, ".");
KEYCASE(SLASH, "/");
KEYCASE(COLON, ":");
KEYCASE(SEMICOLON, ";");
KEYCASE(AT, "at_sign");
KEYCASE(LESS, "<");
KEYCASE(EQUALS, "=");
KEYCASE(GREATER, ">");
KEYCASE(QUESTION, "?");
KEYCASE(LEFTBRACKET, "[");
KEYCASE(RIGHTBRACKET, "]");
KEYCASE(BACKSLASH, "backslash");
KEYCASE(CARET, "^");
KEYCASE(UNDERSCORE, "_");
KEYCASE(LEFT, "left");
KEYCASE(RIGHT, "right");
KEYCASE(UP, "up");
KEYCASE(DOWN, "down");
KEYCASE(KP_PERIOD, "KPperiod");
KEYCASE(KP_DIVIDE, "KPdivide");
KEYCASE(KP_MULTIPLY, "KPmultiply");
KEYCASE(KP_MINUS, "KPminus");
KEYCASE(KP_PLUS, "KPplus");
KEYCASE(KP_ENTER, "KPenter");
KEYCASE(KP_EQUALS, "KPequals");
KEYCASE(INSERT, "ins");
KEYCASE(HOME, "home");
KEYCASE(END, "end");
KEYCASE(PAGEUP, "pgup");
KEYCASE(PAGEDOWN, "pgdn");
KEYCASE(DELETE, "del");
//modifier keys
KEYCASE(CAPSLOCK, "Mcaps");
KEYCASE(RSHIFT, "MshiftR");
KEYCASE(LSHIFT, "MshiftL");
KEYCASE(RCTRL, "MctrlR");
KEYCASE(LCTRL, "MctrlL");
KEYCASE(RALT, "MaltR");
KEYCASE(LALT, "MaltL");
KEYCASE(RMETA, "MmetaR");
KEYCASE(LMETA, "MmetaL");
}
return "unhandled";
}
std::queue<Event*> events;
Event* currentEvent = NULL;
vec2 mousePosition;
double xdest = 0.0;
double ydest = 0.0;
double zdest = 0.0;
bool lmbPressed = false;
void UpdateMouse ( Sint16 px, Sint16 py )
{
SDL_Surface* screen = SDL_GetVideoSurface();
mousePosition.X() = float(px) / float(screen->w);
mousePosition.Y() = 1.0f - (float(py) / float(screen->h));
}
std::string MouseButtonName ( Uint32 button )
{
switch (button)
{
case SDL_BUTTON_LEFT:
return "left";
break;
case SDL_BUTTON_MIDDLE:
return "middle";
break;
case SDL_BUTTON_RIGHT:
return "right";
break;
case SDL_BUTTON_WHEELDOWN:
return "wheel_down";
break;
case SDL_BUTTON_WHEELUP:
return "wheel_up";
break;
}
return "unknown";
}
}
using namespace Internal;
void Pump ()
{
SDL_Event evt;
while (SDL_PollEvent(&evt))
{
switch (evt.type)
{
case SDL_KEYDOWN:
events.push(new Event(Event::KEYDOWN, MapKey(evt.key.keysym.sym), mousePosition));
break;
case SDL_KEYUP:
events.push(new Event(Event::KEYUP, MapKey(evt.key.keysym.sym), mousePosition));
break;
case SDL_QUIT:
events.push(new Event(Event::QUIT, "", mousePosition));
break;
case SDL_MOUSEMOTION:
UpdateMouse(evt.button.x, evt.button.y);
break;
case SDL_MOUSEBUTTONDOWN:
UpdateMouse(evt.button.x, evt.button.y);
events.push(new Event(Event::CLICK, MouseButtonName(evt.button.button), mousePosition));
break;
case SDL_MOUSEBUTTONUP:
UpdateMouse(evt.button.x, evt.button.y);
events.push(new Event(Event::RELEASE, MouseButtonName(evt.button.button), mousePosition));
break;
}
}
}
Event* Next ()
{
if (currentEvent)
delete currentEvent;
if (events.empty())
{
currentEvent = NULL;
return NULL;
}
else
{
currentEvent = events.front();
events.pop();
return currentEvent;
}
}
vec2 MousePosition ()
{
return mousePosition;
}
}
<|endoftext|>
|
<commit_before>#include <future>
#include <iostream>
#include <cassert>
#include <csignal>
#include <unistd.h>
#include <capnp/message.h>
#include <capnp/serialize-packed.h>
#include "json11.hpp"
#include "cereal/gen/cpp/log.capnp.h"
#include "common/swaglog.h"
#include "common/messaging.h"
#include "common/params.h"
#include "common/timing.h"
#include "messaging.hpp"
#include "locationd_yawrate.h"
#include "params_learner.h"
#include "common/util.h"
void sigpipe_handler(int sig) {
LOGE("SIGPIPE received");
}
int main(int argc, char *argv[]) {
signal(SIGPIPE, (sighandler_t)sigpipe_handler);
Context * c = Context::create();
SubSocket * controls_state_sock = SubSocket::create(c, "controlsState");
SubSocket * sensor_events_sock = SubSocket::create(c, "sensorEvents");
SubSocket * camera_odometry_sock = SubSocket::create(c, "cameraOdometry");
PubSocket * live_parameters_sock = PubSocket::create(c, "liveParameters");
assert(controls_state_sock != NULL);
assert(sensor_events_sock != NULL);
assert(camera_odometry_sock != NULL);
assert(live_parameters_sock != NULL);
Poller * poller = Poller::create({controls_state_sock, sensor_events_sock, camera_odometry_sock});
Localizer localizer;
// Read car params
char *value;
size_t value_sz = 0;
LOGW("waiting for params to set vehicle model");
while (true) {
read_db_value(NULL, "CarParams", &value, &value_sz);
if (value_sz > 0) break;
usleep(100*1000);
}
LOGW("got %d bytes CarParams", value_sz);
// make copy due to alignment issues
auto amsg = kj::heapArray<capnp::word>((value_sz / sizeof(capnp::word)) + 1);
memcpy(amsg.begin(), value, value_sz);
free(value);
capnp::FlatArrayMessageReader cmsg(amsg);
cereal::CarParams::Reader car_params = cmsg.getRoot<cereal::CarParams>();
// Read params from previous run
const int result = read_db_value(NULL, "LiveParameters", &value, &value_sz);
std::string fingerprint = car_params.getCarFingerprint();
std::string vin = car_params.getCarVin();
double sR = car_params.getSteerRatio();
double x = 1.0;
double ao = 0.0;
double posenet_invalid_count = 0;
if (result == 0){
auto str = std::string(value, value_sz);
free(value);
std::string err;
auto json = json11::Json::parse(str, err);
if (json.is_null() || !err.empty()) {
std::string log = "Error parsing json: " + err;
LOGW(log.c_str());
} else {
std::string new_fingerprint = json["carFingerprint"].string_value();
std::string new_vin = json["carVin"].string_value();
if (fingerprint == new_fingerprint && vin == new_vin) {
std::string log = "Parameter starting with: " + str;
LOGW(log.c_str());
sR = json["steerRatio"].number_value();
x = json["stiffnessFactor"].number_value();
ao = json["angleOffsetAverage"].number_value();
}
}
}
ParamsLearner learner(car_params, ao, x, sR, 1.0);
// Main loop
int save_counter = 0;
while (true){
for (auto s : poller->poll(100)){
Message * msg = s->receive();
auto amsg = kj::heapArray<capnp::word>((msg->getSize() / sizeof(capnp::word)) + 1);
memcpy(amsg.begin(), msg->getData(), msg->getSize());
capnp::FlatArrayMessageReader capnp_msg(amsg);
cereal::Event::Reader event = capnp_msg.getRoot<cereal::Event>();
localizer.handle_log(event);
auto which = event.which();
// Throw vision failure if posenet and odometric speed too different
if (which == cereal::Event::CAMERA_ODOMETRY){
if (std::abs(localizer.posenet_speed - localizer.car_speed) > std::max(0.4 * localizer.car_speed, 5.0)) {
posenet_invalid_count++;
} else {
posenet_invalid_count = 0;
}
} else if (which == cereal::Event::CONTROLS_STATE){
save_counter++;
double yaw_rate = -localizer.x[0];
bool valid = learner.update(yaw_rate, localizer.car_speed, localizer.steering_angle);
// TODO: Fix in replay
double sensor_data_age = localizer.controls_state_time - localizer.sensor_data_time;
double camera_odometry_age = localizer.controls_state_time - localizer.camera_odometry_time;
double angle_offset_degrees = RADIANS_TO_DEGREES * learner.ao;
double angle_offset_average_degrees = RADIANS_TO_DEGREES * learner.slow_ao;
capnp::MallocMessageBuilder msg;
cereal::Event::Builder event = msg.initRoot<cereal::Event>();
event.setLogMonoTime(nanos_since_boot());
auto live_params = event.initLiveParameters();
live_params.setValid(valid);
live_params.setYawRate(localizer.x[0]);
live_params.setGyroBias(localizer.x[2]);
live_params.setSensorValid(sensor_data_age < 5.0);
live_params.setAngleOffset(angle_offset_degrees);
live_params.setAngleOffsetAverage(angle_offset_average_degrees);
live_params.setStiffnessFactor(learner.x);
live_params.setSteerRatio(learner.sR);
live_params.setPosenetSpeed(localizer.posenet_speed);
live_params.setPosenetValid((posenet_invalid_count < 4) && (camera_odometry_age < 5.0));
auto words = capnp::messageToFlatArray(msg);
auto bytes = words.asBytes();
live_parameters_sock->send((char*)bytes.begin(), bytes.size());
// Save parameters every minute
if (save_counter % 6000 == 0) {
json11::Json json = json11::Json::object {
{"carVin", vin},
{"carFingerprint", fingerprint},
{"steerRatio", learner.sR},
{"stiffnessFactor", learner.x},
{"angleOffsetAverage", angle_offset_average_degrees},
};
std::string out = json.dump();
std::async(std::launch::async,
[out]{
write_db_value(NULL, "LiveParameters", out.c_str(), out.length());
});
}
}
delete msg;
}
}
delete live_parameters_sock;
delete controls_state_sock;
delete camera_odometry_sock;
delete sensor_events_sock;
delete poller;
delete c;
return 0;
}
<commit_msg>Fix bias state number in paramsd too<commit_after>#include <future>
#include <iostream>
#include <cassert>
#include <csignal>
#include <unistd.h>
#include <capnp/message.h>
#include <capnp/serialize-packed.h>
#include "json11.hpp"
#include "cereal/gen/cpp/log.capnp.h"
#include "common/swaglog.h"
#include "common/messaging.h"
#include "common/params.h"
#include "common/timing.h"
#include "messaging.hpp"
#include "locationd_yawrate.h"
#include "params_learner.h"
#include "common/util.h"
void sigpipe_handler(int sig) {
LOGE("SIGPIPE received");
}
int main(int argc, char *argv[]) {
signal(SIGPIPE, (sighandler_t)sigpipe_handler);
Context * c = Context::create();
SubSocket * controls_state_sock = SubSocket::create(c, "controlsState");
SubSocket * sensor_events_sock = SubSocket::create(c, "sensorEvents");
SubSocket * camera_odometry_sock = SubSocket::create(c, "cameraOdometry");
PubSocket * live_parameters_sock = PubSocket::create(c, "liveParameters");
assert(controls_state_sock != NULL);
assert(sensor_events_sock != NULL);
assert(camera_odometry_sock != NULL);
assert(live_parameters_sock != NULL);
Poller * poller = Poller::create({controls_state_sock, sensor_events_sock, camera_odometry_sock});
Localizer localizer;
// Read car params
char *value;
size_t value_sz = 0;
LOGW("waiting for params to set vehicle model");
while (true) {
read_db_value(NULL, "CarParams", &value, &value_sz);
if (value_sz > 0) break;
usleep(100*1000);
}
LOGW("got %d bytes CarParams", value_sz);
// make copy due to alignment issues
auto amsg = kj::heapArray<capnp::word>((value_sz / sizeof(capnp::word)) + 1);
memcpy(amsg.begin(), value, value_sz);
free(value);
capnp::FlatArrayMessageReader cmsg(amsg);
cereal::CarParams::Reader car_params = cmsg.getRoot<cereal::CarParams>();
// Read params from previous run
const int result = read_db_value(NULL, "LiveParameters", &value, &value_sz);
std::string fingerprint = car_params.getCarFingerprint();
std::string vin = car_params.getCarVin();
double sR = car_params.getSteerRatio();
double x = 1.0;
double ao = 0.0;
double posenet_invalid_count = 0;
if (result == 0){
auto str = std::string(value, value_sz);
free(value);
std::string err;
auto json = json11::Json::parse(str, err);
if (json.is_null() || !err.empty()) {
std::string log = "Error parsing json: " + err;
LOGW(log.c_str());
} else {
std::string new_fingerprint = json["carFingerprint"].string_value();
std::string new_vin = json["carVin"].string_value();
if (fingerprint == new_fingerprint && vin == new_vin) {
std::string log = "Parameter starting with: " + str;
LOGW(log.c_str());
sR = json["steerRatio"].number_value();
x = json["stiffnessFactor"].number_value();
ao = json["angleOffsetAverage"].number_value();
}
}
}
ParamsLearner learner(car_params, ao, x, sR, 1.0);
// Main loop
int save_counter = 0;
while (true){
for (auto s : poller->poll(100)){
Message * msg = s->receive();
auto amsg = kj::heapArray<capnp::word>((msg->getSize() / sizeof(capnp::word)) + 1);
memcpy(amsg.begin(), msg->getData(), msg->getSize());
capnp::FlatArrayMessageReader capnp_msg(amsg);
cereal::Event::Reader event = capnp_msg.getRoot<cereal::Event>();
localizer.handle_log(event);
auto which = event.which();
// Throw vision failure if posenet and odometric speed too different
if (which == cereal::Event::CAMERA_ODOMETRY){
if (std::abs(localizer.posenet_speed - localizer.car_speed) > std::max(0.4 * localizer.car_speed, 5.0)) {
posenet_invalid_count++;
} else {
posenet_invalid_count = 0;
}
} else if (which == cereal::Event::CONTROLS_STATE){
save_counter++;
double yaw_rate = -localizer.x[0];
bool valid = learner.update(yaw_rate, localizer.car_speed, localizer.steering_angle);
// TODO: Fix in replay
double sensor_data_age = localizer.controls_state_time - localizer.sensor_data_time;
double camera_odometry_age = localizer.controls_state_time - localizer.camera_odometry_time;
double angle_offset_degrees = RADIANS_TO_DEGREES * learner.ao;
double angle_offset_average_degrees = RADIANS_TO_DEGREES * learner.slow_ao;
capnp::MallocMessageBuilder msg;
cereal::Event::Builder event = msg.initRoot<cereal::Event>();
event.setLogMonoTime(nanos_since_boot());
auto live_params = event.initLiveParameters();
live_params.setValid(valid);
live_params.setYawRate(localizer.x[0]);
live_params.setGyroBias(localizer.x[1]);
live_params.setSensorValid(sensor_data_age < 5.0);
live_params.setAngleOffset(angle_offset_degrees);
live_params.setAngleOffsetAverage(angle_offset_average_degrees);
live_params.setStiffnessFactor(learner.x);
live_params.setSteerRatio(learner.sR);
live_params.setPosenetSpeed(localizer.posenet_speed);
live_params.setPosenetValid((posenet_invalid_count < 4) && (camera_odometry_age < 5.0));
auto words = capnp::messageToFlatArray(msg);
auto bytes = words.asBytes();
live_parameters_sock->send((char*)bytes.begin(), bytes.size());
// Save parameters every minute
if (save_counter % 6000 == 0) {
json11::Json json = json11::Json::object {
{"carVin", vin},
{"carFingerprint", fingerprint},
{"steerRatio", learner.sR},
{"stiffnessFactor", learner.x},
{"angleOffsetAverage", angle_offset_average_degrees},
};
std::string out = json.dump();
std::async(std::launch::async,
[out]{
write_db_value(NULL, "LiveParameters", out.c_str(), out.length());
});
}
}
delete msg;
}
}
delete live_parameters_sock;
delete controls_state_sock;
delete camera_odometry_sock;
delete sensor_events_sock;
delete poller;
delete c;
return 0;
}
<|endoftext|>
|
<commit_before>// Test for direct coverage writing with dlopen.
// RUN: %clangxx_asan -fsanitize-coverage=1 -DSHARED %s -shared -o %T/libcoverage_direct_test_1.so -fPIC
// RUN: %clangxx_asan -fsanitize-coverage=1 -DSO_DIR=\"%T\" %s %libdl -o %t
// RUN: rm -rf %T/coverage-direct
// RUN: mkdir -p %T/coverage-direct/normal
// RUN: ASAN_OPTIONS=coverage=1:coverage_direct=0:coverage_dir=%T/coverage-direct/normal:verbosity=1 %run %t
// RUN: %sancov print %T/coverage-direct/normal/*.sancov >%T/coverage-direct/normal/out.txt
// RUN: mkdir -p %T/coverage-direct/direct
// RUN: ASAN_OPTIONS=coverage=1:coverage_direct=1:coverage_dir=%T/coverage-direct/direct:verbosity=1 %run %t
// RUN: cd %T/coverage-direct/direct
// RUN: %sancov rawunpack *.sancov.raw
// RUN: %sancov print *.sancov >out.txt
// RUN: cd ../..
// RUN: diff -u coverage-direct/normal/out.txt coverage-direct/direct/out.txt
//
// XFAIL: android
#include <assert.h>
#include <dlfcn.h>
#include <stdio.h>
#include <unistd.h>
#ifdef SHARED
extern "C" {
void bar() { printf("bar\n"); }
}
#else
int main(int argc, char **argv) {
fprintf(stderr, "PID: %d\n", getpid());
void *handle1 =
dlopen(SO_DIR "/libcoverage_direct_test_1.so", RTLD_LAZY);
assert(handle1);
void (*bar1)() = (void (*)())dlsym(handle1, "bar");
assert(bar1);
bar1();
return 0;
}
#endif
<commit_msg>[asan] Add tests for direct (mmap-ed) mode for BB- and edge-level coverage.<commit_after>// Test for direct coverage writing with dlopen at coverage level 1 to 3.
// RUN: %clangxx_asan -fsanitize-coverage=1 -DSHARED %s -shared -o %T/libcoverage_direct_test_1.so -fPIC
// RUN: %clangxx_asan -fsanitize-coverage=1 -DSO_DIR=\"%T\" %s %libdl -o %t
// RUN: rm -rf %T/coverage-direct
// RUN: mkdir -p %T/coverage-direct/normal
// RUN: ASAN_OPTIONS=coverage=1:coverage_direct=0:coverage_dir=%T/coverage-direct/normal:verbosity=1 %run %t
// RUN: %sancov print %T/coverage-direct/normal/*.sancov >%T/coverage-direct/normal/out.txt
// RUN: mkdir -p %T/coverage-direct/direct
// RUN: ASAN_OPTIONS=coverage=1:coverage_direct=1:coverage_dir=%T/coverage-direct/direct:verbosity=1 %run %t
// RUN: cd %T/coverage-direct/direct
// RUN: %sancov rawunpack *.sancov.raw
// RUN: %sancov print *.sancov >out.txt
// RUN: cd ../..
// RUN: diff -u coverage-direct/normal/out.txt coverage-direct/direct/out.txt
// RUN: %clangxx_asan -fsanitize-coverage=2 -DSHARED %s -shared -o %T/libcoverage_direct_test_1.so -fPIC
// RUN: %clangxx_asan -fsanitize-coverage=2 -DSO_DIR=\"%T\" %s %libdl -o %t
// RUN: rm -rf %T/coverage-direct
// RUN: mkdir -p %T/coverage-direct/normal
// RUN: ASAN_OPTIONS=coverage=1:coverage_direct=0:coverage_dir=%T/coverage-direct/normal:verbosity=1 %run %t
// RUN: %sancov print %T/coverage-direct/normal/*.sancov >%T/coverage-direct/normal/out.txt
// RUN: mkdir -p %T/coverage-direct/direct
// RUN: ASAN_OPTIONS=coverage=1:coverage_direct=1:coverage_dir=%T/coverage-direct/direct:verbosity=1 %run %t
// RUN: cd %T/coverage-direct/direct
// RUN: %sancov rawunpack *.sancov.raw
// RUN: %sancov print *.sancov >out.txt
// RUN: cd ../..
// RUN: diff -u coverage-direct/normal/out.txt coverage-direct/direct/out.txt
// RUN: %clangxx_asan -fsanitize-coverage=3 -DSHARED %s -shared -o %T/libcoverage_direct_test_1.so -fPIC
// RUN: %clangxx_asan -fsanitize-coverage=3 -DSO_DIR=\"%T\" %s %libdl -o %t
// RUN: rm -rf %T/coverage-direct
// RUN: mkdir -p %T/coverage-direct/normal
// RUN: ASAN_OPTIONS=coverage=1:coverage_direct=0:coverage_dir=%T/coverage-direct/normal:verbosity=1 %run %t
// RUN: %sancov print %T/coverage-direct/normal/*.sancov >%T/coverage-direct/normal/out.txt
// RUN: mkdir -p %T/coverage-direct/direct
// RUN: ASAN_OPTIONS=coverage=1:coverage_direct=1:coverage_dir=%T/coverage-direct/direct:verbosity=1 %run %t
// RUN: cd %T/coverage-direct/direct
// RUN: %sancov rawunpack *.sancov.raw
// RUN: %sancov print *.sancov >out.txt
// RUN: cd ../..
// RUN: diff -u coverage-direct/normal/out.txt coverage-direct/direct/out.txt
// XFAIL: android
#include <assert.h>
#include <dlfcn.h>
#include <stdio.h>
#include <unistd.h>
#ifdef SHARED
extern "C" {
void bar() { printf("bar\n"); }
}
#else
int main(int argc, char **argv) {
fprintf(stderr, "PID: %d\n", getpid());
void *handle1 =
dlopen(SO_DIR "/libcoverage_direct_test_1.so", RTLD_LAZY);
assert(handle1);
void (*bar1)() = (void (*)())dlsym(handle1, "bar");
assert(bar1);
bar1();
return 0;
}
#endif
<|endoftext|>
|
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2014 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
*
*****************************************************************************/
// mapnik
#include <mapnik/make_unique.hpp>
#include <mapnik/debug.hpp>
#include <mapnik/global.hpp>
#include <mapnik/wkb.hpp>
#include <mapnik/feature.hpp>
#include <mapnik/util/noncopyable.hpp>
#include <mapnik/geometry_adapters.hpp>
#include <mapnik/geometry_correct.hpp>
namespace mapnik
{
struct wkb_reader : util::noncopyable
{
private:
const char* wkb_;
std::size_t size_;
std::size_t pos_;
wkbByteOrder byteOrder_;
bool needSwap_;
wkbFormat format_;
public:
enum wkbGeometryType {
wkbPoint=1,
wkbLineString=2,
wkbPolygon=3,
wkbMultiPoint=4,
wkbMultiLineString=5,
wkbMultiPolygon=6,
wkbGeometryCollection=7,
// Z
wkbPointZ=1001,
wkbLineStringZ=1002,
wkbPolygonZ=1003,
wkbMultiPointZ=1004,
wkbMultiLineStringZ=1005,
wkbMultiPolygonZ=1006,
wkbGeometryCollectionZ=1007,
// M
wkbPointM=2001,
wkbLineStringM=2002,
wkbPolygonM=2003,
wkbMultiPointM=2004,
wkbMultiLineStringM=2005,
wkbMultiPolygonM=2006,
wkbGeometryCollectionM=2007,
// ZM
wkbPointZM=3001,
wkbLineStringZM=3002,
wkbPolygonZM=3003,
wkbMultiPointZM=3004,
wkbMultiLineStringZM=3005,
wkbMultiPolygonZM=3006,
wkbGeometryCollectionZM=3007
};
wkb_reader(const char* wkb, std::size_t size, wkbFormat format)
: wkb_(wkb),
size_(size),
pos_(0),
format_(format)
{
// try to determine WKB format automatically
if (format_ == wkbAuto)
{
if (size_ >= 44
&& static_cast<unsigned char>(wkb_[0]) == static_cast<unsigned char>(0x00)
&& static_cast<unsigned char>(wkb_[38]) == static_cast<unsigned char>(0x7C)
&& static_cast<unsigned char>(wkb_[size_ - 1]) == static_cast<unsigned char>(0xFE))
{
format_ = wkbSpatiaLite;
}
else
{
format_ = wkbGeneric;
}
}
switch (format_)
{
case wkbSpatiaLite:
byteOrder_ = (wkbByteOrder) wkb_[1];
pos_ = 39;
break;
case wkbGeneric:
default:
byteOrder_ = (wkbByteOrder) wkb_[0];
pos_ = 1;
break;
}
needSwap_ = byteOrder_ ? wkbXDR : wkbNDR;
}
mapnik::geometry::geometry read()
{
mapnik::geometry::geometry geom = mapnik::geometry::geometry_empty();
int type = read_integer();
switch (type)
{
case wkbPoint:
geom = std::move(read_point());
break;
case wkbLineString:
geom = std::move(read_linestring());
break;
case wkbPolygon:
geom = std::move(read_polygon());
break;
case wkbMultiPoint:
geom = std::move(read_multipoint());
break;
case wkbMultiLineString:
geom = std::move(read_multilinestring());
break;
case wkbMultiPolygon:
geom = std::move(read_multipolygon());
break;
case wkbGeometryCollection:
geom = std::move(read_collection());
break;
case wkbPointZ:
case wkbPointM:
geom = std::move(read_point<true>());
break;
case wkbPointZM:
geom = std::move(read_point<true,true>());
break;
case wkbLineStringZ:
case wkbLineStringM:
geom = std::move(read_linestring<true>());
break;
case wkbLineStringZM:
geom = std::move(read_linestring<true,true>());
break;
case wkbPolygonZ:
case wkbPolygonM:
geom = std::move(read_polygon<true>());
break;
case wkbPolygonZM:
geom = std::move(read_polygon<true,true>());
case wkbMultiPointZ:
case wkbMultiPointM:
geom = std::move(read_multipoint<true>());
break;
case wkbMultiPointZM:
geom = std::move(read_multipoint<true,true>());
break;
case wkbMultiLineStringZ:
case wkbMultiLineStringM:
geom = std::move(read_multilinestring<true>());
break;
case wkbMultiLineStringZM:
geom = std::move(read_multilinestring<true,true>());
break;
case wkbMultiPolygonZ:
case wkbMultiPolygonM:
geom = std::move(read_multipolygon<true>());
break;
case wkbMultiPolygonZM:
geom = std::move(read_multipolygon<true,true>());
break;
case wkbGeometryCollectionZ:
case wkbGeometryCollectionM:
case wkbGeometryCollectionZM:
geom = std::move(read_collection());
break;
default:
break;
}
return geom;
}
private:
int read_integer()
{
std::int32_t n;
if (needSwap_)
{
read_int32_xdr(wkb_ + pos_, n);
}
else
{
read_int32_ndr(wkb_ + pos_, n);
}
pos_ += 4;
return n;
}
double read_double()
{
double d;
if (needSwap_)
{
read_double_xdr(wkb_ + pos_, d);
}
else
{
read_double_ndr(wkb_ + pos_, d);
}
pos_ += 8;
return d;
}
template <typename Ring, bool Z = false, bool M = false>
void read_coords(Ring & ring, std::size_t num_points)
{
double x,y;
if (!needSwap_)
{
for (std::size_t i = 0; i < num_points; ++i)
{
read_double_ndr(wkb_ + pos_, x);
read_double_ndr(wkb_ + pos_ + 8, y);
ring.emplace_back(x,y);
pos_ += 16; // skip XY
if (Z) pos_ += 8;
if (M) pos_ += 8;
}
}
else
{
for (std::size_t i = 0; i < num_points; ++i)
{
read_double_xdr(wkb_ + pos_, x);
read_double_xdr(wkb_ + pos_ + 8, y);
ring.emplace_back(x,y);
pos_ += 16; // skip XY
if (Z) pos_ += 8;
if (M) pos_ += 8;
}
}
}
template <bool Z = false, bool M = false>
mapnik::geometry::point read_point()
{
double x = read_double();
double y = read_double();
if (Z) pos_ += 8;
if (M) pos_ += 8;
return mapnik::geometry::point(x, y);
}
template <bool Z = false, bool M = false>
mapnik::geometry::multi_point read_multipoint()
{
mapnik::geometry::multi_point multi_point;
int num_points = read_integer();
multi_point.reserve(num_points);
for (int i = 0; i < num_points; ++i)
{
pos_ += 5;
multi_point.emplace_back(read_point<Z,M>());
}
return multi_point;
}
template <bool M = false, bool Z = false>
mapnik::geometry::line_string read_linestring()
{
mapnik::geometry::line_string line;
int num_points = read_integer();
if (num_points > 0)
{
line.reserve(num_points);
read_coords<mapnik::geometry::line_string, M, Z>(line, num_points);
}
return line;
}
template <bool M = false, bool Z = false>
mapnik::geometry::multi_line_string read_multilinestring()
{
int num_lines = read_integer();
mapnik::geometry::multi_line_string multi_line;
multi_line.reserve(num_lines);
for (int i = 0; i < num_lines; ++i)
{
pos_ += 5;
multi_line.push_back(std::move(read_linestring<M, Z>()));
}
return multi_line;
}
template <bool M = false, bool Z = false>
mapnik::geometry::polygon read_polygon()
{
int num_rings = read_integer();
mapnik::geometry::polygon poly;
if (num_rings > 1)
{
poly.interior_rings.reserve(num_rings - 1);
}
for (int i = 0; i < num_rings; ++i)
{
mapnik::geometry::linear_ring ring;
int num_points = read_integer();
if (num_points > 0)
{
ring.reserve(num_points);
read_coords<mapnik::geometry::linear_ring, M, Z>(ring, num_points);
}
if ( i == 0) poly.set_exterior_ring(std::move(ring));
else poly.add_hole(std::move(ring));
}
return poly;
}
template <bool M = false, bool Z = false>
mapnik::geometry::multi_polygon read_multipolygon()
{
int num_polys = read_integer();
mapnik::geometry::multi_polygon multi_poly;
for (int i = 0; i < num_polys; ++i)
{
pos_ += 5;
multi_poly.push_back(std::move(read_polygon<M, Z>()));
}
return multi_poly;
}
mapnik::geometry::geometry_collection read_collection()
{
int num_geometries = read_integer();
mapnik::geometry::geometry_collection collection;
for (int i = 0; i < num_geometries; ++i)
{
pos_ += 1; // skip byte order
collection.push_back(std::move(read()));
}
return collection;
}
std::string wkb_geometry_type_string(int type)
{
std::stringstream s;
switch (type)
{
case wkbPoint: s << "Point"; break;
case wkbPointZ: s << "PointZ"; break;
case wkbPointM: s << "PointM"; break;
case wkbPointZM: s << "PointZM"; break;
case wkbMultiPoint: s << "MultiPoint"; break;
case wkbMultiPointZ: s << "MultiPointZ"; break;
case wkbMultiPointM: s << "MultiPointM"; break;
case wkbMultiPointZM: s << "MultiPointZM"; break;
case wkbLineString: s << "LineString"; break;
case wkbLineStringZ: s << "LineStringZ"; break;
case wkbLineStringM: s << "LineStringM"; break;
case wkbLineStringZM: s << "LineStringZM"; break;
case wkbMultiLineString: s << "MultiLineString"; break;
case wkbMultiLineStringZ: s << "MultiLineStringZ"; break;
case wkbMultiLineStringM: s << "MultiLineStringM"; break;
case wkbMultiLineStringZM: s << "MultiLineStringZM"; break;
case wkbPolygon: s << "Polygon"; break;
case wkbPolygonZ: s << "PolygonZ"; break;
case wkbPolygonM: s << "PolygonM"; break;
case wkbPolygonZM: s << "PolygonZM"; break;
case wkbMultiPolygon: s << "MultiPolygon"; break;
case wkbMultiPolygonZ: s << "MultiPolygonZ"; break;
case wkbMultiPolygonM: s << "MultiPolygonM"; break;
case wkbMultiPolygonZM: s << "MultiPolygonZM"; break;
case wkbGeometryCollection: s << "GeometryCollection"; break;
case wkbGeometryCollectionZ: s << "GeometryCollectionZ"; break;
case wkbGeometryCollectionM: s << "GeometryCollectionM"; break;
case wkbGeometryCollectionZM:s << "GeometryCollectionZM"; break;
default: s << "wkbUnknown(" << type << ")"; break;
}
return s.str();
}
};
mapnik::geometry::geometry geometry_utils::from_wkb(const char* wkb,
unsigned size,
wkbFormat format)
{
wkb_reader reader(wkb, size, format);
mapnik::geometry::geometry geom(reader.read());
mapnik::geometry::correct(geom);
return geom;
}
} // namespace mapnik
<commit_msg>bug fix - add missing break statement<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2014 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
*
*****************************************************************************/
// mapnik
#include <mapnik/make_unique.hpp>
#include <mapnik/debug.hpp>
#include <mapnik/global.hpp>
#include <mapnik/wkb.hpp>
#include <mapnik/feature.hpp>
#include <mapnik/util/noncopyable.hpp>
#include <mapnik/geometry_adapters.hpp>
#include <mapnik/geometry_correct.hpp>
namespace mapnik
{
struct wkb_reader : util::noncopyable
{
private:
const char* wkb_;
std::size_t size_;
std::size_t pos_;
wkbByteOrder byteOrder_;
bool needSwap_;
wkbFormat format_;
public:
enum wkbGeometryType {
wkbPoint=1,
wkbLineString=2,
wkbPolygon=3,
wkbMultiPoint=4,
wkbMultiLineString=5,
wkbMultiPolygon=6,
wkbGeometryCollection=7,
// Z
wkbPointZ=1001,
wkbLineStringZ=1002,
wkbPolygonZ=1003,
wkbMultiPointZ=1004,
wkbMultiLineStringZ=1005,
wkbMultiPolygonZ=1006,
wkbGeometryCollectionZ=1007,
// M
wkbPointM=2001,
wkbLineStringM=2002,
wkbPolygonM=2003,
wkbMultiPointM=2004,
wkbMultiLineStringM=2005,
wkbMultiPolygonM=2006,
wkbGeometryCollectionM=2007,
// ZM
wkbPointZM=3001,
wkbLineStringZM=3002,
wkbPolygonZM=3003,
wkbMultiPointZM=3004,
wkbMultiLineStringZM=3005,
wkbMultiPolygonZM=3006,
wkbGeometryCollectionZM=3007
};
wkb_reader(const char* wkb, std::size_t size, wkbFormat format)
: wkb_(wkb),
size_(size),
pos_(0),
format_(format)
{
// try to determine WKB format automatically
if (format_ == wkbAuto)
{
if (size_ >= 44
&& static_cast<unsigned char>(wkb_[0]) == static_cast<unsigned char>(0x00)
&& static_cast<unsigned char>(wkb_[38]) == static_cast<unsigned char>(0x7C)
&& static_cast<unsigned char>(wkb_[size_ - 1]) == static_cast<unsigned char>(0xFE))
{
format_ = wkbSpatiaLite;
}
else
{
format_ = wkbGeneric;
}
}
switch (format_)
{
case wkbSpatiaLite:
byteOrder_ = (wkbByteOrder) wkb_[1];
pos_ = 39;
break;
case wkbGeneric:
default:
byteOrder_ = (wkbByteOrder) wkb_[0];
pos_ = 1;
break;
}
needSwap_ = byteOrder_ ? wkbXDR : wkbNDR;
}
mapnik::geometry::geometry read()
{
mapnik::geometry::geometry geom = mapnik::geometry::geometry_empty();
int type = read_integer();
switch (type)
{
case wkbPoint:
geom = std::move(read_point());
break;
case wkbLineString:
geom = std::move(read_linestring());
break;
case wkbPolygon:
geom = std::move(read_polygon());
break;
case wkbMultiPoint:
geom = std::move(read_multipoint());
break;
case wkbMultiLineString:
geom = std::move(read_multilinestring());
break;
case wkbMultiPolygon:
geom = std::move(read_multipolygon());
break;
case wkbGeometryCollection:
geom = std::move(read_collection());
break;
case wkbPointZ:
case wkbPointM:
geom = std::move(read_point<true>());
break;
case wkbPointZM:
geom = std::move(read_point<true,true>());
break;
case wkbLineStringZ:
case wkbLineStringM:
geom = std::move(read_linestring<true>());
break;
case wkbLineStringZM:
geom = std::move(read_linestring<true,true>());
break;
case wkbPolygonZ:
case wkbPolygonM:
geom = std::move(read_polygon<true>());
break;
case wkbPolygonZM:
geom = std::move(read_polygon<true,true>());
break;
case wkbMultiPointZ:
case wkbMultiPointM:
geom = std::move(read_multipoint<true>());
break;
case wkbMultiPointZM:
geom = std::move(read_multipoint<true,true>());
break;
case wkbMultiLineStringZ:
case wkbMultiLineStringM:
geom = std::move(read_multilinestring<true>());
break;
case wkbMultiLineStringZM:
geom = std::move(read_multilinestring<true,true>());
break;
case wkbMultiPolygonZ:
case wkbMultiPolygonM:
geom = std::move(read_multipolygon<true>());
break;
case wkbMultiPolygonZM:
geom = std::move(read_multipolygon<true,true>());
break;
case wkbGeometryCollectionZ:
case wkbGeometryCollectionM:
case wkbGeometryCollectionZM:
geom = std::move(read_collection());
break;
default:
break;
}
return geom;
}
private:
int read_integer()
{
std::int32_t n;
if (needSwap_)
{
read_int32_xdr(wkb_ + pos_, n);
}
else
{
read_int32_ndr(wkb_ + pos_, n);
}
pos_ += 4;
return n;
}
double read_double()
{
double d;
if (needSwap_)
{
read_double_xdr(wkb_ + pos_, d);
}
else
{
read_double_ndr(wkb_ + pos_, d);
}
pos_ += 8;
return d;
}
template <typename Ring, bool Z = false, bool M = false>
void read_coords(Ring & ring, std::size_t num_points)
{
double x,y;
if (!needSwap_)
{
for (std::size_t i = 0; i < num_points; ++i)
{
read_double_ndr(wkb_ + pos_, x);
read_double_ndr(wkb_ + pos_ + 8, y);
ring.emplace_back(x,y);
pos_ += 16; // skip XY
if (Z) pos_ += 8;
if (M) pos_ += 8;
}
}
else
{
for (std::size_t i = 0; i < num_points; ++i)
{
read_double_xdr(wkb_ + pos_, x);
read_double_xdr(wkb_ + pos_ + 8, y);
ring.emplace_back(x,y);
pos_ += 16; // skip XY
if (Z) pos_ += 8;
if (M) pos_ += 8;
}
}
}
template <bool Z = false, bool M = false>
mapnik::geometry::point read_point()
{
double x = read_double();
double y = read_double();
if (Z) pos_ += 8;
if (M) pos_ += 8;
return mapnik::geometry::point(x, y);
}
template <bool Z = false, bool M = false>
mapnik::geometry::multi_point read_multipoint()
{
mapnik::geometry::multi_point multi_point;
int num_points = read_integer();
multi_point.reserve(num_points);
for (int i = 0; i < num_points; ++i)
{
pos_ += 5;
multi_point.emplace_back(read_point<Z,M>());
}
return multi_point;
}
template <bool M = false, bool Z = false>
mapnik::geometry::line_string read_linestring()
{
mapnik::geometry::line_string line;
int num_points = read_integer();
if (num_points > 0)
{
line.reserve(num_points);
read_coords<mapnik::geometry::line_string, M, Z>(line, num_points);
}
return line;
}
template <bool M = false, bool Z = false>
mapnik::geometry::multi_line_string read_multilinestring()
{
int num_lines = read_integer();
mapnik::geometry::multi_line_string multi_line;
multi_line.reserve(num_lines);
for (int i = 0; i < num_lines; ++i)
{
pos_ += 5;
multi_line.push_back(std::move(read_linestring<M, Z>()));
}
return multi_line;
}
template <bool M = false, bool Z = false>
mapnik::geometry::polygon read_polygon()
{
int num_rings = read_integer();
mapnik::geometry::polygon poly;
if (num_rings > 1)
{
poly.interior_rings.reserve(num_rings - 1);
}
for (int i = 0; i < num_rings; ++i)
{
mapnik::geometry::linear_ring ring;
int num_points = read_integer();
if (num_points > 0)
{
ring.reserve(num_points);
read_coords<mapnik::geometry::linear_ring, M, Z>(ring, num_points);
}
if ( i == 0) poly.set_exterior_ring(std::move(ring));
else poly.add_hole(std::move(ring));
}
return poly;
}
template <bool M = false, bool Z = false>
mapnik::geometry::multi_polygon read_multipolygon()
{
int num_polys = read_integer();
mapnik::geometry::multi_polygon multi_poly;
for (int i = 0; i < num_polys; ++i)
{
pos_ += 5;
multi_poly.push_back(std::move(read_polygon<M, Z>()));
}
return multi_poly;
}
mapnik::geometry::geometry_collection read_collection()
{
int num_geometries = read_integer();
mapnik::geometry::geometry_collection collection;
for (int i = 0; i < num_geometries; ++i)
{
pos_ += 1; // skip byte order
collection.push_back(std::move(read()));
}
return collection;
}
std::string wkb_geometry_type_string(int type)
{
std::stringstream s;
switch (type)
{
case wkbPoint: s << "Point"; break;
case wkbPointZ: s << "PointZ"; break;
case wkbPointM: s << "PointM"; break;
case wkbPointZM: s << "PointZM"; break;
case wkbMultiPoint: s << "MultiPoint"; break;
case wkbMultiPointZ: s << "MultiPointZ"; break;
case wkbMultiPointM: s << "MultiPointM"; break;
case wkbMultiPointZM: s << "MultiPointZM"; break;
case wkbLineString: s << "LineString"; break;
case wkbLineStringZ: s << "LineStringZ"; break;
case wkbLineStringM: s << "LineStringM"; break;
case wkbLineStringZM: s << "LineStringZM"; break;
case wkbMultiLineString: s << "MultiLineString"; break;
case wkbMultiLineStringZ: s << "MultiLineStringZ"; break;
case wkbMultiLineStringM: s << "MultiLineStringM"; break;
case wkbMultiLineStringZM: s << "MultiLineStringZM"; break;
case wkbPolygon: s << "Polygon"; break;
case wkbPolygonZ: s << "PolygonZ"; break;
case wkbPolygonM: s << "PolygonM"; break;
case wkbPolygonZM: s << "PolygonZM"; break;
case wkbMultiPolygon: s << "MultiPolygon"; break;
case wkbMultiPolygonZ: s << "MultiPolygonZ"; break;
case wkbMultiPolygonM: s << "MultiPolygonM"; break;
case wkbMultiPolygonZM: s << "MultiPolygonZM"; break;
case wkbGeometryCollection: s << "GeometryCollection"; break;
case wkbGeometryCollectionZ: s << "GeometryCollectionZ"; break;
case wkbGeometryCollectionM: s << "GeometryCollectionM"; break;
case wkbGeometryCollectionZM:s << "GeometryCollectionZM"; break;
default: s << "wkbUnknown(" << type << ")"; break;
}
return s.str();
}
};
mapnik::geometry::geometry geometry_utils::from_wkb(const char* wkb,
unsigned size,
wkbFormat format)
{
wkb_reader reader(wkb, size, format);
mapnik::geometry::geometry geom(reader.read());
mapnik::geometry::correct(geom);
return geom;
}
} // namespace mapnik
<|endoftext|>
|
<commit_before>#include "FPSRoleLocal.h"
#include "Creature.h"
#include "Engine.h"
#include "Input.h"
#include "App.h"
#include "ObjectMeshSkinned.h"
#include "ActorBase.h"
#include "Visualizer.h"
#include "game.h"
#include "RayControl.h"
#include "Common.h"
#include "ControlsApp.h"
CFPSRoleLocal::CFPSRoleLocal(void)
{
m_nCharMode = 0;
m_nMuzzleBone = -1;
m_nUpdateMove = 0;
}
CFPSRoleLocal::~CFPSRoleLocal(void)
{
delete m_pActorBase;
}
int CFPSRoleLocal::Init( int nRoleID,const char* strCharFile )
{
CFPSRole::Init(nRoleID,strCharFile);
m_pCreature->SetupBody(1,1);
m_pCreature->SetHighShadow(1);
SetupArms(2,0);
m_pActorBase = new CActorBase();
m_pActorBase->SetEnabled(1);
//
//m_vCameraOffset = vec3(0.0f,0.0f,1.8f);
m_vCameraOffset = vec3(0.0f,0.0f,1.8f);
//m_vGunOffset = vec3(0.0,0.0,-0.0f);
m_vGunOffset = vec3(0.2,0.2,0.2f);
//m_vRotateOffset = vec3(-0.076326f, 0.018540f, -1.725809f); // gua dian weizhi);
m_vRotateOffset = vec3(-0.076326f, 0.018540f, -1.725809f); // gua dian weizhi);
return 1;
}
void CFPSRoleLocal::Update( float ifps )
{
if(m_pFire[0] && m_pFire[1])
{
//if(g_Engine.pApp->GetMouseButtonState(CApp::BUTTON_LEFT) || g_Engine.pApp->GetMouseButtonState(CApp::BUTTON_LDCLICK) )
if(g_Engine.pInput->IsLBDownPress()||g_Engine.pInput->IsLBDBDown())
{
OpenFire(); //굥
}
else
{
CloseFire();
}
}
CFPSRole::Update(ifps);
CRayControl::Instance().Update(m_matMuzzleTransform,vec3(0.0f,0.5f,-0.03f));
}
void CFPSRoleLocal::OnFire( float fCoolingTime )
{
CFPSRole::OnFire(fCoolingTime);
}
void CFPSRoleLocal::UpdateTransform( const MathLib::mat4 & matRotate )
{
mat4 m = Translate(m_pActorBase->GetPosition()+ m_vCameraOffset) * Translate(m_vGunOffset) * matRotate * Translate(m_vRotateOffset);
}<commit_msg>Signed-off-by: mrlitong <litongtongxue@gmail.com><commit_after>#include "FPSRoleLocal.h"
#include "Creature.h"
#include "Engine.h"
#include "Input.h"
#include "App.h"
#include "ObjectMeshSkinned.h"
#include "ActorBase.h"
#include "Visualizer.h"
#include "game.h"
#include "RayControl.h"
#include "Common.h"
#include "ControlsApp.h"
CFPSRoleLocal::CFPSRoleLocal(void)
{
m_nCharMode = 0;
m_nMuzzleBone = -1;
m_nUpdateMove = 0;
}
CFPSRoleLocal::~CFPSRoleLocal(void)
{
delete m_pActorBase;
}
int CFPSRoleLocal::Init( int nRoleID,const char* strCharFile )
{
CFPSRole::Init(nRoleID,strCharFile);
m_pCreature->SetupBody(1,1);
m_pCreature->SetHighShadow(1);
SetupArms(2,0);
m_pActorBase = new CActorBase();
m_pActorBase->SetEnabled(1);
//
//m_vCameraOffset = vec3(0.0f,0.0f,1.8f);
m_vCameraOffset = vec3(0.0f,0.0f,1.8f);
//m_vGunOffset = vec3(0.0,0.0,-0.0f);
m_vGunOffset = vec3(0.2,0.2,0.2f);
//m_vRotateOffset = vec3(-0.076326f, 0.018540f, -1.725809f); // gua dian weizhi);
m_vRotateOffset = vec3(-0.076326f, 0.018540f, -1.725809f); // gua dian weizhi);
return 1;
}
void CFPSRoleLocal::Update( float ifps )
{
if(m_pFire[0] && m_pFire[1])
{
//if(g_Engine.pApp->GetMouseButtonState(CApp::BUTTON_LEFT) || g_Engine.pApp->GetMouseButtonState(CApp::BUTTON_LDCLICK) )
if(g_Engine.pInput->IsLBDownPress()||g_Engine.pInput->IsLBDBDown())
{
OpenFire(); //굥
}
else
{
CloseFire();
}
}
CFPSRole::Update(ifps);
CRayControl::Instance().Update(m_matMuzzleTransform,vec3(0.0f,0.5f,-0.03f));
}
void CFPSRoleLocal::OnFire( float fCoolingTime )
{
CFPSRole::OnFire(fCoolingTime);
}
void CFPSRoleLocal::UpdateTransform( const MathLib::mat4 & matRotate )
{
mat4 m = Translate(m_pActorBase->GetPosition()+ m_vCameraOffset) * Translate(m_vGunOffset) * matRotate * Translate(m_vRotateOffset);
m_pCreature->GetMainObjectMesh()->SetWorldTransform(m);
}
<|endoftext|>
|
<commit_before>/*-
* Copyright (c) 2016 Frederic Culot <culot@FreeBSD.org>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer
* in this position and unchanged.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR(S) 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 <tuple>
#include <curses.h>
#include "event.h"
#include "inputwindow.h"
namespace portal {
namespace gfx {
InputWindow::InputWindow(const Point& pos, int len)
: Window() {
Size size;
size.setHeight(3);
size.setWidth(len + 2);
setSize(size);
Point position;
position.setX(pos.x() - 1);
position.setY(pos.y() - 1);
setPosition(position);
Style style;
style.underline = true;
setStyle(style);
draw();
}
std::string InputWindow::getInput() {
for (;;) {
portal::Event event;
event.poll();
clear();
switch (event.type()) {
case portal::Event::Type::enter:
return content_;
case portal::Event::Type::keyBackspace:
content_.pop_back();
break;
case portal::Event::Type::character:
content_.push_back(event.character());
break;
default:
// DO NOTHING
break;
}
print(content_);
}
}
void InputWindow::setContent(const std::string& content) {
content_ = content;
print(content_);
}
}
}
<commit_msg>Fix input window position<commit_after>/*-
* Copyright (c) 2016 Frederic Culot <culot@FreeBSD.org>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer
* in this position and unchanged.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR(S) 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 <tuple>
#include <curses.h>
#include "event.h"
#include "inputwindow.h"
namespace portal {
namespace gfx {
InputWindow::InputWindow(const Point& pos, int len)
: Window() {
Size size;
size.setHeight(1);
size.setWidth(len + 2);
setSize(size);
Point position;
position.setX(pos.x() - len / 2);
position.setY(pos.y());
setPosition(position);
Style style;
style.underline = true;
setStyle(style);
draw();
}
std::string InputWindow::getInput() {
for (;;) {
portal::Event event;
event.poll();
clear();
switch (event.type()) {
case portal::Event::Type::enter:
return content_;
case portal::Event::Type::keyBackspace:
content_.pop_back();
break;
case portal::Event::Type::character:
content_.push_back(event.character());
break;
default:
// DO NOTHING
break;
}
print(content_);
}
}
void InputWindow::setContent(const std::string& content) {
content_ = content;
print(content_);
}
}
}
<|endoftext|>
|
<commit_before>/**********************************************************************/
/* Copyright 2014 RCF */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, */
/* software distributed under the License is distributed on an */
/* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, */
/* either express or implied. */
/* See the License for the specific language governing permissions */
/* and limitations under the License. */
/**********************************************************************/
/**
* @file Simplex.cpp
* @brief Main interface for use of the Network Simplex Algorithm
*/
// Default libraries
#include <tuple>
#include <cstdio>
#include <iostream>
using namespace std;
// Libraries
#include "Options.hpp"
#include "graph/graph.tcc"
#include "graph/flow/flow.tcc"
#include "transport/Transport.hpp"
/**
* @fn Main
* @param argc Number of arguments in the command line
* @param argv Array of string with the arguments
* @return 0 if success; non-zero otherwise
*/
int main(int argc, char **argv)
{
// Process options
Options::parse_args(argc, argv);
if(argc-optind != 1)
{
cerr << "Usage: Simplex [-h] [-d] input.dat ..." << endl;
cerr << "Type --help for more information" << endl;
return EXIT_FAILURE;
}
transport::Transport problem { argv[1] };
cout << problem << endl;
problem.calculate_best_route();
cout << problem << endl;
// typedef graph::flow::Vertex<>::type vertex;
// typedef graph::flow::Arc<>::type arc;
//
// vertex v1 { 0 }, v2 { 1 };
// arc a1 { v1, v2 }, a2 { v2, v1 };
//
// cout << endl << "Vertex list" << endl;
// cout << "=======================" << endl;
// typedef std::vector<vertex> vertex_list;
// vertex_list vl { v1, v2 };
// for(const vertex& v : vl)
// cout << v << endl;
//
// cout << endl << "Arc list" << endl;
// cout << "=======================" << endl;
// typedef std::vector<arc> arc_list;
// arc_list al { a1, a2 };
// for(const arc& a : al)
// cout << a << endl;
//
// cout << endl << "Digraph" << endl;
// cout << "=======================" << endl;
// typedef graph::Adjacency_list<graph::directed,vertex,arc> digraph;
//
// vertex_list tr1_v;
//
// vertex::id_type id {};
// for(size_t i = 0; i < 5; i++)
// tr1_v.emplace_back(id++);
//
// arc_list tr1_a {
// arc{ 0, 1, { 9} },
// arc{ 0, 3, {10} },
// arc{ 1, 2, { 7} },
// arc{ 1, 3, { 4} },
// arc{ 1, 4, { 5} },
// arc{ 2, 4, { 9} },
// arc{ 3, 1, { 4} },
// arc{ 3, 4, { 9} }
// };
//
// digraph T { tr1_v, tr1_a };
//
// typename digraph::vertex_iterator it,it_end;
// for(std::tie(it,it_end) = T.vertices(); it != it_end; ++it)
// cout << *it << endl;
//
// typename digraph::arc_iterator ait,ait_end;
// for(std::tie(ait,ait_end) = T.arcs(); ait != ait_end; ++ait)
// cout << *ait << endl;
//
// cout << "Before removing" << endl;
// for(int i = 0; i <= 4; i++)
// {
// cout << "List " << i << endl;
// for(auto& a : out_arcs_list(i,T))
// cout << a << endl;
// }
//
// add_arc(arc{0,2},T);
// remove_arc(0,1,T);
//
// cout << "After removing" << endl;
// for(int i = 0; i <= 4; i++)
// {
// cout << "List " << i << endl;
// for(auto& a : out_arcs_list(i,T))
// cout << a << endl;
// }
return EXIT_SUCCESS;
}
<commit_msg>Functional main<commit_after>/**********************************************************************/
/* Copyright 2014 RCF */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, */
/* software distributed under the License is distributed on an */
/* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, */
/* either express or implied. */
/* See the License for the specific language governing permissions */
/* and limitations under the License. */
/**********************************************************************/
/**
* @file Simplex.cpp
* @brief Main interface for use of the Network Simplex Algorithm
*/
// Default libraries
#include <tuple>
#include <cstdio>
#include <fstream>
#include <iostream>
using namespace std;
// Libraries
#include "Options.hpp"
#include "graph/graph.tcc"
#include "graph/flow/flow.tcc"
#include "transport/Transport.hpp"
/**
* @fn Main
* @param argc Number of arguments in the command line
* @param argv Array of string with the arguments
* @return 0 if success; non-zero otherwise
*/
int main(int argc, char **argv)
{
// Process options
Options options; options.parse_args(argc, argv);
if(argc-optind != 1)
{
cerr << "Usage: Simplex [-d] [-v] [-o] input.dat ..." << endl;
cerr << "Type --help for more information" << endl;
return EXIT_FAILURE;
}
typedef transport::Transport::arc_type arc_type;
typedef transport::Transport::arc_list arc_list;
std::ofstream output {options.output};
std::ostream& os = options.output.empty() ? cout : output;
for(int i = optind; i < argc; ++i)
{
os << endl;
if(options.verbose)
{
os << "Analyzing file " << argv[i] << endl;
os << "==========================" << endl;
os << endl;
}
if(options.verbose) os << "Graph: " << endl;
transport::Transport problem { argv[i] };
if(options.verbose) os << problem << endl;
// Best route
arc_list values; int final_cost;
std::tie(values,final_cost) = problem.calculate_best_route();
os << "Cost: " << final_cost << endl;
os << "List of arcs: " << endl;
for(arc_type& arc : values)
{
if(options.verbose) os << arc << std::endl;
else os << arc.id << " - " << arc.properties.flux << endl;
}
}
// typedef graph::flow::Vertex<>::type vertex;
// typedef graph::flow::Arc<>::type arc;
//
// vertex v1 { 0 }, v2 { 1 };
// arc a1 { v1, v2 }, a2 { v2, v1 };
//
// cout << endl << "Vertex list" << endl;
// cout << "=======================" << endl;
// typedef std::vector<vertex> vertex_list;
// vertex_list vl { v1, v2 };
// for(const vertex& v : vl)
// cout << v << endl;
//
// cout << endl << "Arc list" << endl;
// cout << "=======================" << endl;
// typedef std::vector<arc> arc_list;
// arc_list al { a1, a2 };
// for(const arc& a : al)
// cout << a << endl;
//
// cout << endl << "Digraph" << endl;
// cout << "=======================" << endl;
// typedef graph::Adjacency_list<graph::directed,vertex,arc> digraph;
//
// vertex_list tr1_v;
//
// vertex::id_type id {};
// for(size_t i = 0; i < 5; i++)
// tr1_v.emplace_back(id++);
//
// arc_list tr1_a {
// arc{ 0, 1, { 9} },
// arc{ 0, 3, {10} },
// arc{ 1, 2, { 7} },
// arc{ 1, 3, { 4} },
// arc{ 1, 4, { 5} },
// arc{ 2, 4, { 9} },
// arc{ 3, 1, { 4} },
// arc{ 3, 4, { 9} }
// };
//
// digraph T { tr1_v, tr1_a };
//
// typename digraph::vertex_iterator it,it_end;
// for(std::tie(it,it_end) = T.vertices(); it != it_end; ++it)
// cout << *it << endl;
//
// typename digraph::arc_iterator ait,ait_end;
// for(std::tie(ait,ait_end) = T.arcs(); ait != ait_end; ++ait)
// cout << *ait << endl;
//
// cout << "Before removing" << endl;
// for(int i = 0; i <= 4; i++)
// {
// cout << "List " << i << endl;
// for(auto& a : out_arcs_list(i,T))
// cout << a << endl;
// }
//
// add_arc(arc{0,2},T);
// remove_arc(0,1,T);
//
// cout << "After removing" << endl;
// for(int i = 0; i <= 4; i++)
// {
// cout << "List " << i << endl;
// for(auto& a : out_arcs_list(i,T))
// cout << a << endl;
// }
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>/* FILE INFORMATION
File: iq.cpp
Authors: Matthew Cole <mcole8@binghamton.edu>
Brian Gracin <bgracin1@binghamton.edu>
Description: Contains the IQ class, which simulates the operation of a Instruction Queue.
*/
#include <iostream>
#include "iq.h"
IQ::IQ(){
this->initialize();
}
IQ::~IQ(){
}
// Return true if the IQ is empty,
// Return false otherwise
// (Delegates to stl::queue::empty())
bool IQ::isEmpty(){
return issue_queue.empty();
}
//Display the contents of the IQ
//Each entry is a Stage, so we delegate the display logic
void IQ::display(){
std::cout << "Head" << std::endl;
for (auto e : issue_queue){
e.display();
}
std::cout << "Tail" << std::endl;
}
//Initialize the IQ to empty state
void IQ::initialize(){
issue_queue.clear();
}
//Dispatch an instruction to IQ
void IQ::dispatchInst(Stage &stage){
stage.empty = false;
stage.ready = false;
this->issue_queue.push_back(stage);
}
//Forward the value of an R reg that was computed from an FU
//If an instruction is found to have an R reg that is being forwarded
//Set value and valid bit for associated operand fields
void IQ::updateSrc(std::string reg, int val){
if (issue_queue.size() > 0){
for (auto& e : issue_queue){
//Handle forward to arithmatic instructions in IQ
if(e.opcode == "ADD" ||
e.opcode == "SUB" ||
e.opcode == "MUL" ||
e.opcode == "AND" ||
e.opcode == "OR" ||
e.opcode == "EX-OR"){
if(e.operands.at(1) == reg){
e.values.at(1) = val;
e.valids.at(1) = true;
}
if(e.operands.at(2) == reg){
e.values.at(2) = val;
e.valids.at(2) = true;
}
}
//Handle forward to LOAD instruction in IQ
if(e.opcode == "LOAD"){
if(e.operands.at(1) == reg){
e.values.at(1) = val;
e.valids.at(1) = true;
}
}
//Handle forward to branch instructions in IQ
if(e.opcode == "BAL" ||
e.opcode == "JUMP"){
if(e.operands.at(0) == reg){
e.values.at(0) = val;
e.valids.at(0) = true;
}
}
//Handle forward to STORE instructions in IQ
if(e.opcode == "STORE"){
if(e.operands.at(0) == reg){
e.values.at(0) = val;
e.valids.at(0) = true;
}
if(e.operands.at(1) == reg){
e.values.at(1) = val;
e.valids.at(1) = true;
}
}
}
}
}
//TODO
bool issue(Stage* ALU, Stage* MUL, Stage* LSFU, Stage* B){
//for (auto& e : issue_queue){
for (auto i = this->issue_queue.begin(); i != this->issue_queue.end();)
if (i->isReady()){
if(i->opcode == "ADD" ||
i->opcode == "SUB" ||
i->opcode == "AND" ||
i->opcode == "OR" ||
i->opcode == "EX-OR" ||
i->opcode == "MOV"){
i->advance(ALU);
return true;
}
if(i->opcode == "MUL"){
return true;
}
if(i->opcode == "LOAD" ||
i->opcode == "STORE"){
return true;
}
if(i->opcode == "BAL" ||
i->opcode == "JUMP" ||
i->opcode == "BZ" ||
i->opcode == "BNZ"){
return true;
}
else{
++i;
}
}
}
//Failed to issue instruction
return false;
}
//TODO
//void checkReady(){}
// Flush all entries in the IQ with whose cycle time stamp
// is >= specified time stamp (used when branch is taken)
void IQ::flush(int cycle){
// ASSUMPTION: the entries in the IQ and ROB are
// sorted at all times by their timestamp of creation (c)
// Point an iterator at the start of the IQ
std::deque<Stage>::iterator it = issue_queue.begin();
// Traverse until encountering an entry
// whose cycle timestamp indicates it must be flushed
while(it->c < cycle){
++it;
}
// flush the elements from the current iterator to end:
issue_queue.erase(it, issue_queue.end());
}
<commit_msg>Update issue in IQ<commit_after>/* FILE INFORMATION
File: iq.cpp
Authors: Matthew Cole <mcole8@binghamton.edu>
Brian Gracin <bgracin1@binghamton.edu>
Description: Contains the IQ class, which simulates the operation of a Instruction Queue.
*/
#include <iostream>
#include "iq.h"
IQ::IQ(){
this->initialize();
}
IQ::~IQ(){
}
// Return true if the IQ is empty,
// Return false otherwise
// (Delegates to stl::queue::empty())
bool IQ::isEmpty(){
return issue_queue.empty();
}
//Display the contents of the IQ
//Each entry is a Stage, so we delegate the display logic
void IQ::display(){
std::cout << "Head" << std::endl;
for (auto e : issue_queue){
e.display();
}
std::cout << "Tail" << std::endl;
}
//Initialize the IQ to empty state
void IQ::initialize(){
issue_queue.clear();
}
//Dispatch an instruction to IQ
void IQ::dispatchInst(Stage &stage){
stage.empty = false;
stage.ready = false;
this->issue_queue.push_back(stage);
}
//Forward the value of an R reg that was computed from an FU
//If an instruction is found to have an R reg that is being forwarded
//Set value and valid bit for associated operand fields
void IQ::updateSrc(std::string reg, int val){
if (issue_queue.size() > 0){
for (auto& e : issue_queue){
//Handle forward to arithmatic instructions in IQ
if(e.opcode == "ADD" ||
e.opcode == "SUB" ||
e.opcode == "MUL" ||
e.opcode == "AND" ||
e.opcode == "OR" ||
e.opcode == "EX-OR"){
if(e.operands.at(1) == reg){
e.values.at(1) = val;
e.valids.at(1) = true;
}
if(e.operands.at(2) == reg){
e.values.at(2) = val;
e.valids.at(2) = true;
}
}
//Handle forward to LOAD instruction in IQ
if(e.opcode == "LOAD"){
if(e.operands.at(1) == reg){
e.values.at(1) = val;
e.valids.at(1) = true;
}
}
//Handle forward to branch instructions in IQ
if(e.opcode == "BAL" ||
e.opcode == "JUMP"){
if(e.operands.at(0) == reg){
e.values.at(0) = val;
e.valids.at(0) = true;
}
}
//Handle forward to STORE instructions in IQ
if(e.opcode == "STORE"){
if(e.operands.at(0) == reg){
e.values.at(0) = val;
e.valids.at(0) = true;
}
if(e.operands.at(1) == reg){
e.values.at(1) = val;
e.valids.at(1) = true;
}
}
}
}
}
//TODO
bool issue(Stage* ALU, Stage* MUL, Stage* LSFU, Stage* B){
int numIssued = 0;
//for (auto& e : issue_queue){
for (auto i = this->issue_queue.begin(); i != this->issue_queue.end();){
if (i->isReady()){
if(i->opcode == "ADD" ||
i->opcode == "SUB" ||
i->opcode == "AND" ||
i->opcode == "OR" ||
i->opcode == "EX-OR" ||
i->opcode == "MOV"){
i->advance(ALU1);
this->issue_queue.erase(i);
numIssued++;
}
if(i->opcode == "MUL"){
i->advance(MUL1);
this->issue_queue.erase(i);
numIssued++;
}
if(i->opcode == "LOAD" ||
i->opcode == "STORE"){
i->advance(LSFU1);
this->issue_queue.erase(i);
numIssued++;
}
if(i->opcode == "BAL" ||
i->opcode == "JUMP" ||
i->opcode == "BZ" ||
i->opcode == "BNZ"){
i->advance(B);
this->issue_queue.erase(i);
numIssued++;
}
}
else{
++i;
}
if (numIssued > 2){
return true;
}
}
//Failed to issue instruction
return false;
}
//TODO
//void checkReady(){}
// Flush all entries in the IQ with whose cycle time stamp
// is >= specified time stamp (used when branch is taken)
void IQ::flush(int cycle){
// ASSUMPTION: the entries in the IQ and ROB are
// sorted at all times by their timestamp of creation (c)
// Point an iterator at the start of the IQ
std::deque<Stage>::iterator it = issue_queue.begin();
// Traverse until encountering an entry
// whose cycle timestamp indicates it must be flushed
while(it->c < cycle){
++it;
}
// flush the elements from the current iterator to end:
issue_queue.erase(it, issue_queue.end());
}
<|endoftext|>
|
<commit_before>/**
* Copyright © 2019 IBM Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "host_notifier.hpp"
#include <phosphor-logging/log.hpp>
namespace openpower::pels
{
const auto subscriptionName = "PELHostNotifier";
const size_t maxRetryAttempts = 15;
using namespace phosphor::logging;
HostNotifier::HostNotifier(Repository& repo, DataInterfaceBase& dataIface,
std::unique_ptr<HostInterface> hostIface) :
_repo(repo),
_dataIface(dataIface), _hostIface(std::move(hostIface)),
_retryTimer(_hostIface->getEvent(),
std::bind(std::mem_fn(&HostNotifier::retryTimerExpired), this)),
_hostFullTimer(
_hostIface->getEvent(),
std::bind(std::mem_fn(&HostNotifier::hostFullTimerExpired), this)),
_hostUpTimer(
_hostIface->getEvent(),
std::bind(std::mem_fn(&HostNotifier::hostUpTimerExpired), this))
{
// Subscribe to be told about new PELs.
_repo.subscribeToAdds(subscriptionName,
std::bind(std::mem_fn(&HostNotifier::newLogCallback),
this, std::placeholders::_1));
// Subscribe to be told about deleted PELs.
_repo.subscribeToDeletes(
subscriptionName,
std::bind(std::mem_fn(&HostNotifier::deleteLogCallback), this,
std::placeholders::_1));
// Add any existing PELs to the queue to send them if necessary.
_repo.for_each(std::bind(std::mem_fn(&HostNotifier::addPELToQueue), this,
std::placeholders::_1));
// Subscribe to be told about host state changes.
_dataIface.subscribeToHostStateChange(
subscriptionName,
std::bind(std::mem_fun(&HostNotifier::hostStateChange), this,
std::placeholders::_1));
// Set the function to call when the async reponse is received.
_hostIface->setResponseFunction(
std::bind(std::mem_fn(&HostNotifier::commandResponse), this,
std::placeholders::_1));
// Start sending logs if the host is running
if (!_pelQueue.empty() && _dataIface.isHostUp())
{
log<level::DEBUG>("Host is already up at startup");
_hostUpTimer.restartOnce(_hostIface->getHostUpDelay());
}
}
HostNotifier::~HostNotifier()
{
_repo.unsubscribeFromAdds(subscriptionName);
_dataIface.unsubscribeFromHostStateChange(subscriptionName);
}
void HostNotifier::hostUpTimerExpired()
{
log<level::DEBUG>("Host up timer expired");
doNewLogNotify();
}
bool HostNotifier::addPELToQueue(const PEL& pel)
{
if (enqueueRequired(pel.id()))
{
_pelQueue.push_back(pel.id());
}
// Return false so that Repo::for_each keeps going.
return false;
}
bool HostNotifier::enqueueRequired(uint32_t id) const
{
bool required = true;
Repository::LogID i{Repository::LogID::Pel{id}};
// Manufacturing testing may turn off sending up PELs
if (!_dataIface.getHostPELEnablement())
{
return false;
}
if (auto attributes = _repo.getPELAttributes(i); attributes)
{
auto a = attributes.value().get();
if ((a.hostState == TransmissionState::acked) ||
(a.hostState == TransmissionState::badPEL))
{
required = false;
}
else if (a.actionFlags.test(hiddenFlagBit) &&
(a.hmcState == TransmissionState::acked))
{
required = false;
}
else if (a.actionFlags.test(dontReportToHostFlagBit))
{
required = false;
}
}
else
{
using namespace phosphor::logging;
log<level::ERR>("Host Enqueue: Unable to find PEL ID in repository",
entry("PEL_ID=0x%X", id));
required = false;
}
return required;
}
bool HostNotifier::notifyRequired(uint32_t id) const
{
bool notify = true;
Repository::LogID i{Repository::LogID::Pel{id}};
if (auto attributes = _repo.getPELAttributes(i); attributes)
{
// If already acked by the host, don't send again.
// (A safety check as it shouldn't get to this point.)
auto a = attributes.value().get();
if (a.hostState == TransmissionState::acked)
{
notify = false;
}
else if (a.actionFlags.test(hiddenFlagBit))
{
// If hidden and acked (or will be) acked by the HMC,
// also don't send it. (HMC management can come and
// go at any time)
if ((a.hmcState == TransmissionState::acked) ||
_dataIface.isHMCManaged())
{
notify = false;
}
}
}
else
{
// Must have been deleted since put on the queue.
notify = false;
}
return notify;
}
void HostNotifier::newLogCallback(const PEL& pel)
{
if (!enqueueRequired(pel.id()))
{
return;
}
log<level::DEBUG>("new PEL added to queue", entry("PEL_ID=0x%X", pel.id()));
_pelQueue.push_back(pel.id());
// Notify shouldn't happen if host is down, not up long enough, or full
if (!_dataIface.isHostUp() || _hostFull || _hostUpTimer.isEnabled())
{
return;
}
// Dispatch a command now if there isn't currently a command
// in progress and this is the first log in the queue or it
// previously gave up from a hard failure.
auto inProgress = (_inProgressPEL != 0) || _hostIface->cmdInProgress() ||
_retryTimer.isEnabled();
auto firstPEL = _pelQueue.size() == 1;
auto gaveUp = _retryCount >= maxRetryAttempts;
if (!inProgress && (firstPEL || gaveUp))
{
_retryCount = 0;
// Send a log, but from the event loop, not from here.
scheduleDispatch();
}
}
void HostNotifier::deleteLogCallback(uint32_t id)
{
auto queueIt = std::find(_pelQueue.begin(), _pelQueue.end(), id);
if (queueIt != _pelQueue.end())
{
log<level::DEBUG>("Host notifier removing deleted log from queue");
_pelQueue.erase(queueIt);
}
auto sentIt = std::find(_sentPELs.begin(), _sentPELs.end(), id);
if (sentIt != _sentPELs.end())
{
log<level::DEBUG>("Host notifier removing deleted log from sent list");
_sentPELs.erase(sentIt);
}
// Nothing we can do about this...
if (id == _inProgressPEL)
{
log<level::WARNING>(
"A PEL was deleted while its host notification was in progress",
entry("PEL_ID=0x%X", id));
}
}
void HostNotifier::scheduleDispatch()
{
_dispatcher = std::make_unique<sdeventplus::source::Defer>(
_hostIface->getEvent(), std::bind(std::mem_fn(&HostNotifier::dispatch),
this, std::placeholders::_1));
}
void HostNotifier::dispatch(sdeventplus::source::EventBase& /*source*/)
{
_dispatcher.reset();
doNewLogNotify();
}
void HostNotifier::doNewLogNotify()
{
if (!_dataIface.isHostUp() || _retryTimer.isEnabled() ||
_hostFullTimer.isEnabled())
{
return;
}
if (_retryCount >= maxRetryAttempts)
{
// Give up until a new log comes in.
if (_retryCount == maxRetryAttempts)
{
// If this were to really happen, the PLDM interface
// would be down and isolating that shouldn't left to
// a logging daemon, so just trace. Also, this will start
// trying again when the next new log comes in.
log<level::ERR>(
"PEL Host notifier hit max retry attempts. Giving up for now.",
entry("PEL_ID=0x%X", _pelQueue.front()));
// Tell the host interface object to clean itself up, especially to
// release the PLDM instance ID it's been using.
_hostIface->cancelCmd();
}
return;
}
bool doNotify = false;
uint32_t id = 0;
// Find the PEL to send
while (!doNotify && !_pelQueue.empty())
{
id = _pelQueue.front();
_pelQueue.pop_front();
if (notifyRequired(id))
{
doNotify = true;
}
}
if (doNotify)
{
// Get the size using the repo attributes
Repository::LogID i{Repository::LogID::Pel{id}};
if (auto attributes = _repo.getPELAttributes(i); attributes)
{
auto size = static_cast<size_t>(
std::filesystem::file_size((*attributes).get().path));
log<level::DEBUG>("sendNewLogCmd", entry("PEL_ID=0x%X", id),
entry("PEL_SIZE=%d", size));
auto rc = _hostIface->sendNewLogCmd(id, size);
if (rc == CmdStatus::success)
{
_inProgressPEL = id;
}
else
{
// It failed. Retry
log<level::ERR>("PLDM send failed", entry("PEL_ID=0x%X", id));
_pelQueue.push_front(id);
_inProgressPEL = 0;
_retryTimer.restartOnce(_hostIface->getSendRetryDelay());
}
}
else
{
log<level::ERR>("PEL ID not in repository. Cannot notify host",
entry("PEL_ID=0x%X", id));
}
}
}
void HostNotifier::hostStateChange(bool hostUp)
{
_retryCount = 0;
_hostFull = false;
if (hostUp && !_pelQueue.empty())
{
log<level::DEBUG>("Host state change to on");
_hostUpTimer.restartOnce(_hostIface->getHostUpDelay());
}
else if (!hostUp)
{
log<level::DEBUG>("Host state change to off");
stopCommand();
// Reset the state on any PELs that were sent but not acked back
// to new so they'll get sent again.
for (auto id : _sentPELs)
{
_pelQueue.push_back(id);
_repo.setPELHostTransState(id, TransmissionState::newPEL);
}
_sentPELs.clear();
if (_hostFullTimer.isEnabled())
{
_hostFullTimer.setEnabled(false);
}
if (_hostUpTimer.isEnabled())
{
_hostUpTimer.setEnabled(false);
}
}
}
void HostNotifier::commandResponse(ResponseStatus status)
{
auto id = _inProgressPEL;
_inProgressPEL = 0;
if (status == ResponseStatus::success)
{
log<level::DEBUG>("HostNotifier command response success",
entry("PEL_ID=0x%X", id));
_retryCount = 0;
_sentPELs.push_back(id);
_repo.setPELHostTransState(id, TransmissionState::sent);
// If the host is full, don't send off the next PEL
if (!_hostFull && !_pelQueue.empty())
{
doNewLogNotify();
}
}
else
{
log<level::ERR>("PLDM command response failure",
entry("PEL_ID=0x%X", id));
// Retry
_pelQueue.push_front(id);
_retryTimer.restartOnce(_hostIface->getReceiveRetryDelay());
}
}
void HostNotifier::retryTimerExpired()
{
if (_dataIface.isHostUp())
{
log<level::INFO>("Attempting command retry",
entry("PEL_ID=0x%X", _pelQueue.front()));
_retryCount++;
doNewLogNotify();
}
}
void HostNotifier::hostFullTimerExpired()
{
log<level::DEBUG>("Host full timer expired, trying send again");
doNewLogNotify();
}
void HostNotifier::stopCommand()
{
_retryCount = 0;
if (_inProgressPEL != 0)
{
_pelQueue.push_front(_inProgressPEL);
_inProgressPEL = 0;
}
if (_retryTimer.isEnabled())
{
_retryTimer.setEnabled(false);
}
// Ensure the PLDM instance ID is released
_hostIface->cancelCmd();
}
void HostNotifier::ackPEL(uint32_t id)
{
_repo.setPELHostTransState(id, TransmissionState::acked);
// No longer just 'sent', so remove it from the sent list.
auto sent = std::find(_sentPELs.begin(), _sentPELs.end(), id);
if (sent != _sentPELs.end())
{
_sentPELs.erase(sent);
}
// An ack means the host is no longer full
if (_hostFullTimer.isEnabled())
{
_hostFullTimer.setEnabled(false);
}
if (_hostFull)
{
_hostFull = false;
log<level::DEBUG>("Host previously full, not anymore after this ack");
// Start sending PELs again, from the event loop
if (!_pelQueue.empty())
{
scheduleDispatch();
}
}
}
void HostNotifier::setHostFull(uint32_t id)
{
log<level::INFO>("Received Host full indication", entry("PEL_ID=0x%X", id));
_hostFull = true;
// This PEL needs to get re-sent
auto sent = std::find(_sentPELs.begin(), _sentPELs.end(), id);
if (sent != _sentPELs.end())
{
_sentPELs.erase(sent);
_repo.setPELHostTransState(id, TransmissionState::newPEL);
if (std::find(_pelQueue.begin(), _pelQueue.end(), id) ==
_pelQueue.end())
{
_pelQueue.push_front(id);
}
}
// The only PELs that will be sent when the
// host is full is from this timer callback.
if (!_hostFullTimer.isEnabled())
{
log<level::DEBUG>("Starting host full timer");
_hostFullTimer.restartOnce(_hostIface->getHostFullRetryDelay());
}
}
void HostNotifier::setBadPEL(uint32_t id)
{
log<level::ERR>("PEL rejected by the host", entry("PEL_ID=0x%X", id));
auto sent = std::find(_sentPELs.begin(), _sentPELs.end(), id);
if (sent != _sentPELs.end())
{
_sentPELs.erase(sent);
}
_repo.setPELHostTransState(id, TransmissionState::badPEL);
}
} // namespace openpower::pels
<commit_msg>PEL: Remove use of deprecated mem_fun<commit_after>/**
* Copyright © 2019 IBM Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "host_notifier.hpp"
#include <phosphor-logging/log.hpp>
namespace openpower::pels
{
const auto subscriptionName = "PELHostNotifier";
const size_t maxRetryAttempts = 15;
using namespace phosphor::logging;
HostNotifier::HostNotifier(Repository& repo, DataInterfaceBase& dataIface,
std::unique_ptr<HostInterface> hostIface) :
_repo(repo),
_dataIface(dataIface), _hostIface(std::move(hostIface)),
_retryTimer(_hostIface->getEvent(),
std::bind(std::mem_fn(&HostNotifier::retryTimerExpired), this)),
_hostFullTimer(
_hostIface->getEvent(),
std::bind(std::mem_fn(&HostNotifier::hostFullTimerExpired), this)),
_hostUpTimer(
_hostIface->getEvent(),
std::bind(std::mem_fn(&HostNotifier::hostUpTimerExpired), this))
{
// Subscribe to be told about new PELs.
_repo.subscribeToAdds(subscriptionName,
std::bind(std::mem_fn(&HostNotifier::newLogCallback),
this, std::placeholders::_1));
// Subscribe to be told about deleted PELs.
_repo.subscribeToDeletes(
subscriptionName,
std::bind(std::mem_fn(&HostNotifier::deleteLogCallback), this,
std::placeholders::_1));
// Add any existing PELs to the queue to send them if necessary.
_repo.for_each(std::bind(std::mem_fn(&HostNotifier::addPELToQueue), this,
std::placeholders::_1));
// Subscribe to be told about host state changes.
_dataIface.subscribeToHostStateChange(
subscriptionName, std::bind(std::mem_fn(&HostNotifier::hostStateChange),
this, std::placeholders::_1));
// Set the function to call when the async reponse is received.
_hostIface->setResponseFunction(
std::bind(std::mem_fn(&HostNotifier::commandResponse), this,
std::placeholders::_1));
// Start sending logs if the host is running
if (!_pelQueue.empty() && _dataIface.isHostUp())
{
log<level::DEBUG>("Host is already up at startup");
_hostUpTimer.restartOnce(_hostIface->getHostUpDelay());
}
}
HostNotifier::~HostNotifier()
{
_repo.unsubscribeFromAdds(subscriptionName);
_dataIface.unsubscribeFromHostStateChange(subscriptionName);
}
void HostNotifier::hostUpTimerExpired()
{
log<level::DEBUG>("Host up timer expired");
doNewLogNotify();
}
bool HostNotifier::addPELToQueue(const PEL& pel)
{
if (enqueueRequired(pel.id()))
{
_pelQueue.push_back(pel.id());
}
// Return false so that Repo::for_each keeps going.
return false;
}
bool HostNotifier::enqueueRequired(uint32_t id) const
{
bool required = true;
Repository::LogID i{Repository::LogID::Pel{id}};
// Manufacturing testing may turn off sending up PELs
if (!_dataIface.getHostPELEnablement())
{
return false;
}
if (auto attributes = _repo.getPELAttributes(i); attributes)
{
auto a = attributes.value().get();
if ((a.hostState == TransmissionState::acked) ||
(a.hostState == TransmissionState::badPEL))
{
required = false;
}
else if (a.actionFlags.test(hiddenFlagBit) &&
(a.hmcState == TransmissionState::acked))
{
required = false;
}
else if (a.actionFlags.test(dontReportToHostFlagBit))
{
required = false;
}
}
else
{
using namespace phosphor::logging;
log<level::ERR>("Host Enqueue: Unable to find PEL ID in repository",
entry("PEL_ID=0x%X", id));
required = false;
}
return required;
}
bool HostNotifier::notifyRequired(uint32_t id) const
{
bool notify = true;
Repository::LogID i{Repository::LogID::Pel{id}};
if (auto attributes = _repo.getPELAttributes(i); attributes)
{
// If already acked by the host, don't send again.
// (A safety check as it shouldn't get to this point.)
auto a = attributes.value().get();
if (a.hostState == TransmissionState::acked)
{
notify = false;
}
else if (a.actionFlags.test(hiddenFlagBit))
{
// If hidden and acked (or will be) acked by the HMC,
// also don't send it. (HMC management can come and
// go at any time)
if ((a.hmcState == TransmissionState::acked) ||
_dataIface.isHMCManaged())
{
notify = false;
}
}
}
else
{
// Must have been deleted since put on the queue.
notify = false;
}
return notify;
}
void HostNotifier::newLogCallback(const PEL& pel)
{
if (!enqueueRequired(pel.id()))
{
return;
}
log<level::DEBUG>("new PEL added to queue", entry("PEL_ID=0x%X", pel.id()));
_pelQueue.push_back(pel.id());
// Notify shouldn't happen if host is down, not up long enough, or full
if (!_dataIface.isHostUp() || _hostFull || _hostUpTimer.isEnabled())
{
return;
}
// Dispatch a command now if there isn't currently a command
// in progress and this is the first log in the queue or it
// previously gave up from a hard failure.
auto inProgress = (_inProgressPEL != 0) || _hostIface->cmdInProgress() ||
_retryTimer.isEnabled();
auto firstPEL = _pelQueue.size() == 1;
auto gaveUp = _retryCount >= maxRetryAttempts;
if (!inProgress && (firstPEL || gaveUp))
{
_retryCount = 0;
// Send a log, but from the event loop, not from here.
scheduleDispatch();
}
}
void HostNotifier::deleteLogCallback(uint32_t id)
{
auto queueIt = std::find(_pelQueue.begin(), _pelQueue.end(), id);
if (queueIt != _pelQueue.end())
{
log<level::DEBUG>("Host notifier removing deleted log from queue");
_pelQueue.erase(queueIt);
}
auto sentIt = std::find(_sentPELs.begin(), _sentPELs.end(), id);
if (sentIt != _sentPELs.end())
{
log<level::DEBUG>("Host notifier removing deleted log from sent list");
_sentPELs.erase(sentIt);
}
// Nothing we can do about this...
if (id == _inProgressPEL)
{
log<level::WARNING>(
"A PEL was deleted while its host notification was in progress",
entry("PEL_ID=0x%X", id));
}
}
void HostNotifier::scheduleDispatch()
{
_dispatcher = std::make_unique<sdeventplus::source::Defer>(
_hostIface->getEvent(), std::bind(std::mem_fn(&HostNotifier::dispatch),
this, std::placeholders::_1));
}
void HostNotifier::dispatch(sdeventplus::source::EventBase& /*source*/)
{
_dispatcher.reset();
doNewLogNotify();
}
void HostNotifier::doNewLogNotify()
{
if (!_dataIface.isHostUp() || _retryTimer.isEnabled() ||
_hostFullTimer.isEnabled())
{
return;
}
if (_retryCount >= maxRetryAttempts)
{
// Give up until a new log comes in.
if (_retryCount == maxRetryAttempts)
{
// If this were to really happen, the PLDM interface
// would be down and isolating that shouldn't left to
// a logging daemon, so just trace. Also, this will start
// trying again when the next new log comes in.
log<level::ERR>(
"PEL Host notifier hit max retry attempts. Giving up for now.",
entry("PEL_ID=0x%X", _pelQueue.front()));
// Tell the host interface object to clean itself up, especially to
// release the PLDM instance ID it's been using.
_hostIface->cancelCmd();
}
return;
}
bool doNotify = false;
uint32_t id = 0;
// Find the PEL to send
while (!doNotify && !_pelQueue.empty())
{
id = _pelQueue.front();
_pelQueue.pop_front();
if (notifyRequired(id))
{
doNotify = true;
}
}
if (doNotify)
{
// Get the size using the repo attributes
Repository::LogID i{Repository::LogID::Pel{id}};
if (auto attributes = _repo.getPELAttributes(i); attributes)
{
auto size = static_cast<size_t>(
std::filesystem::file_size((*attributes).get().path));
log<level::DEBUG>("sendNewLogCmd", entry("PEL_ID=0x%X", id),
entry("PEL_SIZE=%d", size));
auto rc = _hostIface->sendNewLogCmd(id, size);
if (rc == CmdStatus::success)
{
_inProgressPEL = id;
}
else
{
// It failed. Retry
log<level::ERR>("PLDM send failed", entry("PEL_ID=0x%X", id));
_pelQueue.push_front(id);
_inProgressPEL = 0;
_retryTimer.restartOnce(_hostIface->getSendRetryDelay());
}
}
else
{
log<level::ERR>("PEL ID not in repository. Cannot notify host",
entry("PEL_ID=0x%X", id));
}
}
}
void HostNotifier::hostStateChange(bool hostUp)
{
_retryCount = 0;
_hostFull = false;
if (hostUp && !_pelQueue.empty())
{
log<level::DEBUG>("Host state change to on");
_hostUpTimer.restartOnce(_hostIface->getHostUpDelay());
}
else if (!hostUp)
{
log<level::DEBUG>("Host state change to off");
stopCommand();
// Reset the state on any PELs that were sent but not acked back
// to new so they'll get sent again.
for (auto id : _sentPELs)
{
_pelQueue.push_back(id);
_repo.setPELHostTransState(id, TransmissionState::newPEL);
}
_sentPELs.clear();
if (_hostFullTimer.isEnabled())
{
_hostFullTimer.setEnabled(false);
}
if (_hostUpTimer.isEnabled())
{
_hostUpTimer.setEnabled(false);
}
}
}
void HostNotifier::commandResponse(ResponseStatus status)
{
auto id = _inProgressPEL;
_inProgressPEL = 0;
if (status == ResponseStatus::success)
{
log<level::DEBUG>("HostNotifier command response success",
entry("PEL_ID=0x%X", id));
_retryCount = 0;
_sentPELs.push_back(id);
_repo.setPELHostTransState(id, TransmissionState::sent);
// If the host is full, don't send off the next PEL
if (!_hostFull && !_pelQueue.empty())
{
doNewLogNotify();
}
}
else
{
log<level::ERR>("PLDM command response failure",
entry("PEL_ID=0x%X", id));
// Retry
_pelQueue.push_front(id);
_retryTimer.restartOnce(_hostIface->getReceiveRetryDelay());
}
}
void HostNotifier::retryTimerExpired()
{
if (_dataIface.isHostUp())
{
log<level::INFO>("Attempting command retry",
entry("PEL_ID=0x%X", _pelQueue.front()));
_retryCount++;
doNewLogNotify();
}
}
void HostNotifier::hostFullTimerExpired()
{
log<level::DEBUG>("Host full timer expired, trying send again");
doNewLogNotify();
}
void HostNotifier::stopCommand()
{
_retryCount = 0;
if (_inProgressPEL != 0)
{
_pelQueue.push_front(_inProgressPEL);
_inProgressPEL = 0;
}
if (_retryTimer.isEnabled())
{
_retryTimer.setEnabled(false);
}
// Ensure the PLDM instance ID is released
_hostIface->cancelCmd();
}
void HostNotifier::ackPEL(uint32_t id)
{
_repo.setPELHostTransState(id, TransmissionState::acked);
// No longer just 'sent', so remove it from the sent list.
auto sent = std::find(_sentPELs.begin(), _sentPELs.end(), id);
if (sent != _sentPELs.end())
{
_sentPELs.erase(sent);
}
// An ack means the host is no longer full
if (_hostFullTimer.isEnabled())
{
_hostFullTimer.setEnabled(false);
}
if (_hostFull)
{
_hostFull = false;
log<level::DEBUG>("Host previously full, not anymore after this ack");
// Start sending PELs again, from the event loop
if (!_pelQueue.empty())
{
scheduleDispatch();
}
}
}
void HostNotifier::setHostFull(uint32_t id)
{
log<level::INFO>("Received Host full indication", entry("PEL_ID=0x%X", id));
_hostFull = true;
// This PEL needs to get re-sent
auto sent = std::find(_sentPELs.begin(), _sentPELs.end(), id);
if (sent != _sentPELs.end())
{
_sentPELs.erase(sent);
_repo.setPELHostTransState(id, TransmissionState::newPEL);
if (std::find(_pelQueue.begin(), _pelQueue.end(), id) ==
_pelQueue.end())
{
_pelQueue.push_front(id);
}
}
// The only PELs that will be sent when the
// host is full is from this timer callback.
if (!_hostFullTimer.isEnabled())
{
log<level::DEBUG>("Starting host full timer");
_hostFullTimer.restartOnce(_hostIface->getHostFullRetryDelay());
}
}
void HostNotifier::setBadPEL(uint32_t id)
{
log<level::ERR>("PEL rejected by the host", entry("PEL_ID=0x%X", id));
auto sent = std::find(_sentPELs.begin(), _sentPELs.end(), id);
if (sent != _sentPELs.end())
{
_sentPELs.erase(sent);
}
_repo.setPELHostTransState(id, TransmissionState::badPEL);
}
} // namespace openpower::pels
<|endoftext|>
|
<commit_before>/* Copyright 2014 Peter Goodman, all rights reserved. */
#define GRANARY_INTERNAL
#include "granary/base/base.h"
#include "granary/driver/xed2-intel64/xed.h"
#include "granary/register/register.h"
#include "granary/breakpoint.h"
namespace granary {
// See `http://sandpile.org/x86/gpr.htm` for more details on general-purpose
// registers in x86-64.
enum {
LOW_BYTE = 0x1,
BYTE_2 = 0x2,
LOW_2_BYTES = 0x3,
LOW_4_BYTES = 0xF,
ALL_8_BYTES = 0xFF,
HIGH_6_BYTES = 0xFC,
HIGH_7_BYTES = 0xFE,
HIGH_6_LOW_1_BYTE = 0xFD
};
// Convert an architectural register into a virtual register.
void VirtualRegister::DecodeArchRegister(uint64_t reg_) {
value = 0; // Reset.
auto reg = static_cast<xed_reg_enum_t>(reg_);
auto widest_reg = xed_get_largest_enclosing_register(reg);
num_bytes = static_cast<uint8_t>(xed_get_register_width_bits64(reg) / 8);
// Non-general-purpose registers are treated as "fixed" architectural
// registers.
if (XED_REG_RAX > widest_reg || XED_REG_R15 < widest_reg) {
kind = VR_KIND_ARCH_FIXED;
reg_num = static_cast<decltype(reg_num)>(reg_);
return;
}
// General-purpose registers are disambiguated in terms of their "widest"
// enclosing register, and then specialized in terms of their width and which
// bytes are actually named by the register.
kind = VR_KIND_ARCH_VIRTUAL;
reg_num = widest_reg - XED_REG_RAX;
if (XED_REG_RSP <= widest_reg) {
reg_num -= 1; // Directly map registers to indexes.
}
switch (reg) {
case XED_REG_AX: case XED_REG_CX: case XED_REG_DX: case XED_REG_BX:
case XED_REG_BP: case XED_REG_SI: case XED_REG_DI: case XED_REG_R8W:
case XED_REG_R9W: case XED_REG_R10W: case XED_REG_R11W: case XED_REG_R12W:
case XED_REG_R13W: case XED_REG_R14W: case XED_REG_R15W:
byte_mask = LOW_2_BYTES;
preserved_byte_mask = HIGH_6_BYTES;
return;
case XED_REG_EAX: case XED_REG_ECX: case XED_REG_EDX: case XED_REG_EBX:
case XED_REG_EBP: case XED_REG_ESI: case XED_REG_EDI: case XED_REG_R8D:
case XED_REG_R9D: case XED_REG_R10D: case XED_REG_R11D: case XED_REG_R12D:
case XED_REG_R13D: case XED_REG_R14D: case XED_REG_R15D:
byte_mask = LOW_4_BYTES; // 4 high-order bytes are zero extended.
return;
case XED_REG_RAX: case XED_REG_RCX: case XED_REG_RDX: case XED_REG_RBX:
case XED_REG_RBP: case XED_REG_RSI: case XED_REG_RDI: case XED_REG_R8:
case XED_REG_R9: case XED_REG_R10: case XED_REG_R11: case XED_REG_R12:
case XED_REG_R13: case XED_REG_R14: case XED_REG_R15:
byte_mask = ALL_8_BYTES;
return;
case XED_REG_AL: case XED_REG_CL: case XED_REG_DL: case XED_REG_BL:
case XED_REG_BPL: case XED_REG_SIL: case XED_REG_DIL: case XED_REG_R8B:
case XED_REG_R9B: case XED_REG_R10B: case XED_REG_R11B: case XED_REG_R12B:
case XED_REG_R13B: case XED_REG_R14B: case XED_REG_R15B:
byte_mask = LOW_BYTE;
preserved_byte_mask = HIGH_7_BYTES;
return;
case XED_REG_AH: case XED_REG_CH: case XED_REG_DH: case XED_REG_BH:
byte_mask = BYTE_2;
preserved_byte_mask = HIGH_6_LOW_1_BYTE;
return;
default: GRANARY_ASSERT(false);
}
}
// Convert a virtual register into its associated architectural register.
uint64_t VirtualRegister::EncodeArchRegister(void) const {
if (VR_KIND_ARCH_FIXED == kind) {
return static_cast<uint64_t>(reg_num);
} else if (VR_KIND_ARCH_VIRTUAL != kind) {
return XED_REG_INVALID;
}
// Map register numbers to XED registers.
auto widest_reg = static_cast<xed_reg_enum_t>(reg_num + XED_REG_RAX);
if (XED_REG_RSP <= widest_reg) {
widest_reg = static_cast<xed_reg_enum_t>(static_cast<int>(widest_reg) + 1);
}
switch (byte_mask) {
case LOW_2_BYTES: return widest_reg - (XED_REG_RAX - XED_REG_AX);
case LOW_4_BYTES: return widest_reg - (XED_REG_RAX - XED_REG_EAX);
case ALL_8_BYTES: return widest_reg;
case LOW_BYTE: return widest_reg + (XED_REG_AL - XED_REG_RAX);
case BYTE_2: return widest_reg + (XED_REG_AH - XED_REG_RAX);
default: return XED_REG_INVALID;
}
}
} // namespace granary
<commit_msg>Minor fix to decoding RSP as an architectural register.<commit_after>/* Copyright 2014 Peter Goodman, all rights reserved. */
#define GRANARY_INTERNAL
#include "granary/base/base.h"
#include "granary/driver/xed2-intel64/xed.h"
#include "granary/register/register.h"
#include "granary/breakpoint.h"
namespace granary {
// See `http://sandpile.org/x86/gpr.htm` for more details on general-purpose
// registers in x86-64.
enum {
LOW_BYTE = 0x1,
BYTE_2 = 0x2,
LOW_2_BYTES = 0x3,
LOW_4_BYTES = 0xF,
ALL_8_BYTES = 0xFF,
HIGH_6_BYTES = 0xFC,
HIGH_7_BYTES = 0xFE,
HIGH_6_LOW_1_BYTE = 0xFD
};
// Convert an architectural register into a virtual register.
void VirtualRegister::DecodeArchRegister(uint64_t reg_) {
value = 0; // Reset.
auto reg = static_cast<xed_reg_enum_t>(reg_);
auto widest_reg = xed_get_largest_enclosing_register(reg);
num_bytes = static_cast<uint8_t>(xed_get_register_width_bits64(reg) / 8);
// Non-general-purpose registers are treated as "fixed" architectural
// registers.
if (XED_REG_RAX > widest_reg || XED_REG_R15 < widest_reg ||
XED_REG_RSP == widest_reg) {
kind = VR_KIND_ARCH_FIXED;
reg_num = static_cast<decltype(reg_num)>(reg_);
return;
}
// General-purpose registers are disambiguated in terms of their "widest"
// enclosing register, and then specialized in terms of their width and which
// bytes are actually named by the register.
kind = VR_KIND_ARCH_VIRTUAL;
reg_num = widest_reg - XED_REG_RAX;
if (XED_REG_RSP <= widest_reg) {
reg_num -= 1; // Directly map registers to indexes.
}
switch (reg) {
case XED_REG_AX: case XED_REG_CX: case XED_REG_DX: case XED_REG_BX:
case XED_REG_BP: case XED_REG_SI: case XED_REG_DI: case XED_REG_R8W:
case XED_REG_R9W: case XED_REG_R10W: case XED_REG_R11W: case XED_REG_R12W:
case XED_REG_R13W: case XED_REG_R14W: case XED_REG_R15W:
byte_mask = LOW_2_BYTES;
preserved_byte_mask = HIGH_6_BYTES;
return;
case XED_REG_EAX: case XED_REG_ECX: case XED_REG_EDX: case XED_REG_EBX:
case XED_REG_EBP: case XED_REG_ESI: case XED_REG_EDI: case XED_REG_R8D:
case XED_REG_R9D: case XED_REG_R10D: case XED_REG_R11D: case XED_REG_R12D:
case XED_REG_R13D: case XED_REG_R14D: case XED_REG_R15D:
byte_mask = LOW_4_BYTES; // 4 high-order bytes are zero extended.
return;
case XED_REG_RAX: case XED_REG_RCX: case XED_REG_RDX: case XED_REG_RBX:
case XED_REG_RBP: case XED_REG_RSI: case XED_REG_RDI: case XED_REG_R8:
case XED_REG_R9: case XED_REG_R10: case XED_REG_R11: case XED_REG_R12:
case XED_REG_R13: case XED_REG_R14: case XED_REG_R15:
byte_mask = ALL_8_BYTES;
return;
case XED_REG_AL: case XED_REG_CL: case XED_REG_DL: case XED_REG_BL:
case XED_REG_BPL: case XED_REG_SIL: case XED_REG_DIL: case XED_REG_R8B:
case XED_REG_R9B: case XED_REG_R10B: case XED_REG_R11B: case XED_REG_R12B:
case XED_REG_R13B: case XED_REG_R14B: case XED_REG_R15B:
byte_mask = LOW_BYTE;
preserved_byte_mask = HIGH_7_BYTES;
return;
case XED_REG_AH: case XED_REG_CH: case XED_REG_DH: case XED_REG_BH:
byte_mask = BYTE_2;
preserved_byte_mask = HIGH_6_LOW_1_BYTE;
return;
default: GRANARY_ASSERT(false);
}
}
// Convert a virtual register into its associated architectural register.
uint64_t VirtualRegister::EncodeArchRegister(void) const {
if (VR_KIND_ARCH_FIXED == kind) {
return static_cast<uint64_t>(reg_num);
} else if (VR_KIND_ARCH_VIRTUAL != kind) {
return XED_REG_INVALID;
}
// Map register numbers to XED registers.
auto widest_reg = static_cast<xed_reg_enum_t>(reg_num + XED_REG_RAX);
if (XED_REG_RSP <= widest_reg) {
widest_reg = static_cast<xed_reg_enum_t>(static_cast<int>(widest_reg) + 1);
}
switch (byte_mask) {
case LOW_2_BYTES: return widest_reg - (XED_REG_RAX - XED_REG_AX);
case LOW_4_BYTES: return widest_reg - (XED_REG_RAX - XED_REG_EAX);
case ALL_8_BYTES: return widest_reg;
case LOW_BYTE: return widest_reg + (XED_REG_AL - XED_REG_RAX);
case BYTE_2: return widest_reg + (XED_REG_AH - XED_REG_RAX);
default: return XED_REG_INVALID;
}
}
} // namespace granary
<|endoftext|>
|
<commit_before>// fluxbox-remote.cc
// Copyright (c) 2007 Fluxbox Team (fluxgen at fluxbox dot org)
//
// 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 <X11/Xlib.h>
#include <X11/Xatom.h>
#include <X11/Xutil.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
bool g_gotError = false;
static int HandleIPCError(Display *disp, XErrorEvent*ptr)
{
// ptr->error_code contains the actual error flags
g_gotError = true;
return( 0 );
}
typedef int (*xerror_cb_t)(Display*,XErrorEvent*);
int main(int argc, char **argv) {
int rc;
Display* disp;
Window root;
Atom atom_utf8;
Atom atom_fbcmd;
Atom atom_result;
xerror_cb_t error_cb;
char* cmd;
if (argc <= 1) {
printf("fluxbox-remote <fluxbox-command>\n");
return EXIT_SUCCESS;
}
disp = XOpenDisplay(NULL);
if (!disp) {
perror("error, can't open display.");
return rc;
}
cmd = argv[1];
atom_utf8 = XInternAtom(disp, "UTF8_STRING", False);
atom_fbcmd = XInternAtom(disp, "_FLUXBOX_ACTION", False);
atom_result = XInternAtom(disp, "_FLUXBOX_ACTION_RESULT", False);
root = DefaultRootWindow(disp);
// assign the custom handler, clear the flag, sync the data,
// then check it for success/failure
error_cb = XSetErrorHandler(HandleIPCError);
if (strcmp(cmd, "result") == 0) {
XTextProperty text_prop;
if (XGetTextProperty(disp, root, &text_prop, atom_result) != 0
&& text_prop.value > 0
&& text_prop.nitems > 0) {
printf("%s", text_prop.value);
XFree(text_prop.value);
}
} else {
XChangeProperty(disp, root, atom_fbcmd,
XA_STRING, 8, PropModeReplace,
(unsigned char *)cmd, strlen(cmd));
XSync(disp, false);
}
rc = (g_gotError ? EXIT_FAILURE : EXIT_SUCCESS);
XSetErrorHandler(error_cb);
XCloseDisplay(disp);
return rc;
}
<commit_msg>Returning EXIT_FAILURE on exit in fluxbox-remote.<commit_after>// fluxbox-remote.cc
// Copyright (c) 2007 Fluxbox Team (fluxgen at fluxbox dot org)
//
// 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 <X11/Xlib.h>
#include <X11/Xatom.h>
#include <X11/Xutil.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
bool g_gotError = false;
static int HandleIPCError(Display *disp, XErrorEvent*ptr)
{
// ptr->error_code contains the actual error flags
g_gotError = true;
return( 0 );
}
typedef int (*xerror_cb_t)(Display*,XErrorEvent*);
int main(int argc, char **argv) {
int rc;
Display* disp;
Window root;
Atom atom_utf8;
Atom atom_fbcmd;
Atom atom_result;
xerror_cb_t error_cb;
char* cmd;
if (argc <= 1) {
printf("fluxbox-remote <fluxbox-command>\n");
return EXIT_SUCCESS;
}
disp = XOpenDisplay(NULL);
if (!disp) {
perror("error, can't open display.");
rc = EXIT_FAILURE;
return rc;
}
cmd = argv[1];
atom_utf8 = XInternAtom(disp, "UTF8_STRING", False);
atom_fbcmd = XInternAtom(disp, "_FLUXBOX_ACTION", False);
atom_result = XInternAtom(disp, "_FLUXBOX_ACTION_RESULT", False);
root = DefaultRootWindow(disp);
// assign the custom handler, clear the flag, sync the data,
// then check it for success/failure
error_cb = XSetErrorHandler(HandleIPCError);
if (strcmp(cmd, "result") == 0) {
XTextProperty text_prop;
if (XGetTextProperty(disp, root, &text_prop, atom_result) != 0
&& text_prop.value > 0
&& text_prop.nitems > 0) {
printf("%s", text_prop.value);
XFree(text_prop.value);
}
} else {
XChangeProperty(disp, root, atom_fbcmd,
XA_STRING, 8, PropModeReplace,
(unsigned char *)cmd, strlen(cmd));
XSync(disp, false);
}
rc = (g_gotError ? EXIT_FAILURE : EXIT_SUCCESS);
XSetErrorHandler(error_cb);
XCloseDisplay(disp);
return rc;
}
<|endoftext|>
|
<commit_before>#pragma warning(disable:4996)
#include "stdafx.h"
#include <atlframe.h>
#include <atlctrls.h>
#include <atldlgs.h>
#include <atlmisc.h>
#include <atlsplit.h>
#include <atlctrlx.h>
#include "MainFrame.h"
#include "SplashWnd.h"
CAppModule _Module;
int Run(LPTSTR lpstrCmdLine=NULL,int nCmdShow=SW_SHOWDEFAULT)
{
char *Filename=NULL;
int argc;
WCHAR *wcCommandLine;
LPWSTR *argw;
wcCommandLine=GetCommandLineW();
argw=CommandLineToArgvW(wcCommandLine,&argc);
if(argw && argc>1)
{
int BuffSize=WideCharToMultiByte(CP_ACP,WC_COMPOSITECHECK,argw[1],-1,NULL,0,NULL,NULL);
if(BuffSize>0)
{
Filename=(char *)GlobalAlloc(LPTR,BuffSize);
if(Filename)
WideCharToMultiByte(CP_ACP,WC_COMPOSITECHECK,argw[1],BuffSize*sizeof(WCHAR),Filename,BuffSize,NULL,NULL);
}
}
CMessageLoop theLoop;
_Module.AddMessageLoop(&theLoop);
CMainFrame wndMain;
//size of window to create
CRect rc=CRect(0,0,800,600);
if(wndMain.CreateEx(NULL,rc) == NULL)
{
ATLTRACE(_T("Main window creation failed!\n"));
return 0;
}
/////////////////////////////////////////////
//center and show main window
wndMain.CenterWindow();
wndMain.ShowWindow(nCmdShow);
new CSplashWnd(IDB_SPLASH,3000,wndMain.m_hWnd);
if(Filename)
wndMain.SetDatabaseFilename(Filename);
int nRet=theLoop.Run();
_Module.RemoveMessageLoop();
return nRet;
}
int WINAPI _tWinMain(HINSTANCE hInstance,HINSTANCE,LPTSTR lpstrCmdLine,int nCmdShow)
{
HRESULT hRes=::CoInitialize(NULL);
ATLASSERT(SUCCEEDED(hRes));
::DefWindowProc(NULL,0,0,0L);
hRes=_Module.Init(NULL,hInstance);
ATLASSERT(SUCCEEDED(hRes));
int nRet=Run(lpstrCmdLine,nCmdShow);
_Module.Term();
::CoUninitialize();
return nRet;
}
<commit_msg>Removed DebugLevel Global Variable From UI Part<commit_after>#pragma warning(disable:4996)
#include "stdafx.h"
#include <atlframe.h>
#include <atlctrls.h>
#include <atldlgs.h>
#include <atlmisc.h>
#include <atlsplit.h>
#include <atlctrlx.h>
#include "MainFrame.h"
#include "SplashWnd.h"
CAppModule _Module;
int Run(LPTSTR lpstrCmdLine=NULL,int nCmdShow=SW_SHOWDEFAULT)
{
char *Filename=NULL;
int argc;
WCHAR *wcCommandLine;
LPWSTR *argw;
wcCommandLine=GetCommandLineW();
argw=CommandLineToArgvW(wcCommandLine,&argc);
if(argw && argc>1)
{
int BuffSize=WideCharToMultiByte(CP_ACP,WC_COMPOSITECHECK,argw[1],-1,NULL,0,NULL,NULL);
if(BuffSize>0)
{
Filename=(char *)GlobalAlloc(LPTR,BuffSize);
if(Filename)
WideCharToMultiByte(CP_ACP,WC_COMPOSITECHECK,argw[1],BuffSize*sizeof(WCHAR),Filename,BuffSize,NULL,NULL);
}
}
CMessageLoop theLoop;
_Module.AddMessageLoop(&theLoop);
CMainFrame wndMain;
//size of window to create
CRect rc=CRect(0,0,800,600);
if(wndMain.CreateEx(NULL,rc) == NULL)
{
ATLTRACE(_T("Main window creation failed!\n"));
return 0;
}
/////////////////////////////////////////////
//center and show main window
wndMain.CenterWindow();
wndMain.ShowWindow(nCmdShow);
new CSplashWnd(IDB_SPLASH,3000,wndMain.m_hWnd);
if(Filename)
wndMain.SetDatabaseFilename(Filename);
int nRet=theLoop.Run();
_Module.RemoveMessageLoop();
return nRet;
}
int WINAPI _tWinMain(HINSTANCE hInstance,HINSTANCE,LPTSTR lpstrCmdLine,int nCmdShow)
{
HRESULT hRes=::CoInitialize(NULL);
ATLASSERT(SUCCEEDED(hRes));
::DefWindowProc(NULL,0,0,0L);
hRes=_Module.Init(NULL,hInstance);
ATLASSERT(SUCCEEDED(hRes));
int nRet=Run(lpstrCmdLine,nCmdShow);
_Module.Term();
::CoUninitialize();
return nRet;
}
<|endoftext|>
|
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include <basegfx/polygon/b2dpolygon.hxx>
#include <drawinglayer/primitive2d/polygonprimitive2d.hxx>
#include <drawinglayer/primitive2d/polypolygonprimitive2d.hxx>
#include <drawinglayer/processor2d/baseprocessor2d.hxx>
#include <drawinglayer/processor2d/processorfromoutputdevice.hxx>
#include <sfx2/bindings.hxx>
#include <sfx2/dispatch.hxx>
#include <sfx2/infobar.hxx>
#include <sfx2/objsh.hxx>
#include <sfx2/sfx.hrc>
#include <sfx2/viewsh.hxx>
#include <vcl/svapp.hxx>
#include <vcl/settings.hxx>
using namespace std;
using namespace drawinglayer::geometry;
using namespace drawinglayer::processor2d;
using namespace drawinglayer::primitive2d;
using namespace drawinglayer::attribute;
using namespace drawinglayer::geometry;
namespace
{
class SfxCloseButton : public PushButton
{
public:
SfxCloseButton( vcl::Window* pParent ) : PushButton( pParent, 0 )
{
}
virtual ~SfxCloseButton( ) { }
virtual void Paint( const Rectangle& rRect ) SAL_OVERRIDE;
};
void SfxCloseButton::Paint( const Rectangle& )
{
const ViewInformation2D aNewViewInfos;
const unique_ptr<BaseProcessor2D> pProcessor(
createBaseProcessor2DFromOutputDevice(*this, aNewViewInfos));
const Rectangle aRect( Rectangle( Point( 0, 0 ), PixelToLogic( GetSizePixel() ) ) );
Primitive2DSequence aSeq( 2 );
basegfx::BColor aLightColor( 1.0, 1.0, 191.0 / 255.0 );
basegfx::BColor aDarkColor( 217.0 / 255.0, 217.0 / 255.0, 78.0 / 255.0 );
const StyleSettings& rSettings = Application::GetSettings().GetStyleSettings();
if ( rSettings.GetHighContrastMode() )
{
aLightColor = rSettings.GetLightColor( ).getBColor( );
aDarkColor = rSettings.GetDialogTextColor( ).getBColor( );
}
// Light background
basegfx::B2DPolygon aPolygon;
aPolygon.append( basegfx::B2DPoint( aRect.Left( ), aRect.Top( ) ) );
aPolygon.append( basegfx::B2DPoint( aRect.Right( ), aRect.Top( ) ) );
aPolygon.append( basegfx::B2DPoint( aRect.Right( ), aRect.Bottom( ) ) );
aPolygon.append( basegfx::B2DPoint( aRect.Left( ), aRect.Bottom( ) ) );
aPolygon.setClosed( true );
PolyPolygonColorPrimitive2D* pBack = new PolyPolygonColorPrimitive2D(
basegfx::B2DPolyPolygon( aPolygon ), aLightColor );
aSeq[0] = pBack;
LineAttribute aLineAttribute(aDarkColor, 2.0);
// Cross
basegfx::B2DPolyPolygon aCross;
basegfx::B2DPolygon aLine1;
aLine1.append( basegfx::B2DPoint( aRect.Left(), aRect.Top( ) ) );
aLine1.append( basegfx::B2DPoint( aRect.Right(), aRect.Bottom( ) ) );
aCross.append( aLine1 );
basegfx::B2DPolygon aLine2;
aLine2.append( basegfx::B2DPoint( aRect.Right(), aRect.Top( ) ) );
aLine2.append( basegfx::B2DPoint( aRect.Left(), aRect.Bottom( ) ) );
aCross.append( aLine2 );
PolyPolygonStrokePrimitive2D * pCross =
new PolyPolygonStrokePrimitive2D(aCross, aLineAttribute, StrokeAttribute());
aSeq[1] = pCross;
pProcessor->process(aSeq);
}
}
SfxInfoBarWindow::SfxInfoBarWindow( vcl::Window* pParent, const OUString& sId,
const OUString& sMessage, vector<PushButton*> aButtons ) :
Window( pParent, 0 ),
m_sId( sId ),
m_pMessage(new FixedText(this, 0)),
m_pCloseBtn(new SfxCloseButton(this)),
m_aActionBtns()
{
long nWidth = pParent->GetSizePixel().getWidth();
SetPosSizePixel( Point( 0, 0 ), Size( nWidth, 40 ) );
m_pMessage->SetText( sMessage );
m_pMessage->SetBackground( Wallpaper( Color( 255, 255, 191 ) ) );
m_pMessage->Show( );
m_pCloseBtn->SetPosSizePixel( Point( nWidth - 25, 15 ), Size( 10, 10 ) );
m_pCloseBtn->SetClickHdl( LINK( this, SfxInfoBarWindow, CloseHandler ) );
m_pCloseBtn->Show( );
// Reparent the buttons and place them on the right of the bar
vector<PushButton*>::iterator it;
for (it = aButtons.begin(); it != aButtons.end(); ++it)
{
PushButton* pButton = *it;
pButton->SetParent(this);
pButton->Show();
m_aActionBtns.push_back(pButton);
}
Resize();
}
SfxInfoBarWindow::~SfxInfoBarWindow( )
{}
void SfxInfoBarWindow::Paint( const Rectangle& rPaintRect )
{
const ViewInformation2D aNewViewInfos;
const unique_ptr<BaseProcessor2D> pProcessor(
createBaseProcessor2DFromOutputDevice(*this, aNewViewInfos));
const Rectangle aRect( Rectangle( Point( 0, 0 ), PixelToLogic( GetSizePixel() ) ) );
Primitive2DSequence aSeq( 2 );
basegfx::BColor aLightColor( 1.0, 1.0, 191.0 / 255.0 );
basegfx::BColor aDarkColor( 217.0 / 255.0, 217.0 / 255.0, 78.0 / 255.0 );
const StyleSettings& rSettings = Application::GetSettings().GetStyleSettings();
if ( rSettings.GetHighContrastMode() )
{
aLightColor = rSettings.GetLightColor( ).getBColor( );
aDarkColor = rSettings.GetDialogTextColor( ).getBColor( );
}
// Update the label background color
m_pMessage->SetBackground( Wallpaper( Color( aLightColor ) ) );
// Light background
basegfx::B2DPolygon aPolygon;
aPolygon.append( basegfx::B2DPoint( aRect.Left( ), aRect.Top( ) ) );
aPolygon.append( basegfx::B2DPoint( aRect.Right( ), aRect.Top( ) ) );
aPolygon.append( basegfx::B2DPoint( aRect.Right( ), aRect.Bottom( ) ) );
aPolygon.append( basegfx::B2DPoint( aRect.Left( ), aRect.Bottom( ) ) );
aPolygon.setClosed( true );
PolyPolygonColorPrimitive2D* pBack =
new PolyPolygonColorPrimitive2D(basegfx::B2DPolyPolygon(aPolygon), aLightColor);
aSeq[0] = pBack;
LineAttribute aLineAttribute(aDarkColor, 1.0);
// Bottom dark line
basegfx::B2DPolygon aPolygonBottom;
aPolygonBottom.append( basegfx::B2DPoint( aRect.Left(), aRect.Bottom( ) ) );
aPolygonBottom.append( basegfx::B2DPoint( aRect.Right(), aRect.Bottom( ) ) );
PolygonStrokePrimitive2D * pLineBottom =
new PolygonStrokePrimitive2D (aPolygonBottom, aLineAttribute);
aSeq[1] = pLineBottom;
pProcessor->process( aSeq );
Window::Paint( rPaintRect );
}
void SfxInfoBarWindow::Resize()
{
long nWidth = GetSizePixel().getWidth();
m_pCloseBtn->SetPosSizePixel( Point( nWidth - 25, 15 ), Size( 10, 10 ) );
// Reparent the buttons and place them on the right of the bar
long nX = m_pCloseBtn->GetPosPixel( ).getX( ) - 15;
long nBtnGap = 5;
boost::ptr_vector<PushButton>::iterator it;
for (it = m_aActionBtns.begin(); it != m_aActionBtns.end(); ++it)
{
long nBtnWidth = it->GetSizePixel( ).getWidth();
nX -= nBtnWidth;
it->SetPosSizePixel( Point( nX, 5 ), Size( nBtnWidth, 30 ) );
nX -= nBtnGap;
}
m_pMessage->SetPosSizePixel( Point( 10, 10 ), Size( nX - 20, 20 ) );
}
IMPL_LINK_NOARG( SfxInfoBarWindow, CloseHandler )
{
static_cast<SfxInfoBarContainerWindow*>(GetParent())->removeInfoBar( this );
return 0;
}
SfxInfoBarContainerWindow::SfxInfoBarContainerWindow( SfxInfoBarContainerChild* pChildWin ) :
Window( pChildWin->GetParent( ), 0 ),
m_pChildWin( pChildWin ),
m_pInfoBars()
{
}
SfxInfoBarContainerWindow::~SfxInfoBarContainerWindow( )
{
}
void SfxInfoBarContainerWindow::appendInfoBar( const OUString& sId, const OUString& sMessage, vector< PushButton* > aButtons )
{
Size aSize = GetSizePixel( );
SfxInfoBarWindow* pInfoBar = new SfxInfoBarWindow( this, sId, sMessage, aButtons );
pInfoBar->SetPosPixel( Point( 0, aSize.getHeight( ) ) );
pInfoBar->Show( );
m_pInfoBars.push_back( pInfoBar );
long nHeight = pInfoBar->GetSizePixel( ).getHeight( );
aSize.setHeight( aSize.getHeight() + nHeight );
SetSizePixel( aSize );
}
SfxInfoBarWindow* SfxInfoBarContainerWindow::getInfoBar( const OUString& sId )
{
boost::ptr_vector<SfxInfoBarWindow>::iterator it;
for (it = m_pInfoBars.begin(); it != m_pInfoBars.end(); ++it)
{
if (it->getId() == sId)
return &(*it);
}
return NULL;
}
void SfxInfoBarContainerWindow::removeInfoBar( SfxInfoBarWindow* pInfoBar )
{
boost::ptr_vector<SfxInfoBarWindow>::iterator it;
for (it = m_pInfoBars.begin(); it != m_pInfoBars.end(); ++it)
{
if (pInfoBar == &(*it))
{
m_pInfoBars.erase(it);
break;
}
}
long nY = 0;
for (it = m_pInfoBars.begin(); it != m_pInfoBars.end(); ++it)
{
it->SetPosPixel( Point( 0, nY ) );
nY += it->GetSizePixel( ).getHeight( );
}
Size aSize = GetSizePixel( );
aSize.setHeight( nY );
SetSizePixel( aSize );
m_pChildWin->Update( );
}
void SfxInfoBarContainerWindow::Resize( )
{
// Only need to change the width of the infobars
long nWidth = GetSizePixel( ).getWidth( );
boost::ptr_vector<SfxInfoBarWindow>::iterator it;
for (it = m_pInfoBars.begin(); it != m_pInfoBars.end(); ++it)
{
Size aSize = it->GetSizePixel( );
aSize.setWidth( nWidth );
it->SetSizePixel( aSize );
it->Resize( );
}
}
SFX_IMPL_POS_CHILDWINDOW_WITHID( SfxInfoBarContainerChild, SID_INFOBAR, SFX_OBJECTBAR_OBJECT );
SfxInfoBarContainerChild::SfxInfoBarContainerChild( vcl::Window* _pParent, sal_uInt16 nId, SfxBindings* pBindings, SfxChildWinInfo* ) :
SfxChildWindow( _pParent, nId ),
m_pBindings( pBindings )
{
pWindow = new SfxInfoBarContainerWindow( this );
pWindow->SetPosSizePixel( Point( 0, 0 ), Size( _pParent->GetSizePixel( ).getWidth(), 0 ) );
pWindow->Show( );
eChildAlignment = SFX_ALIGN_LOWESTTOP;
}
SfxInfoBarContainerChild::~SfxInfoBarContainerChild( )
{
}
SfxChildWinInfo SfxInfoBarContainerChild::GetInfo( ) const
{
SfxChildWinInfo aInfo = SfxChildWindow::GetInfo();
return aInfo;
}
void SfxInfoBarContainerChild::Update( )
{
// Refresh the frame to take the infobars container height change into account
const sal_uInt16 nId = GetChildWindowId();
SfxViewFrame* pVFrame = m_pBindings->GetDispatcher( )->GetFrame( );
pVFrame->ShowChildWindow( nId );
// Give the focus to the document view
pVFrame->GetWindow().GrabFocusToDocument();
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Cleanup infobar<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include <basegfx/polygon/b2dpolygon.hxx>
#include <drawinglayer/primitive2d/polygonprimitive2d.hxx>
#include <drawinglayer/primitive2d/polypolygonprimitive2d.hxx>
#include <drawinglayer/processor2d/baseprocessor2d.hxx>
#include <drawinglayer/processor2d/processorfromoutputdevice.hxx>
#include <sfx2/bindings.hxx>
#include <sfx2/dispatch.hxx>
#include <sfx2/infobar.hxx>
#include <sfx2/objsh.hxx>
#include <sfx2/sfx.hrc>
#include <sfx2/viewsh.hxx>
#include <vcl/svapp.hxx>
#include <vcl/settings.hxx>
using namespace std;
using namespace drawinglayer::geometry;
using namespace drawinglayer::processor2d;
using namespace drawinglayer::primitive2d;
using namespace drawinglayer::attribute;
using namespace drawinglayer::geometry;
namespace
{
class SfxCloseButton : public PushButton
{
public:
SfxCloseButton( vcl::Window* pParent ) : PushButton( pParent, 0 )
{
}
virtual ~SfxCloseButton( ) { }
virtual void Paint( const Rectangle& rRect ) SAL_OVERRIDE;
};
void SfxCloseButton::Paint( const Rectangle& )
{
const ViewInformation2D aNewViewInfos;
const unique_ptr<BaseProcessor2D> pProcessor(
createBaseProcessor2DFromOutputDevice(*this, aNewViewInfos));
const Rectangle aRect(Point(0, 0), PixelToLogic(GetSizePixel()));
Primitive2DSequence aSeq(2);
basegfx::BColor aLightColor(1.0, 1.0, 191.0 / 255.0);
basegfx::BColor aDarkColor(217.0 / 255.0, 217.0 / 255.0, 78.0 / 255.0);
const StyleSettings& rSettings = Application::GetSettings().GetStyleSettings();
if ( rSettings.GetHighContrastMode() )
{
aLightColor = rSettings.GetLightColor( ).getBColor( );
aDarkColor = rSettings.GetDialogTextColor( ).getBColor( );
}
// Light background
basegfx::B2DPolygon aPolygon;
aPolygon.append( basegfx::B2DPoint( aRect.Left( ), aRect.Top( ) ) );
aPolygon.append( basegfx::B2DPoint( aRect.Right( ), aRect.Top( ) ) );
aPolygon.append( basegfx::B2DPoint( aRect.Right( ), aRect.Bottom( ) ) );
aPolygon.append( basegfx::B2DPoint( aRect.Left( ), aRect.Bottom( ) ) );
aPolygon.setClosed( true );
PolyPolygonColorPrimitive2D* pBack = new PolyPolygonColorPrimitive2D(
basegfx::B2DPolyPolygon( aPolygon ), aLightColor );
aSeq[0] = pBack;
LineAttribute aLineAttribute(aDarkColor, 2.0);
// Cross
basegfx::B2DPolyPolygon aCross;
basegfx::B2DPolygon aLine1;
aLine1.append( basegfx::B2DPoint( aRect.Left(), aRect.Top( ) ) );
aLine1.append( basegfx::B2DPoint( aRect.Right(), aRect.Bottom( ) ) );
aCross.append( aLine1 );
basegfx::B2DPolygon aLine2;
aLine2.append( basegfx::B2DPoint( aRect.Right(), aRect.Top( ) ) );
aLine2.append( basegfx::B2DPoint( aRect.Left(), aRect.Bottom( ) ) );
aCross.append( aLine2 );
PolyPolygonStrokePrimitive2D * pCross =
new PolyPolygonStrokePrimitive2D(aCross, aLineAttribute, StrokeAttribute());
aSeq[1] = pCross;
pProcessor->process(aSeq);
}
}
SfxInfoBarWindow::SfxInfoBarWindow( vcl::Window* pParent, const OUString& sId,
const OUString& sMessage, vector<PushButton*> aButtons ) :
Window(pParent, 0),
m_sId(sId),
m_pMessage(new FixedText(this, 0)),
m_pCloseBtn(new SfxCloseButton(this)),
m_aActionBtns()
{
long nWidth = pParent->GetSizePixel().getWidth();
SetPosSizePixel(Point(0, 0), Size(nWidth, 40));
m_pMessage->SetText(sMessage);
m_pMessage->SetBackground(Wallpaper(Color(255, 255, 191)));
m_pMessage->Show();
m_pCloseBtn->SetClickHdl(LINK(this, SfxInfoBarWindow, CloseHandler));
m_pCloseBtn->Show();
// Reparent the buttons and place them on the right of the bar
vector<PushButton*>::iterator it;
for (it = aButtons.begin(); it != aButtons.end(); ++it)
{
PushButton* pButton = *it;
pButton->SetParent(this);
pButton->Show();
m_aActionBtns.push_back(pButton);
}
Resize();
}
SfxInfoBarWindow::~SfxInfoBarWindow()
{}
void SfxInfoBarWindow::Paint(const Rectangle& rPaintRect)
{
const ViewInformation2D aNewViewInfos;
const unique_ptr<BaseProcessor2D> pProcessor(
createBaseProcessor2DFromOutputDevice(*this, aNewViewInfos));
const Rectangle aRect(Point(0, 0), PixelToLogic(GetSizePixel()));
Primitive2DSequence aSeq(2);
basegfx::BColor aLightColor(1.0, 1.0, 191.0 / 255.0);
basegfx::BColor aDarkColor(217.0 / 255.0, 217.0 / 255.0, 78.0 / 255.0);
const StyleSettings& rSettings = Application::GetSettings().GetStyleSettings();
if (rSettings.GetHighContrastMode())
{
aLightColor = rSettings.GetLightColor().getBColor();
aDarkColor = rSettings.GetDialogTextColor().getBColor();
}
// Update the label background color
m_pMessage->SetBackground(Wallpaper(Color(aLightColor)));
// Light background
basegfx::B2DPolygon aPolygon;
aPolygon.append( basegfx::B2DPoint( aRect.Left( ), aRect.Top( ) ) );
aPolygon.append( basegfx::B2DPoint( aRect.Right( ), aRect.Top( ) ) );
aPolygon.append( basegfx::B2DPoint( aRect.Right( ), aRect.Bottom( ) ) );
aPolygon.append( basegfx::B2DPoint( aRect.Left( ), aRect.Bottom( ) ) );
aPolygon.setClosed(true);
PolyPolygonColorPrimitive2D* pBack =
new PolyPolygonColorPrimitive2D(basegfx::B2DPolyPolygon(aPolygon), aLightColor);
aSeq[0] = pBack;
LineAttribute aLineAttribute(aDarkColor, 1.0);
// Bottom dark line
basegfx::B2DPolygon aPolygonBottom;
aPolygonBottom.append( basegfx::B2DPoint( aRect.Left(), aRect.Bottom( ) ) );
aPolygonBottom.append( basegfx::B2DPoint( aRect.Right(), aRect.Bottom( ) ) );
PolygonStrokePrimitive2D * pLineBottom =
new PolygonStrokePrimitive2D (aPolygonBottom, aLineAttribute);
aSeq[1] = pLineBottom;
pProcessor->process(aSeq);
Window::Paint(rPaintRect);
}
void SfxInfoBarWindow::Resize()
{
long nWidth = GetSizePixel().getWidth();
m_pCloseBtn->SetPosSizePixel(Point( nWidth - 25, 15), Size(10, 10));
// Reparent the buttons and place them on the right of the bar
long nX = m_pCloseBtn->GetPosPixel().getX() - 15;
long nBtnGap = 5;
boost::ptr_vector<PushButton>::iterator it;
for (it = m_aActionBtns.begin(); it != m_aActionBtns.end(); ++it)
{
long nBtnWidth = it->GetSizePixel().getWidth();
nX -= nBtnWidth;
it->SetPosSizePixel(Point(nX, 5), Size(nBtnWidth, 30));
nX -= nBtnGap;
}
m_pMessage->SetPosSizePixel(Point(10, 10), Size(nX - 20, 20));
}
IMPL_LINK_NOARG(SfxInfoBarWindow, CloseHandler)
{
static_cast<SfxInfoBarContainerWindow*>(GetParent())->removeInfoBar(this);
return 0;
}
SfxInfoBarContainerWindow::SfxInfoBarContainerWindow(SfxInfoBarContainerChild* pChildWin ) :
Window(pChildWin->GetParent(), 0),
m_pChildWin(pChildWin),
m_pInfoBars()
{
}
SfxInfoBarContainerWindow::~SfxInfoBarContainerWindow()
{
}
void SfxInfoBarContainerWindow::appendInfoBar(const OUString& sId, const OUString& sMessage, vector<PushButton*> aButtons)
{
Size aSize = GetSizePixel( );
SfxInfoBarWindow* pInfoBar = new SfxInfoBarWindow(this, sId, sMessage, aButtons);
pInfoBar->SetPosPixel(Point( 0, aSize.getHeight()));
pInfoBar->Show();
m_pInfoBars.push_back(pInfoBar);
long nHeight = pInfoBar->GetSizePixel().getHeight();
aSize.setHeight(aSize.getHeight() + nHeight);
SetSizePixel(aSize);
}
SfxInfoBarWindow* SfxInfoBarContainerWindow::getInfoBar(const OUString& sId)
{
boost::ptr_vector<SfxInfoBarWindow>::iterator it;
for (it = m_pInfoBars.begin(); it != m_pInfoBars.end(); ++it)
{
if (it->getId() == sId)
return &(*it);
}
return NULL;
}
void SfxInfoBarContainerWindow::removeInfoBar(SfxInfoBarWindow* pInfoBar)
{
boost::ptr_vector<SfxInfoBarWindow>::iterator it;
for (it = m_pInfoBars.begin(); it != m_pInfoBars.end(); ++it)
{
if (pInfoBar == &(*it))
{
m_pInfoBars.erase(it);
break;
}
}
long nY = 0;
for (it = m_pInfoBars.begin(); it != m_pInfoBars.end(); ++it)
{
it->SetPosPixel( Point( 0, nY ) );
nY += it->GetSizePixel( ).getHeight( );
}
Size aSize = GetSizePixel( );
aSize.setHeight(nY);
SetSizePixel(aSize);
m_pChildWin->Update();
}
void SfxInfoBarContainerWindow::Resize()
{
// Only need to change the width of the infobars
long nWidth = GetSizePixel().getWidth();
boost::ptr_vector<SfxInfoBarWindow>::iterator it;
for (it = m_pInfoBars.begin(); it != m_pInfoBars.end(); ++it)
{
Size aSize = it->GetSizePixel();
aSize.setWidth(nWidth);
it->SetSizePixel(aSize);
it->Resize();
}
}
SFX_IMPL_POS_CHILDWINDOW_WITHID(SfxInfoBarContainerChild, SID_INFOBAR, SFX_OBJECTBAR_OBJECT);
SfxInfoBarContainerChild::SfxInfoBarContainerChild( vcl::Window* _pParent, sal_uInt16 nId, SfxBindings* pBindings, SfxChildWinInfo* ) :
SfxChildWindow(_pParent, nId),
m_pBindings(pBindings)
{
pWindow = new SfxInfoBarContainerWindow(this);
pWindow->SetPosSizePixel(Point(0, 0), Size(_pParent->GetSizePixel().getWidth(), 0));
pWindow->Show();
eChildAlignment = SFX_ALIGN_LOWESTTOP;
}
SfxInfoBarContainerChild::~SfxInfoBarContainerChild()
{
}
SfxChildWinInfo SfxInfoBarContainerChild::GetInfo() const
{
SfxChildWinInfo aInfo = SfxChildWindow::GetInfo();
return aInfo;
}
void SfxInfoBarContainerChild::Update()
{
// Refresh the frame to take the infobars container height change into account
const sal_uInt16 nId = GetChildWindowId();
SfxViewFrame* pVFrame = m_pBindings->GetDispatcher()->GetFrame();
pVFrame->ShowChildWindow(nId);
// Give the focus to the document view
pVFrame->GetWindow().GrabFocusToDocument();
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: shutdowniconw32.cxx,v $
* $Revision: 1.48 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sfx2.hxx"
#include "syspath.hxx"
using namespace ::rtl;
#ifdef WNT
#ifdef _MSC_VER
#pragma warning(disable:4917)
#endif
#include <shlobj.h>
static bool _SHGetSpecialFolderW32( int nFolderID, WCHAR* pszFolder, int nSize )
{
LPITEMIDLIST pidl;
HRESULT hHdl = SHGetSpecialFolderLocation( NULL, nFolderID, &pidl );
if( hHdl == NOERROR )
{
WCHAR *lpFolder = static_cast< WCHAR* >( HeapAlloc( GetProcessHeap(), 0, 16000 ));
SHGetPathFromIDListW( pidl, lpFolder );
wcsncpy( pszFolder, lpFolder, nSize );
HeapFree( GetProcessHeap(), 0, lpFolder );
IMalloc *pMalloc;
if( NOERROR == SHGetMalloc(&pMalloc) )
{
pMalloc->Free( pidl );
pMalloc->Release();
}
}
return true;
}
#endif
bool SystemPath::GetUserTemplateLocation(sal_Unicode* pFolder, int nSize )
{
#ifdef WNT
return _SHGetSpecialFolderW32(CSIDL_TEMPLATES, pFolder, nSize );
#else
return false;
#endif
}
<commit_msg>fwk139: #i10000# Another fix for type redefinitions<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: shutdowniconw32.cxx,v $
* $Revision: 1.48 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
// Comment out precompiled statement due to redefinition errors
//#include "precompiled_sfx2.hxx"
#include "syspath.hxx"
#ifdef WNT
#ifdef _MSC_VER
#pragma warning(disable:4917)
#endif
#include <shlobj.h>
static bool _SHGetSpecialFolderW32( int nFolderID, WCHAR* pszFolder, int nSize )
{
LPITEMIDLIST pidl;
HRESULT hHdl = SHGetSpecialFolderLocation( NULL, nFolderID, &pidl );
if( hHdl == NOERROR )
{
WCHAR *lpFolder = static_cast< WCHAR* >( HeapAlloc( GetProcessHeap(), 0, 16000 ));
SHGetPathFromIDListW( pidl, lpFolder );
wcsncpy( pszFolder, lpFolder, nSize );
HeapFree( GetProcessHeap(), 0, lpFolder );
IMalloc *pMalloc;
if( NOERROR == SHGetMalloc(&pMalloc) )
{
pMalloc->Free( pidl );
pMalloc->Release();
}
}
return true;
}
#endif
bool SystemPath::GetUserTemplateLocation(sal_Unicode* pFolder, int nSize )
{
#ifdef WNT
return _SHGetSpecialFolderW32(CSIDL_TEMPLATES, pFolder, nSize );
#else
return false;
#endif
}
<|endoftext|>
|
<commit_before>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/**
* @file
**/
#include "modules/planning/lattice/trajectory_generation/trajectory_evaluator.h"
#include <cmath>
#include <functional>
#include <limits>
#include <utility>
#include "modules/common/log.h"
#include "modules/planning/common/planning_gflags.h"
#include "modules/planning/constraint_checker/constraint_checker1d.h"
namespace apollo {
namespace planning {
using Trajectory1d = Curve1d;
TrajectoryEvaluator::TrajectoryEvaluator(
const PlanningTarget& planning_target,
const std::vector<std::shared_ptr<Trajectory1d>>& lon_trajectories,
const std::vector<std::shared_ptr<Trajectory1d>>& lat_trajectories,
std::shared_ptr<PathTimeGraph> path_time_graph)
: path_time_graph_(path_time_graph) {
const double start_time = 0.0;
const double end_time = FLAGS_trajectory_time_length;
path_time_intervals_ = path_time_graph_->GetPathBlockingIntervals(
start_time, end_time, FLAGS_trajectory_time_resolution);
// if we have a stop point along the reference line,
// filter out the lon. trajectories that pass the stop point.
double stop_point = std::numeric_limits<double>::max();
if (planning_target.has_stop_point()) {
stop_point = planning_target.stop_point().s();
}
for (const auto lon_trajectory : lon_trajectories) {
double lon_end_s = lon_trajectory->Evaluate(0, end_time);
if (lon_end_s > stop_point) {
continue;
}
if (!ConstraintChecker1d::IsValidLongitudinalTrajectory(*lon_trajectory)) {
continue;
}
for (const auto lat_trajectory : lat_trajectories) {
/**
if (!ConstraintChecker1d::IsValidLateralTrajectory(*lat_trajectory,
*lon_trajectory)) {
continue;
}
*/
if (!FLAGS_enable_auto_tuning) {
double cost = Evaluate(planning_target, lon_trajectory, lat_trajectory);
cost_queue_.push(PairCost({lon_trajectory, lat_trajectory}, cost));
} else {
std::vector<double> cost_components;
double cost = Evaluate(planning_target, lon_trajectory, lat_trajectory,
&cost_components);
cost_queue_with_components_.push(PairCostWithComponents(
{lon_trajectory, lat_trajectory}, {cost_components, cost}));
}
}
}
if (!FLAGS_enable_auto_tuning) {
ADEBUG << "Number of valid 1d trajectory pairs: " << cost_queue_.size();
} else {
ADEBUG << "Number of valid 1d trajectory pairs: "
<< cost_queue_with_components_.size();
}
}
bool TrajectoryEvaluator::has_more_trajectory_pairs() const {
if (!FLAGS_enable_auto_tuning) {
return !cost_queue_.empty();
} else {
return !cost_queue_with_components_.empty();
}
}
std::size_t TrajectoryEvaluator::num_of_trajectory_pairs() const {
if (!FLAGS_enable_auto_tuning) {
return cost_queue_.size();
} else {
return cost_queue_with_components_.size();
}
}
std::pair<std::shared_ptr<Trajectory1d>, std::shared_ptr<Trajectory1d>>
TrajectoryEvaluator::next_top_trajectory_pair() {
CHECK(has_more_trajectory_pairs() == true);
if (!FLAGS_enable_auto_tuning) {
auto top = cost_queue_.top();
cost_queue_.pop();
return top.first;
} else {
auto top = cost_queue_with_components_.top();
cost_queue_with_components_.pop();
return top.first;
}
}
double TrajectoryEvaluator::top_trajectory_pair_cost() const {
if (!FLAGS_enable_auto_tuning) {
return cost_queue_.top().second;
} else {
return cost_queue_with_components_.top().second.second;
}
}
std::vector<double> TrajectoryEvaluator::top_trajectory_pair_component_cost()
const {
CHECK(FLAGS_enable_auto_tuning);
return cost_queue_with_components_.top().second.first;
}
double TrajectoryEvaluator::Evaluate(
const PlanningTarget& planning_target,
const std::shared_ptr<Trajectory1d>& lon_trajectory,
const std::shared_ptr<Trajectory1d>& lat_trajectory,
std::vector<double>* cost_components) const {
// Costs:
// 1. Cost to achieve the objective
// 2. Cost of logitudinal jerk
// 3. Cost of logitudinal collision
// 4. Cost of lateral offsets
// 5. Cost of lateral comfort
// Longitudinal costs
double lon_travel_cost = LonObjectiveCost(lon_trajectory, planning_target);
double lon_jerk_cost = LonComfortCost(lon_trajectory);
double lon_collision_cost = LonCollisionCost(lon_trajectory);
std::vector<double> s_values;
for (double s = 0.0; s < FLAGS_decision_horizon;
s += FLAGS_trajectory_space_resolution) {
s_values.push_back(s);
}
// Lateral costs
double lat_offset_cost = LatOffsetCost(lat_trajectory, s_values);
double lat_comfort_cost = LatComfortCost(lon_trajectory, lat_trajectory);
if (cost_components != nullptr) {
cost_components->push_back(lon_travel_cost);
cost_components->push_back(lon_jerk_cost);
cost_components->push_back(lon_collision_cost);
cost_components->push_back(lat_offset_cost);
}
return lon_travel_cost * FLAGS_weight_lon_travel +
lon_jerk_cost * FLAGS_weight_lon_jerk +
lon_collision_cost * FLAGS_weight_lon_collision +
lat_offset_cost * FLAGS_weight_lat_offset +
lat_comfort_cost * FLAGS_weight_lat_comfort;
}
double TrajectoryEvaluator::LatOffsetCost(
const std::shared_ptr<Trajectory1d>& lat_trajectory,
const std::vector<double>& s_values) const {
double lat_offset_start = lat_trajectory->Evaluate(0, 0.0);
double cost_sqr_sum = 0.0;
double cost_abs_sum = 0.0;
for (const auto& s : s_values) {
double lat_offset = lat_trajectory->Evaluate(0, s);
double cost = lat_offset / FLAGS_lat_offset_bound;
if (lat_offset * lat_offset_start < 0.0) {
cost_sqr_sum += cost * cost * FLAGS_weight_opposite_side_offset;
cost_abs_sum += std::abs(cost) * FLAGS_weight_opposite_side_offset;
} else {
cost_sqr_sum += cost * cost * FLAGS_weight_same_side_offset;
cost_abs_sum += std::abs(cost) * FLAGS_weight_same_side_offset;
}
}
return cost_sqr_sum / (cost_abs_sum + FLAGS_lattice_epsilon);
}
double TrajectoryEvaluator::LatComfortCost(
const std::shared_ptr<Trajectory1d>& lon_trajectory,
const std::shared_ptr<Trajectory1d>& lat_trajectory) const {
double cost_sqr_sum = 0.0;
double cost_abs_sum = 0.0;
for (double t = 0.0; t < FLAGS_trajectory_time_length;
t += FLAGS_trajectory_time_resolution) {
double s = lon_trajectory->Evaluate(0, t);
double cost = lat_trajectory->Evaluate(1, s) *
lon_trajectory->Evaluate(1, t) / FLAGS_default_cruise_speed;
cost_sqr_sum += cost * cost;
cost_abs_sum += std::abs(cost);
}
return cost_sqr_sum / (cost_abs_sum + FLAGS_lattice_epsilon);
}
double TrajectoryEvaluator::LonComfortCost(
const std::shared_ptr<Trajectory1d>& lon_trajectory) const {
double cost_sqr_sum = 0.0;
double cost_abs_sum = 0.0;
for (double t = 0.0; t < FLAGS_trajectory_time_length;
t += FLAGS_trajectory_time_resolution) {
double jerk = lon_trajectory->Evaluate(3, t);
double cost = jerk / FLAGS_longitudinal_jerk_upper_bound;
cost_sqr_sum += cost * cost;
cost_abs_sum += std::abs(cost);
}
return cost_sqr_sum / (cost_abs_sum + FLAGS_lattice_epsilon);
}
double TrajectoryEvaluator::LonObjectiveCost(
const std::shared_ptr<Trajectory1d>& lon_trajectory,
const PlanningTarget& planning_target) const {
double t_max = lon_trajectory->ParamLength();
double dist_s =
lon_trajectory->Evaluate(0, t_max) - lon_trajectory->Evaluate(0, 0.0);
double speed_cost_sqr_sum = 0.0;
double speed_cost_abs_sum = 0.0;
for (double t = 0.0; t < FLAGS_trajectory_time_length;
t += FLAGS_trajectory_time_resolution) {
double cost =
planning_target.cruise_speed() - lon_trajectory->Evaluate(1, t);
speed_cost_sqr_sum += cost * cost;
speed_cost_abs_sum += std::abs(cost);
}
double speed_cost =
speed_cost_sqr_sum / (speed_cost_abs_sum + FLAGS_lattice_epsilon);
double dist_travelled_cost = 1.0 / (1.0 + dist_s);
return (speed_cost * FLAGS_weight_target_speed +
dist_travelled_cost * FLAGS_weight_dist_travelled) /
(FLAGS_weight_target_speed + FLAGS_weight_dist_travelled);
}
// TODO(all): consider putting pointer of reference_line_info and frame
// while constructing trajectory evaluator
double TrajectoryEvaluator::LonCollisionCost(
const std::shared_ptr<Trajectory1d>& lon_trajectory) const {
double cost_sqr_sum = 0.0;
double cost_abs_sum = 0.0;
for (std::size_t i = 0; i < path_time_intervals_.size(); ++i) {
const auto& pt_interval = path_time_intervals_[i];
if (pt_interval.empty()) {
continue;
}
double t = i * FLAGS_trajectory_time_resolution;
double traj_s = lon_trajectory->Evaluate(0, t);
double sigma = FLAGS_lon_collision_cost_std;
for (const auto& m : pt_interval) {
double dist = 0.0;
if (traj_s < m.first - FLAGS_lon_collision_yield_buffer) {
dist = m.first - FLAGS_lon_collision_yield_buffer - traj_s;
} else if (traj_s > m.second + FLAGS_lon_collision_overtake_buffer) {
dist = traj_s - m.second - FLAGS_lon_collision_overtake_buffer;
}
double cost = std::exp(-dist * dist / (2.0 * sigma * sigma));
cost_sqr_sum += cost * cost;
cost_abs_sum += cost;
}
}
return cost_sqr_sum / (cost_abs_sum + FLAGS_lattice_epsilon);
}
std::vector<double> TrajectoryEvaluator::evaluate_per_lonlat_trajectory(
const PlanningTarget& planning_target,
const std::vector<apollo::common::SpeedPoint> st_points,
const std::vector<apollo::common::FrenetFramePoint> sl_points) {
std::vector<double> ret;
return ret;
}
} // namespace planning
} // namespace apollo
<commit_msg>planning: fixed the evaluation horizon problem in lattice planner<commit_after>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/**
* @file
**/
#include "modules/planning/lattice/trajectory_generation/trajectory_evaluator.h"
#include <cmath>
#include <functional>
#include <limits>
#include <utility>
#include "modules/common/log.h"
#include "modules/planning/common/planning_gflags.h"
#include "modules/planning/constraint_checker/constraint_checker1d.h"
namespace apollo {
namespace planning {
using Trajectory1d = Curve1d;
TrajectoryEvaluator::TrajectoryEvaluator(
const PlanningTarget& planning_target,
const std::vector<std::shared_ptr<Trajectory1d>>& lon_trajectories,
const std::vector<std::shared_ptr<Trajectory1d>>& lat_trajectories,
std::shared_ptr<PathTimeGraph> path_time_graph)
: path_time_graph_(path_time_graph) {
const double start_time = 0.0;
const double end_time = FLAGS_trajectory_time_length;
path_time_intervals_ = path_time_graph_->GetPathBlockingIntervals(
start_time, end_time, FLAGS_trajectory_time_resolution);
// if we have a stop point along the reference line,
// filter out the lon. trajectories that pass the stop point.
double stop_point = std::numeric_limits<double>::max();
if (planning_target.has_stop_point()) {
stop_point = planning_target.stop_point().s();
}
for (const auto lon_trajectory : lon_trajectories) {
double lon_end_s = lon_trajectory->Evaluate(0, end_time);
if (lon_end_s > stop_point) {
continue;
}
if (!ConstraintChecker1d::IsValidLongitudinalTrajectory(*lon_trajectory)) {
continue;
}
for (const auto lat_trajectory : lat_trajectories) {
/**
if (!ConstraintChecker1d::IsValidLateralTrajectory(*lat_trajectory,
*lon_trajectory)) {
continue;
}
*/
if (!FLAGS_enable_auto_tuning) {
double cost = Evaluate(planning_target, lon_trajectory, lat_trajectory);
cost_queue_.push(PairCost({lon_trajectory, lat_trajectory}, cost));
} else {
std::vector<double> cost_components;
double cost = Evaluate(planning_target, lon_trajectory, lat_trajectory,
&cost_components);
cost_queue_with_components_.push(PairCostWithComponents(
{lon_trajectory, lat_trajectory}, {cost_components, cost}));
}
}
}
if (!FLAGS_enable_auto_tuning) {
ADEBUG << "Number of valid 1d trajectory pairs: " << cost_queue_.size();
} else {
ADEBUG << "Number of valid 1d trajectory pairs: "
<< cost_queue_with_components_.size();
}
}
bool TrajectoryEvaluator::has_more_trajectory_pairs() const {
if (!FLAGS_enable_auto_tuning) {
return !cost_queue_.empty();
} else {
return !cost_queue_with_components_.empty();
}
}
std::size_t TrajectoryEvaluator::num_of_trajectory_pairs() const {
if (!FLAGS_enable_auto_tuning) {
return cost_queue_.size();
} else {
return cost_queue_with_components_.size();
}
}
std::pair<std::shared_ptr<Trajectory1d>, std::shared_ptr<Trajectory1d>>
TrajectoryEvaluator::next_top_trajectory_pair() {
CHECK(has_more_trajectory_pairs() == true);
if (!FLAGS_enable_auto_tuning) {
auto top = cost_queue_.top();
cost_queue_.pop();
return top.first;
} else {
auto top = cost_queue_with_components_.top();
cost_queue_with_components_.pop();
return top.first;
}
}
double TrajectoryEvaluator::top_trajectory_pair_cost() const {
if (!FLAGS_enable_auto_tuning) {
return cost_queue_.top().second;
} else {
return cost_queue_with_components_.top().second.second;
}
}
std::vector<double> TrajectoryEvaluator::top_trajectory_pair_component_cost()
const {
CHECK(FLAGS_enable_auto_tuning);
return cost_queue_with_components_.top().second.first;
}
double TrajectoryEvaluator::Evaluate(
const PlanningTarget& planning_target,
const std::shared_ptr<Trajectory1d>& lon_trajectory,
const std::shared_ptr<Trajectory1d>& lat_trajectory,
std::vector<double>* cost_components) const {
// Costs:
// 1. Cost to achieve the objective
// 2. Cost of logitudinal jerk
// 3. Cost of logitudinal collision
// 4. Cost of lateral offsets
// 5. Cost of lateral comfort
// Longitudinal costs
double lon_travel_cost = LonObjectiveCost(lon_trajectory, planning_target);
double lon_jerk_cost = LonComfortCost(lon_trajectory);
double lon_collision_cost = LonCollisionCost(lon_trajectory);
double evaluation_horizon = std::min(FLAGS_decision_horizon,
lon_trajectory->Evaluate(0, lon_trajectory->ParamLength()));
std::vector<double> s_values;
for (double s = 0.0; s < evaluation_horizon;
s += FLAGS_trajectory_space_resolution) {
s_values.push_back(s);
}
// Lateral costs
double lat_offset_cost = LatOffsetCost(lat_trajectory, s_values);
double lat_comfort_cost = LatComfortCost(lon_trajectory, lat_trajectory);
if (cost_components != nullptr) {
cost_components->push_back(lon_travel_cost);
cost_components->push_back(lon_jerk_cost);
cost_components->push_back(lon_collision_cost);
cost_components->push_back(lat_offset_cost);
}
return lon_travel_cost * FLAGS_weight_lon_travel +
lon_jerk_cost * FLAGS_weight_lon_jerk +
lon_collision_cost * FLAGS_weight_lon_collision +
lat_offset_cost * FLAGS_weight_lat_offset +
lat_comfort_cost * FLAGS_weight_lat_comfort;
}
double TrajectoryEvaluator::LatOffsetCost(
const std::shared_ptr<Trajectory1d>& lat_trajectory,
const std::vector<double>& s_values) const {
double lat_offset_start = lat_trajectory->Evaluate(0, 0.0);
double cost_sqr_sum = 0.0;
double cost_abs_sum = 0.0;
for (const auto& s : s_values) {
double lat_offset = lat_trajectory->Evaluate(0, s);
double cost = lat_offset / FLAGS_lat_offset_bound;
if (lat_offset * lat_offset_start < 0.0) {
cost_sqr_sum += cost * cost * FLAGS_weight_opposite_side_offset;
cost_abs_sum += std::abs(cost) * FLAGS_weight_opposite_side_offset;
} else {
cost_sqr_sum += cost * cost * FLAGS_weight_same_side_offset;
cost_abs_sum += std::abs(cost) * FLAGS_weight_same_side_offset;
}
}
return cost_sqr_sum / (cost_abs_sum + FLAGS_lattice_epsilon);
}
double TrajectoryEvaluator::LatComfortCost(
const std::shared_ptr<Trajectory1d>& lon_trajectory,
const std::shared_ptr<Trajectory1d>& lat_trajectory) const {
double cost_sqr_sum = 0.0;
double cost_abs_sum = 0.0;
for (double t = 0.0; t < FLAGS_trajectory_time_length;
t += FLAGS_trajectory_time_resolution) {
double s = lon_trajectory->Evaluate(0, t);
double cost = lat_trajectory->Evaluate(1, s) *
lon_trajectory->Evaluate(1, t) / FLAGS_default_cruise_speed;
cost_sqr_sum += cost * cost;
cost_abs_sum += std::abs(cost);
}
return cost_sqr_sum / (cost_abs_sum + FLAGS_lattice_epsilon);
}
double TrajectoryEvaluator::LonComfortCost(
const std::shared_ptr<Trajectory1d>& lon_trajectory) const {
double cost_sqr_sum = 0.0;
double cost_abs_sum = 0.0;
for (double t = 0.0; t < FLAGS_trajectory_time_length;
t += FLAGS_trajectory_time_resolution) {
double jerk = lon_trajectory->Evaluate(3, t);
double cost = jerk / FLAGS_longitudinal_jerk_upper_bound;
cost_sqr_sum += cost * cost;
cost_abs_sum += std::abs(cost);
}
return cost_sqr_sum / (cost_abs_sum + FLAGS_lattice_epsilon);
}
double TrajectoryEvaluator::LonObjectiveCost(
const std::shared_ptr<Trajectory1d>& lon_trajectory,
const PlanningTarget& planning_target) const {
double t_max = lon_trajectory->ParamLength();
double dist_s =
lon_trajectory->Evaluate(0, t_max) - lon_trajectory->Evaluate(0, 0.0);
double speed_cost_sqr_sum = 0.0;
double speed_cost_abs_sum = 0.0;
for (double t = 0.0; t < FLAGS_trajectory_time_length;
t += FLAGS_trajectory_time_resolution) {
double cost =
planning_target.cruise_speed() - lon_trajectory->Evaluate(1, t);
speed_cost_sqr_sum += cost * cost;
speed_cost_abs_sum += std::abs(cost);
}
double speed_cost =
speed_cost_sqr_sum / (speed_cost_abs_sum + FLAGS_lattice_epsilon);
double dist_travelled_cost = 1.0 / (1.0 + dist_s);
return (speed_cost * FLAGS_weight_target_speed +
dist_travelled_cost * FLAGS_weight_dist_travelled) /
(FLAGS_weight_target_speed + FLAGS_weight_dist_travelled);
}
// TODO(all): consider putting pointer of reference_line_info and frame
// while constructing trajectory evaluator
double TrajectoryEvaluator::LonCollisionCost(
const std::shared_ptr<Trajectory1d>& lon_trajectory) const {
double cost_sqr_sum = 0.0;
double cost_abs_sum = 0.0;
for (std::size_t i = 0; i < path_time_intervals_.size(); ++i) {
const auto& pt_interval = path_time_intervals_[i];
if (pt_interval.empty()) {
continue;
}
double t = i * FLAGS_trajectory_time_resolution;
double traj_s = lon_trajectory->Evaluate(0, t);
double sigma = FLAGS_lon_collision_cost_std;
for (const auto& m : pt_interval) {
double dist = 0.0;
if (traj_s < m.first - FLAGS_lon_collision_yield_buffer) {
dist = m.first - FLAGS_lon_collision_yield_buffer - traj_s;
} else if (traj_s > m.second + FLAGS_lon_collision_overtake_buffer) {
dist = traj_s - m.second - FLAGS_lon_collision_overtake_buffer;
}
double cost = std::exp(-dist * dist / (2.0 * sigma * sigma));
cost_sqr_sum += cost * cost;
cost_abs_sum += cost;
}
}
return cost_sqr_sum / (cost_abs_sum + FLAGS_lattice_epsilon);
}
std::vector<double> TrajectoryEvaluator::evaluate_per_lonlat_trajectory(
const PlanningTarget& planning_target,
const std::vector<apollo::common::SpeedPoint> st_points,
const std::vector<apollo::common::FrenetFramePoint> sl_points) {
std::vector<double> ret;
return ret;
}
} // namespace planning
} // namespace apollo
<|endoftext|>
|
<commit_before>#include "IRremote.h"
#include "IRremoteInt.h"
//==============================================================================
// L EEEEEE EEEE OOOO
// L E E O O
// L EEEE E EEE O O
// L E E E O O LEGO Power Functions
// LLLLLL EEEEEE EEEE OOOO Copyright (c) 2016 Philipp Henkel
//==============================================================================
//+=============================================================================
//
#if SEND_LEGO_PF
class BitStreamEncoder {
private:
uint16_t data;
bool repeatMessage;
int messageBitIdx;
int repeatCount;
int messageLength;
// HIGH data bit = IR mark + high pause
// LOW data bit = IR mark + low pause
static const int LOW_BIT_DURATION = 421;
static const int HIGH_BIT_DURATION = 711;
static const int START_BIT_DURATION = 1184;
static const int STOP_BIT_DURATION = 1184;
static const int IR_MARK_DURATION = 158;
static const int HIGH_PAUSE_DURATION = HIGH_BIT_DURATION - IR_MARK_DURATION;
static const int LOW_PAUSE_DURATION = LOW_BIT_DURATION - IR_MARK_DURATION;
static const int START_PAUSE_DURATION = START_BIT_DURATION - IR_MARK_DURATION;
static const int STOP_PAUSE_DURATION = STOP_BIT_DURATION - IR_MARK_DURATION;
static const int MESSAGE_BITS = 18;
static const int MAX_MESSAGE_LENGTH = 16000;
public:
void reset(uint16_t data, bool repeatMessage) {
this->data = data;
this->repeatMessage = repeatMessage;
messageBitIdx = 0;
repeatCount = 0;
messageLength = getMessageLength();
}
int getChannelId() const { return 1 + ((data >> 12) & 0x3); }
int getMessageLength() const {
// Sum up all marks
int length = MESSAGE_BITS * IR_MARK_DURATION;
// Sum up all pauses
length += START_PAUSE_DURATION;
for (unsigned long mask = 1UL << 15; mask; mask >>= 1) {
if (data & mask) {
length += HIGH_PAUSE_DURATION;
} else {
length += LOW_PAUSE_DURATION;
}
}
length += STOP_PAUSE_DURATION;
return length;
}
boolean next() {
messageBitIdx++;
if (messageBitIdx >= MESSAGE_BITS) {
repeatCount++;
messageBitIdx = 0;
}
if (repeatCount >= 1 && !repeatMessage) {
return false;
} else if (repeatCount >= 5) {
return false;
} else {
return true;
}
}
int getMarkDuration() const { return IR_MARK_DURATION; }
int getPauseDuration() const {
if (messageBitIdx == 0)
return START_PAUSE_DURATION;
else if (messageBitIdx < MESSAGE_BITS - 1) {
return getDataBitPause();
} else {
return getStopPause();
}
}
private:
int getDataBitPause() const {
const int pos = MESSAGE_BITS - 2 - messageBitIdx;
const bool isHigh = data & (1 << pos);
return isHigh ? HIGH_PAUSE_DURATION : LOW_PAUSE_DURATION;
}
int getStopPause() const {
if (repeatMessage) {
return getRepeatStopPause();
} else {
return STOP_PAUSE_DURATION;
}
}
int getRepeatStopPause() const {
if (repeatCount == 0 || repeatCount == 1) {
return STOP_PAUSE_DURATION + 5 * MAX_MESSAGE_LENGTH - messageLength;
} else if (repeatCount == 2 || repeatCount == 3) {
return STOP_PAUSE_DURATION
+ (6 + 2 * getChannelId()) * MAX_MESSAGE_LENGTH - messageLength;
} else {
return STOP_PAUSE_DURATION;
}
}
};
void IRsend::sendLegoPowerFunctions(uint16_t data, bool repeat)
{
enableIROut(38);
static BitStreamEncoder bitStreamEncoder;
bitStreamEncoder.reset(data, repeat);
do {
mark(bitStreamEncoder.getMarkDuration());
space(bitStreamEncoder.getPauseDuration());
} while (bitStreamEncoder.next());
}
#endif
<commit_msg>Add supported device LEGO® Power Functions IR Receiver 8884<commit_after>#include "IRremote.h"
#include "IRremoteInt.h"
//==============================================================================
// L EEEEEE EEEE OOOO
// L E E O O
// L EEEE E EEE O O
// L E E E O O LEGO Power Functions
// LLLLLL EEEEEE EEEE OOOO Copyright (c) 2016 Philipp Henkel
//==============================================================================
// Supported Devices
// LEGO® Power Functions IR Receiver 8884
//+=============================================================================
//
#if SEND_LEGO_PF
class BitStreamEncoder {
private:
uint16_t data;
bool repeatMessage;
int messageBitIdx;
int repeatCount;
int messageLength;
// HIGH data bit = IR mark + high pause
// LOW data bit = IR mark + low pause
static const int LOW_BIT_DURATION = 421;
static const int HIGH_BIT_DURATION = 711;
static const int START_BIT_DURATION = 1184;
static const int STOP_BIT_DURATION = 1184;
static const int IR_MARK_DURATION = 158;
static const int HIGH_PAUSE_DURATION = HIGH_BIT_DURATION - IR_MARK_DURATION;
static const int LOW_PAUSE_DURATION = LOW_BIT_DURATION - IR_MARK_DURATION;
static const int START_PAUSE_DURATION = START_BIT_DURATION - IR_MARK_DURATION;
static const int STOP_PAUSE_DURATION = STOP_BIT_DURATION - IR_MARK_DURATION;
static const int MESSAGE_BITS = 18;
static const int MAX_MESSAGE_LENGTH = 16000;
public:
void reset(uint16_t data, bool repeatMessage) {
this->data = data;
this->repeatMessage = repeatMessage;
messageBitIdx = 0;
repeatCount = 0;
messageLength = getMessageLength();
}
int getChannelId() const { return 1 + ((data >> 12) & 0x3); }
int getMessageLength() const {
// Sum up all marks
int length = MESSAGE_BITS * IR_MARK_DURATION;
// Sum up all pauses
length += START_PAUSE_DURATION;
for (unsigned long mask = 1UL << 15; mask; mask >>= 1) {
if (data & mask) {
length += HIGH_PAUSE_DURATION;
} else {
length += LOW_PAUSE_DURATION;
}
}
length += STOP_PAUSE_DURATION;
return length;
}
boolean next() {
messageBitIdx++;
if (messageBitIdx >= MESSAGE_BITS) {
repeatCount++;
messageBitIdx = 0;
}
if (repeatCount >= 1 && !repeatMessage) {
return false;
} else if (repeatCount >= 5) {
return false;
} else {
return true;
}
}
int getMarkDuration() const { return IR_MARK_DURATION; }
int getPauseDuration() const {
if (messageBitIdx == 0)
return START_PAUSE_DURATION;
else if (messageBitIdx < MESSAGE_BITS - 1) {
return getDataBitPause();
} else {
return getStopPause();
}
}
private:
int getDataBitPause() const {
const int pos = MESSAGE_BITS - 2 - messageBitIdx;
const bool isHigh = data & (1 << pos);
return isHigh ? HIGH_PAUSE_DURATION : LOW_PAUSE_DURATION;
}
int getStopPause() const {
if (repeatMessage) {
return getRepeatStopPause();
} else {
return STOP_PAUSE_DURATION;
}
}
int getRepeatStopPause() const {
if (repeatCount == 0 || repeatCount == 1) {
return STOP_PAUSE_DURATION + 5 * MAX_MESSAGE_LENGTH - messageLength;
} else if (repeatCount == 2 || repeatCount == 3) {
return STOP_PAUSE_DURATION
+ (6 + 2 * getChannelId()) * MAX_MESSAGE_LENGTH - messageLength;
} else {
return STOP_PAUSE_DURATION;
}
}
};
void IRsend::sendLegoPowerFunctions(uint16_t data, bool repeat)
{
enableIROut(38);
static BitStreamEncoder bitStreamEncoder;
bitStreamEncoder.reset(data, repeat);
do {
mark(bitStreamEncoder.getMarkDuration());
space(bitStreamEncoder.getPauseDuration());
} while (bitStreamEncoder.next());
}
#endif
<|endoftext|>
|
<commit_before>#include "ircmanager.h"
#include "QJsonArray"
#include "QJsonDocument"
#include "QJsonObject"
#include "QNetworkReply"
#include "asyncexec.h"
#include "channel.h"
#include "future"
#include "irccommand.h"
#include "ircconnection.h"
#include "qnetworkrequest.h"
Account *IrcManager::account = const_cast<Account *>(Account::anon());
IrcConnection *IrcManager::connection = NULL;
QMutex IrcManager::connectionMutex;
long IrcManager::connectionIteration = 0;
const QString IrcManager::defaultClientId = "7ue61iz46fz11y3cugd0l3tawb4taal";
QNetworkAccessManager IrcManager::m_accessManager;
QMap<QString, bool> IrcManager::twitchBlockedUsers;
QMutex IrcManager::twitchBlockedUsersMutex;
IrcManager::IrcManager()
{
}
void
IrcManager::connect()
{
disconnect();
async_exec([] { beginConnecting(); });
}
void
IrcManager::beginConnecting()
{
int iteration = ++connectionIteration;
auto c = new IrcConnection();
QObject::connect(c, &IrcConnection::messageReceived, &messageReceived);
QObject::connect(c, &IrcConnection::privateMessageReceived,
&privateMessageReceived);
if (account->isAnon()) {
// fetch ignored users
QString username = account->username();
QString oauthClient = account->oauthClient();
QString oauthToken = account->oauthToken();
{
QString nextLink = "https://api.twitch.tv/kraken/users/" +
username + "/blocks?limit=" + 100 +
"&client_id=" + oauthClient;
QNetworkRequest req(QUrl(nextLink + "&oauth_token=" + oauthToken));
QNetworkReply *reply = m_accessManager.get(req);
QObject::connect(reply, &QNetworkReply::finished, [=] {
twitchBlockedUsersMutex.lock();
twitchBlockedUsers.clear();
twitchBlockedUsersMutex.unlock();
QByteArray data = reply->readAll();
QJsonDocument jsonDoc(QJsonDocument::fromJson(data));
QJsonObject root = jsonDoc.object();
// nextLink =
// root.value("_links").toObject().value("next").toString();
auto blocks = root.value("blocks").toArray();
twitchBlockedUsersMutex.lock();
for (QJsonValue block : blocks) {
QJsonObject user =
block.toObject().value("user").toObject();
// display_name
twitchBlockedUsers.insert(
user.value("name").toString().toLower(), true);
}
twitchBlockedUsersMutex.unlock();
});
}
// fetch available twitch emtoes
{
QNetworkRequest req(QUrl("https://api.twitch.tv/kraken/users/" +
username + "/emotes?oauth_token=" +
oauthToken + "&client_id=" + oauthClient));
QNetworkReply *reply = m_accessManager.get(req);
QObject::connect(reply, &QNetworkReply::finished, [=] {
QByteArray data = reply->readAll();
QJsonDocument jsonDoc(QJsonDocument::fromJson(data));
QJsonObject root = jsonDoc.object();
// nextLink =
// root.value("_links").toObject().value("next").toString();
auto blocks = root.value("blocks").toArray();
twitchBlockedUsersMutex.lock();
for (QJsonValue block : blocks) {
QJsonObject user =
block.toObject().value("user").toObject();
// display_name
twitchBlockedUsers.insert(
user.value("name").toString().toLower(), true);
}
twitchBlockedUsersMutex.unlock();
});
}
}
c->setHost("irc.chat.twitch.tv");
c->setPort(6667);
c->setUserName("justinfan123");
c->setNickName("justinfan123");
c->setRealName("justinfan123");
c->sendRaw("JOIN #fourtf");
c->sendCommand(IrcCommand::createCapability("REQ", "twitch.tv/commands"));
c->sendCommand(IrcCommand::createCapability("REQ", "twitch.tv/tags"));
c->open();
connectionMutex.lock();
if (iteration == connectionIteration) {
delete connection;
c->moveToThread(QCoreApplication::instance()->thread());
connection = c;
} else {
delete c;
}
connectionMutex.unlock();
}
void
IrcManager::disconnect()
{
connectionMutex.lock();
if (connection != NULL) {
delete connection;
connection = NULL;
}
connectionMutex.unlock();
}
void
IrcManager::messageReceived(IrcMessage *message)
{
qInfo(message->command().toStdString().c_str());
// if (message->command() == "")
}
void
IrcManager::privateMessageReceived(IrcPrivateMessage *message)
{
qInfo(message->content().toStdString().c_str());
qInfo(message->target().toStdString().c_str());
auto c = Channel::getChannel(message->target().mid(1));
if (c != NULL) {
c->addMessage(std::shared_ptr<Message>(new Message(*message, *c)));
}
}
bool
IrcManager::isTwitchBlockedUser(QString const &username)
{
twitchBlockedUsersMutex.lock();
auto iterator = twitchBlockedUsers.find(username);
if (iterator == twitchBlockedUsers.end()) {
twitchBlockedUsersMutex.unlock();
return false;
}
twitchBlockedUsersMutex.unlock();
return true;
}
bool
IrcManager::tryAddIgnoredUser(QString const &username, QString &errorMessage)
{
QUrl url("https://api.twitch.tv/kraken/users/" + account->username() +
"/blocks/" + username + "?oauth_token=" + account->oauthToken() +
"&client_id=" + account->oauthClient());
QNetworkRequest request(url);
auto reply = m_accessManager.put(request, QByteArray());
reply->waitForReadyRead(10000);
if (reply->error() == QNetworkReply::NoError) {
twitchBlockedUsersMutex.lock();
twitchBlockedUsers.insert(username, true);
twitchBlockedUsersMutex.unlock();
delete reply;
return true;
}
errorMessage = "Error while ignoring user \"" + username +
"\": " + reply->errorString();
return false;
}
void
IrcManager::addIgnoredUser(QString const &username)
{
QString errorMessage;
if (!tryAddIgnoredUser(username, errorMessage)) {
#pragma message WARN("Implement IrcManager::addIgnoredUser")
}
}
bool
IrcManager::tryRemoveIgnoredUser(QString const &username, QString &errorMessage)
{
QUrl url("https://api.twitch.tv/kraken/users/" + account->username() +
"/blocks/" + username + "?oauth_token=" + account->oauthToken() +
"&client_id=" + account->oauthClient());
QNetworkRequest request(url);
auto reply = m_accessManager.deleteResource(request);
reply->waitForReadyRead(10000);
if (reply->error() == QNetworkReply::NoError) {
twitchBlockedUsersMutex.lock();
twitchBlockedUsers.remove(username);
twitchBlockedUsersMutex.unlock();
delete reply;
return true;
}
errorMessage = "Error while unignoring user \"" + username +
"\": " + reply->errorString();
return false;
}
void
IrcManager::removeIgnoredUser(QString const &username)
{
QString errorMessage;
if (!tryRemoveIgnoredUser(username, errorMessage)) {
#pragma message WARN("TODO: Implement IrcManager::removeIgnoredUser")
}
}
<commit_msg>changed initialization order of account<commit_after>#include "ircmanager.h"
#include "QJsonArray"
#include "QJsonDocument"
#include "QJsonObject"
#include "QNetworkReply"
#include "asyncexec.h"
#include "channel.h"
#include "future"
#include "irccommand.h"
#include "ircconnection.h"
#include "qnetworkrequest.h"
Account *IrcManager::account = nullptr;
IrcConnection *IrcManager::connection = NULL;
QMutex IrcManager::connectionMutex;
long IrcManager::connectionIteration = 0;
const QString IrcManager::defaultClientId = "7ue61iz46fz11y3cugd0l3tawb4taal";
QNetworkAccessManager IrcManager::m_accessManager;
QMap<QString, bool> IrcManager::twitchBlockedUsers;
QMutex IrcManager::twitchBlockedUsersMutex;
IrcManager::IrcManager()
{
}
void
IrcManager::connect()
{
disconnect();
async_exec([] { beginConnecting(); });
}
void
IrcManager::beginConnecting()
{
IrcManager::account = const_cast<Account *>(Account::anon());
int iteration = ++connectionIteration;
auto c = new IrcConnection();
QObject::connect(c, &IrcConnection::messageReceived, &messageReceived);
QObject::connect(c, &IrcConnection::privateMessageReceived,
&privateMessageReceived);
if (account->isAnon()) {
// fetch ignored users
QString username = account->username();
QString oauthClient = account->oauthClient();
QString oauthToken = account->oauthToken();
{
QString nextLink = "https://api.twitch.tv/kraken/users/" +
username + "/blocks?limit=" + 100 +
"&client_id=" + oauthClient;
QNetworkRequest req(QUrl(nextLink + "&oauth_token=" + oauthToken));
QNetworkReply *reply = m_accessManager.get(req);
QObject::connect(reply, &QNetworkReply::finished, [=] {
twitchBlockedUsersMutex.lock();
twitchBlockedUsers.clear();
twitchBlockedUsersMutex.unlock();
QByteArray data = reply->readAll();
QJsonDocument jsonDoc(QJsonDocument::fromJson(data));
QJsonObject root = jsonDoc.object();
// nextLink =
// root.value("_links").toObject().value("next").toString();
auto blocks = root.value("blocks").toArray();
twitchBlockedUsersMutex.lock();
for (QJsonValue block : blocks) {
QJsonObject user =
block.toObject().value("user").toObject();
// display_name
twitchBlockedUsers.insert(
user.value("name").toString().toLower(), true);
}
twitchBlockedUsersMutex.unlock();
});
}
// fetch available twitch emtoes
{
QNetworkRequest req(QUrl("https://api.twitch.tv/kraken/users/" +
username + "/emotes?oauth_token=" +
oauthToken + "&client_id=" + oauthClient));
QNetworkReply *reply = m_accessManager.get(req);
QObject::connect(reply, &QNetworkReply::finished, [=] {
QByteArray data = reply->readAll();
QJsonDocument jsonDoc(QJsonDocument::fromJson(data));
QJsonObject root = jsonDoc.object();
// nextLink =
// root.value("_links").toObject().value("next").toString();
auto blocks = root.value("blocks").toArray();
twitchBlockedUsersMutex.lock();
for (QJsonValue block : blocks) {
QJsonObject user =
block.toObject().value("user").toObject();
// display_name
twitchBlockedUsers.insert(
user.value("name").toString().toLower(), true);
}
twitchBlockedUsersMutex.unlock();
});
}
}
c->setHost("irc.chat.twitch.tv");
c->setPort(6667);
c->setUserName("justinfan123");
c->setNickName("justinfan123");
c->setRealName("justinfan123");
c->sendRaw("JOIN #fourtf");
c->sendCommand(IrcCommand::createCapability("REQ", "twitch.tv/commands"));
c->sendCommand(IrcCommand::createCapability("REQ", "twitch.tv/tags"));
c->open();
connectionMutex.lock();
if (iteration == connectionIteration) {
delete connection;
c->moveToThread(QCoreApplication::instance()->thread());
connection = c;
} else {
delete c;
}
connectionMutex.unlock();
}
void
IrcManager::disconnect()
{
connectionMutex.lock();
if (connection != NULL) {
delete connection;
connection = NULL;
}
connectionMutex.unlock();
}
void
IrcManager::messageReceived(IrcMessage *message)
{
qInfo(message->command().toStdString().c_str());
// if (message->command() == "")
}
void
IrcManager::privateMessageReceived(IrcPrivateMessage *message)
{
qInfo(message->content().toStdString().c_str());
qInfo(message->target().toStdString().c_str());
auto c = Channel::getChannel(message->target().mid(1));
if (c != NULL) {
c->addMessage(std::shared_ptr<Message>(new Message(*message, *c)));
}
}
bool
IrcManager::isTwitchBlockedUser(QString const &username)
{
twitchBlockedUsersMutex.lock();
auto iterator = twitchBlockedUsers.find(username);
if (iterator == twitchBlockedUsers.end()) {
twitchBlockedUsersMutex.unlock();
return false;
}
twitchBlockedUsersMutex.unlock();
return true;
}
bool
IrcManager::tryAddIgnoredUser(QString const &username, QString &errorMessage)
{
QUrl url("https://api.twitch.tv/kraken/users/" + account->username() +
"/blocks/" + username + "?oauth_token=" + account->oauthToken() +
"&client_id=" + account->oauthClient());
QNetworkRequest request(url);
auto reply = m_accessManager.put(request, QByteArray());
reply->waitForReadyRead(10000);
if (reply->error() == QNetworkReply::NoError) {
twitchBlockedUsersMutex.lock();
twitchBlockedUsers.insert(username, true);
twitchBlockedUsersMutex.unlock();
delete reply;
return true;
}
errorMessage = "Error while ignoring user \"" + username + "\": " +
reply->errorString();
return false;
}
void
IrcManager::addIgnoredUser(QString const &username)
{
QString errorMessage;
if (!tryAddIgnoredUser(username, errorMessage)) {
#pragma message WARN("Implement IrcManager::addIgnoredUser")
}
}
bool
IrcManager::tryRemoveIgnoredUser(QString const &username, QString &errorMessage)
{
QUrl url("https://api.twitch.tv/kraken/users/" + account->username() +
"/blocks/" + username + "?oauth_token=" + account->oauthToken() +
"&client_id=" + account->oauthClient());
QNetworkRequest request(url);
auto reply = m_accessManager.deleteResource(request);
reply->waitForReadyRead(10000);
if (reply->error() == QNetworkReply::NoError) {
twitchBlockedUsersMutex.lock();
twitchBlockedUsers.remove(username);
twitchBlockedUsersMutex.unlock();
delete reply;
return true;
}
errorMessage = "Error while unignoring user \"" + username + "\": " +
reply->errorString();
return false;
}
void
IrcManager::removeIgnoredUser(QString const &username)
{
QString errorMessage;
if (!tryRemoveIgnoredUser(username, errorMessage)) {
#pragma message WARN("TODO: Implement IrcManager::removeIgnoredUser")
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2010 Martin Hebnes Pedersen, martinhpedersen @ "google mail"
* All rights reserved. Distributed under the terms of the MIT License.
*/
#include "HTGTweetItem.h"
HTGTweetItem::HTGTweetItem(HTTweet *theTweet) : BListItem() {
this->theTweet = theTweet;
textView = NULL;
}
int HTGTweetItem::calculateSize(BView *owner) {
BFont textFont;
owner->GetFont(&textFont);
float calculatedSize = 0;
float sizeOfTextView = 0;
string tweetContent = theTweet->getText();
/*Create a testView for the text, so we can calculate the number of line breaks*/
BRect textRect(72,0, owner->Frame().right, 0);
HTGTweetTextView *calcView = new HTGTweetTextView(textRect, theTweet->getScreenName().c_str(), BRect(0,0,owner->Frame().right-72,300), B_FOLLOW_LEFT_RIGHT, B_WILL_DRAW);
calcView->setTweetId(theTweet->getId());
textFont.SetEncoding(B_UNICODE_UTF8);
textFont.SetSize(textFont.Size()-2);
calcView->SetFontAndColor(&textFont);
calcView->SetWordWrap(true);
calcView->MakeEditable(false);
calcView->SetText(theTweet->getText().c_str());
font_height height;
calcView->GetFontHeight(&height);
float lineHeight = (height.ascent + height.descent + height.leading);
if(textFont.Size() > 11)
lineHeight += (textFont.Size()-11)*1.5f;
sizeOfTextView = calcView->CountLines()*lineHeight;
calculatedSize = sizeOfTextView+(lineHeight+3)*2;
if(calculatedSize < 60)
calculatedSize = 60;
delete calcView;
return (int)(calculatedSize + 0.5f);
}
void HTGTweetItem::Update(BView *owner, const BFont* font) {
theTweet->setView(owner);
SetHeight(calculateSize(owner));
}
void HTGTweetItem::DrawItem(BView *owner, BRect frame, bool complete) {
BFont textFont;
owner->GetFont(&textFont);
font_height height;
owner->GetFontHeight(&height);
float lineHeight = (height.ascent + height.descent + height.leading);
/*Write screen name*/
owner->SetHighColor(100,100,100); //Or maybe twitter's color: 000,153,185 (blue)?
owner->MovePenTo(frame.left+60+4, frame.top+lineHeight);
owner->DrawString(theTweet->getScreenName().c_str());
/*Write time*/
owner->SetHighColor(128,128,128);
owner->MovePenTo(frame.right-textFont.StringWidth(theTweet->getRelativeDate().c_str())-5, frame.top+12);
owner->DrawString(theTweet->getRelativeDate().c_str());
/*Write source name*/
if(theTweet->getSourceName().length() < 25 && theTweet->getSourceName().length() > 1) {
std::string viaString = theTweet->getSourceName();
viaString.insert(0, "via ");
BFont textFont;
BFont currentFont;
owner->GetFont(&textFont);
owner->GetFont(¤tFont);
textFont.SetEncoding(B_UNICODE_UTF8);
textFont.SetSize(textFont.Size()-2);
owner->SetFont(&textFont, B_FONT_ALL);
owner->SetHighColor(128,128,128);
owner->MovePenTo(frame.right-textFont.StringWidth(viaString.c_str())-5, frame.bottom-5);
owner->DrawString(viaString.c_str());
owner->SetFont(¤tFont);
}
/*Write text*/
BRect textRect(60+4,frame.top+lineHeight+3, frame.right, frame.bottom-lineHeight);
if(textView == NULL) {
textView = new HTGTweetTextView(textRect, theTweet->getScreenName().c_str(), BRect(0,0,frame.right-60-4,frame.bottom-lineHeight), B_FOLLOW_LEFT_RIGHT, B_WILL_DRAW);
owner->AddChild(textView);
textFont.SetEncoding(B_UNICODE_UTF8);
textFont.SetSize(textFont.Size()-2);
textView->SetFontAndColor(&textFont);
textView->SetWordWrap(true);
textView->MakeEditable(false);
textView->setTweetId(theTweet->getId());
textView->SetText(theTweet->getText().c_str());
}
else {
textFont.SetEncoding(B_UNICODE_UTF8);
textFont.SetSize(textFont.Size()-2);
textView->SetFontAndColor(&textFont);
textView->MoveTo(textRect.left, textRect.top);
textView->ResizeTo(textRect.Width(), textRect.Height());
textView->SetTextRect(BRect(0,0,frame.right-60-4,frame.bottom));
}
/*Draw seperator*/
owner->StrokeLine(BPoint(frame.left, frame.bottom), BPoint(frame.right, frame.bottom));
/*Draw userIcon*/
if(!theTweet->isDownloadingBitmap()) {
//theTweet->waitUntilDownloadComplete();
owner->SetDrawingMode(B_OP_ALPHA);
owner->DrawBitmapAsync(theTweet->getBitmap(), BRect(frame.left+9, frame.top+5+((Height()-60)/2), frame.left+48+8, frame.top+72-20+((Height()-60)/2)));
owner->SetDrawingMode(B_OP_OVER);
}
}
HTTweet* HTGTweetItem::getTweetPtr() {
return theTweet;
}
HTGTweetItem::~HTGTweetItem() {
if(textView != NULL) {
textView->RemoveSelf();
delete textView;
}
delete theTweet;
}
<commit_msg>Tweaked the constants.<commit_after>/*
* Copyright 2010 Martin Hebnes Pedersen, martinhpedersen @ "google mail"
* All rights reserved. Distributed under the terms of the MIT License.
*/
#include "HTGTweetItem.h"
HTGTweetItem::HTGTweetItem(HTTweet *theTweet) : BListItem() {
this->theTweet = theTweet;
textView = NULL;
}
int HTGTweetItem::calculateSize(BView *owner) {
BFont textFont;
owner->GetFont(&textFont);
float calculatedSize = 0;
float sizeOfTextView = 0;
string tweetContent = theTweet->getText();
/*Create a testView for the text, so we can calculate the number of line breaks*/
BRect textRect(72,0, owner->Frame().right, 0);
HTGTweetTextView *calcView = new HTGTweetTextView(textRect, theTweet->getScreenName().c_str(), BRect(0,0,owner->Frame().right-72,300), B_FOLLOW_LEFT_RIGHT, B_WILL_DRAW);
calcView->setTweetId(theTweet->getId());
textFont.SetEncoding(B_UNICODE_UTF8);
textFont.SetSize(textFont.Size()-2);
calcView->SetFontAndColor(&textFont);
calcView->SetWordWrap(true);
calcView->MakeEditable(false);
calcView->SetText(theTweet->getText().c_str());
font_height height;
calcView->GetFontHeight(&height);
float lineHeight = (height.ascent + height.descent + height.leading);
if(textFont.Size() > 10)
lineHeight += (textFont.Size()-11)*1.8f;
sizeOfTextView = calcView->CountLines()*lineHeight;
calculatedSize = sizeOfTextView+(lineHeight+3)*1.8;
if(calculatedSize < 60)
calculatedSize = 60;
delete calcView;
return (int)(calculatedSize + 0.5f);
}
void HTGTweetItem::Update(BView *owner, const BFont* font) {
theTweet->setView(owner);
SetHeight(calculateSize(owner));
}
void HTGTweetItem::DrawItem(BView *owner, BRect frame, bool complete) {
BFont textFont;
owner->GetFont(&textFont);
font_height height;
owner->GetFontHeight(&height);
float lineHeight = (height.ascent + height.descent + height.leading);
/*Write screen name*/
owner->SetHighColor(100,100,100); //Or maybe twitter's color: 000,153,185 (blue)?
owner->MovePenTo(frame.left+60+4, frame.top+lineHeight);
owner->DrawString(theTweet->getScreenName().c_str());
/*Write time*/
owner->SetHighColor(128,128,128);
owner->MovePenTo(frame.right-textFont.StringWidth(theTweet->getRelativeDate().c_str())-5, frame.top+lineHeight);
owner->DrawString(theTweet->getRelativeDate().c_str());
/*Write source name*/
if(theTweet->getSourceName().length() < 25 && theTweet->getSourceName().length() > 1) {
std::string viaString = theTweet->getSourceName();
viaString.insert(0, "via ");
BFont textFont;
BFont currentFont;
owner->GetFont(&textFont);
owner->GetFont(¤tFont);
textFont.SetEncoding(B_UNICODE_UTF8);
textFont.SetSize(textFont.Size()-2);
owner->SetFont(&textFont, B_FONT_ALL);
owner->SetHighColor(128,128,128);
owner->MovePenTo(frame.right-textFont.StringWidth(viaString.c_str())-5, frame.bottom-5);
owner->DrawString(viaString.c_str());
owner->SetFont(¤tFont);
}
/*Write text*/
BRect textRect(60+4,frame.top+lineHeight+3, frame.right, frame.bottom-lineHeight);
if(textView == NULL) {
textView = new HTGTweetTextView(textRect, theTweet->getScreenName().c_str(), BRect(0,0,frame.right-60-4,frame.bottom-lineHeight), B_FOLLOW_LEFT_RIGHT, B_WILL_DRAW);
owner->AddChild(textView);
textFont.SetEncoding(B_UNICODE_UTF8);
textFont.SetSize(textFont.Size()-2);
textView->SetFontAndColor(&textFont);
textView->SetWordWrap(true);
textView->MakeEditable(false);
textView->setTweetId(theTweet->getId());
textView->SetText(theTweet->getText().c_str());
}
else {
textFont.SetEncoding(B_UNICODE_UTF8);
textFont.SetSize(textFont.Size()-2);
textView->SetFontAndColor(&textFont);
textView->MoveTo(textRect.left, textRect.top);
textView->ResizeTo(textRect.Width(), textRect.Height());
textView->SetTextRect(BRect(0,0,frame.right-60-4,frame.bottom));
}
/*Draw seperator*/
owner->StrokeLine(BPoint(frame.left, frame.bottom), BPoint(frame.right, frame.bottom));
/*Draw userIcon*/
if(!theTweet->isDownloadingBitmap()) {
//theTweet->waitUntilDownloadComplete();
owner->SetDrawingMode(B_OP_ALPHA);
owner->DrawBitmapAsync(theTweet->getBitmap(), BRect(frame.left+9, frame.top+5+((Height()-60)/2), frame.left+48+8, frame.top+72-20+((Height()-60)/2)));
owner->SetDrawingMode(B_OP_OVER);
}
}
HTTweet* HTGTweetItem::getTweetPtr() {
return theTweet;
}
HTGTweetItem::~HTGTweetItem() {
if(textView != NULL) {
textView->RemoveSelf();
delete textView;
}
delete theTweet;
}
<|endoftext|>
|
<commit_before>#include <stdio.h>
#include <stdlib.h>
#include "App.h"
#include <Directory.h>
#include <NodeMonitor.h>
#include <Entry.h>
#include <Path.h>
#include <String.h>
#include <File.h>
/*
* Runs a command in the terminal, given the string you'd type
*/
BString*
run_script(const char *cmd)
{
char buf[BUFSIZ];
FILE *ptr;
BString *output = new BString;
if ((ptr = popen(cmd, "r")) != NULL)
while (fgets(buf, BUFSIZ, ptr) != NULL)
output->Append(buf);
(void) pclose(ptr);
return output;
}
int
parse_command(BString command)
{
if(command.Compare("RESET\n") == 0)
{
printf("Burn Everything. 8D\n");
run_script("rm -rf ~/Dropbox");
create_directory("/boot/home/Dropbox", 0x0777);
}
else if(command.Compare("FILE ",5) == 0)
{
BString path, dirpath;
command.CopyInto(path,5,command.FindLast(" ") - 5);
printf("create a file at |%s|\n",path.String());
int32 split = path.FindLast("/");
path.CopyInto(dirpath,0,split);
if(dirpath != "")
create_directory(dirpath,0x0777);
run_script(BString("python db_get.py ") << path << " /boot/home/Dropbox/" << path);
}
else if(command.Compare("FOLDER ",7) == 0)
{
BString path;
int last = command.FindLast(" ");
command.CopyInto(path,7,last - 7);
printf("create a folder at |%s|\n", path.String());
path.Prepend("/boot/home/Dropbox");
create_directory(path, 0x0777);
}
else if(command.Compare("REMOVE ",7) == 0)
{
BString path;
command.CopyInto(path,7,command.FindLast(" ") - 7);
printf("Remove whatever is at |%s|\n", path.String());
}
else
{
printf("Something more specific.\n");
}
return 0;
}
int32
get_next_line(BString *src, BString *dest)
{
int32 eol = src->FindFirst('\n');
if(eol == B_ERROR)
return B_ERROR;
src->MoveInto(*dest,0,eol+1);
return B_OK;
}
/*
* Sets up the Node Monitoring for Dropbox folder and contents
* and creates data structure for determining which files are deleted or edited
*/
App::App(void)
: BApplication("application/x-vnd.lh-MyDropboxClient")
{
//ask Dropbox for deltas!
BString *delta_commands = run_script("python db_delta.py");
BString line;
while(get_next_line(delta_commands,&line) == B_OK)
{
(void) parse_command(line);
}
//start watching ~/Dropbox folder contents (create, delete, move)
BDirectory dir("/boot/home/Dropbox"); //don't use ~ here
node_ref nref;
status_t err;
if(dir.InitCheck() == B_OK){
dir.GetNodeRef(&nref);
err = watch_node(&nref, B_WATCH_DIRECTORY, BMessenger(this));
if(err != B_OK)
printf("Watch Node: Not OK\n");
}
// record each file in the folder so that we know the name on deletion
BEntry *entry = new BEntry;
status_t err2;
err = dir.GetNextEntry(entry);
BPath *path;
BFile *file;
while(err == B_OK) //loop over files
{
file = new BFile(entry, B_READ_ONLY);
this->tracked_files.AddItem((void*)(file)); //add file to my list
path = new BPath;
entry->GetPath(path);
printf("tracking: %s\n",path->Path());
this->tracked_filepaths.AddItem((void*)path);
err2 = entry->GetNodeRef(&nref);
if(err2 == B_OK)
{
err2 = watch_node(&nref, B_WATCH_STAT|B_WATCH_DIRECTORY, be_app_messenger); //watch for edits
if(err2 != B_OK)
printf("Watch file Node: Not OK\n");
}
entry = new BEntry;
err = dir.GetNextEntry(entry);
}
//delete that last BEntry...
}
/*
* Given a local file path,
* call the script to delete the corresponding Dropbox file
*/
void
delete_file_on_dropbox(const char * filepath)
{
printf("Telling Dropbox to Delete\n");
BString s, dbfp;
s = BString(filepath);
s.RemoveFirst("/boot/home/Dropbox");
dbfp << "python db_rm.py " << s;
printf("%s\n",dbfp.String());
run_script(dbfp);
}
/*
* Convert a local absolute filepath to a Dropbox one
* by removing the <path to Dropbox> from the beginning
*/
BString local_to_db_filepath(const char * local_path)
{
BString s;
s = BString(local_path);
s.RemoveFirst("/boot/home/Dropbox/");
return s;
}
/*
* Given the local file path of a new file,
* run the script to upload it to Dropbox
*/
void
add_file_to_dropbox(const char * filepath)
{
BString s, dbfp;
dbfp = local_to_db_filepath(filepath);
s << "python db_put.py " << BString(filepath) << " " << dbfp;
printf("local filepath:%s\n",filepath);
printf("dropbox filepath:%s\n",dbfp.String());
run_script(s.String());
}
/*
* Given the local file path of a new folder,
* run the script to mkdir on Dropbox
*/
void
add_folder_to_dropbox(const char * filepath)
{
BString s;
s << "python db_mkdir.py " << local_to_db_filepath(filepath);
printf("local filepath: %s\n", filepath);
printf("db filepath: %s\n", local_to_db_filepath(filepath).String());
run_script(s.String());
}
/*
* TODO
* Given a "file/folder moved" message,
* figure out whether to call add or delete
* and with what file path
* and then call add/delete.
*/
void
moved_file(BMessage *msg)
{
//is this file being move into or out of ~/Dropbox?
run_script("python db_ls.py");
}
/*
* Given a local file path,
* update the corresponding file on Dropbox
*/
void
update_file_in_dropbox(const char * filepath)
{
printf("Putting %s to Dropbox.\n", filepath);
add_file_to_dropbox(filepath); //just put it?
}
/*
* Message Handling Function
* If it's a node monitor message,
* then figure out what to do based on it.
* Otherwise, let BApplication handle it.
*/
void
App::MessageReceived(BMessage *msg)
{
switch(msg->what)
{
case B_NODE_MONITOR:
{
printf("Received Node Monitor Alert\n");
status_t err;
int32 opcode;
err = msg->FindInt32("opcode",&opcode);
if(err == B_OK)
{
printf("what:%d\topcode:%d\n",msg->what, opcode);
switch(opcode)
{
case B_ENTRY_CREATED:
{
printf("NEW FILE\n");
entry_ref ref;
BPath path;
const char * name;
// unpack the message
msg->FindInt32("device",&ref.device);
msg->FindInt64("directory",&ref.directory);
msg->FindString("name",&name);
printf("name:%s\n",name);
ref.set_name(name);
BEntry new_file = BEntry(&ref);
if(new_file.IsDirectory())
{
printf("Actually, it's a directory!\n");
//add to Dropbox
new_file.GetPath(&path);
add_folder_to_dropbox(path.Path());
//do I need a global data structure for BDirectories?
//track folder
node_ref nref;
err = new_file.GetNodeRef(&nref);
if(err == B_OK)
{
err = watch_node(&nref, B_WATCH_STAT | B_WATCH_DIRECTORY, be_app_messenger);
if(err != B_OK)
printf("Watch new folder %s: Not Ok.\n", path.Path());
}
}
else //it's a file (or sym link)
{
// add the new file to Dropbox
new_file.GetPath(&path);
add_file_to_dropbox(path.Path());
// add the new file to global tracking lists
BFile *file = new BFile(&new_file, B_READ_ONLY);
this->tracked_files.AddItem((void*)file);
BPath *path2 = new BPath;
new_file.GetPath(path2);
this->tracked_filepaths.AddItem((void*)path2);
// listen for EDIT alerts on the new file
node_ref nref;
err = new_file.GetNodeRef(&nref);
if(err == B_OK)
{
err = watch_node(&nref, B_WATCH_STAT, be_app_messenger);
if(err != B_OK)
printf("Watch new file %s: Not Ok.\n", path2->Path());
}
}
break;
}
case B_ENTRY_MOVED:
{
printf("MOVED FILE\n");
moved_file(msg);
break;
}
case B_ENTRY_REMOVED:
{
printf("DELETED FILE\n");
node_ref nref, cref;
msg->FindInt32("device",&nref.device);
msg->FindInt64("node",&nref.node);
BFile *filePtr;
int32 ktr = 0;
int32 limit = this->tracked_files.CountItems();
printf("About to loop %d times\n", limit);
while((filePtr = (BFile*)this->tracked_files.ItemAt(ktr))&&(ktr<limit))
{
printf("In loop.\n");
filePtr->GetNodeRef(&cref);
printf("GotNodeRef\n");
if(nref == cref)
{
printf("Deleting it\n");
BPath *path = (BPath*)this->tracked_filepaths.ItemAt(ktr);
printf("%s\n",path->Path());
delete_file_on_dropbox(path->Path());
this->tracked_files.RemoveItem(ktr);
this->tracked_filepaths.RemoveItem(ktr);
break; //break out of loop
}
ktr++;
}
break;
}
case B_STAT_CHANGED:
{
printf("EDITED FILE\n");
node_ref nref1,nref2;
msg->FindInt32("device",&nref1.device);
msg->FindInt64("node",&nref1.node);
BFile * filePtr;
int32 ktr = 0;
while((filePtr = (BFile *)this->tracked_files.ItemAt(ktr++)))
{
filePtr->GetNodeRef(&nref2);
if(nref1 == nref2)
{
BPath *path;
path = (BPath*)this->tracked_filepaths.ItemAt(ktr-1);
update_file_in_dropbox(path->Path());
break;
}
}
break;
}
default:
{
printf("default case opcode...\n");
}
}
}
break;
}
default:
{
printf("default msg\n");
BApplication::MessageReceived(msg);
break;
}
}
}
int
main(void)
{
//set up application (watch Dropbox folder & contents)
App *app = new App();
//start the application
app->Run();
//clean up now that we're shutting down
delete app;
return 0;
}
<commit_msg>using fork and execlp rather than popen so that the shell escaping doesn't matter. :D paired with Alan.<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include "App.h"
#include <Directory.h>
#include <NodeMonitor.h>
#include <Entry.h>
#include <Path.h>
#include <String.h>
#include <File.h>
/*
* Runs a command in the terminal, given the string you'd type
*/
BString*
run_script(const char *cmd)
{
char buf[BUFSIZ];
FILE *ptr;
BString *output = new BString;
if ((ptr = popen(cmd, "r")) != NULL)
while (fgets(buf, BUFSIZ, ptr) != NULL)
output->Append(buf);
(void) pclose(ptr);
return output;
}
/*
* Convert a Dropbox path to a local absolute filepath
* by adding the <path to Dropbox> to the beginning
*/
BString db_to_local_filepath(const char * local_path)
{
BString s;
s << "/boot/home/Dropbox/" << local_path;
return s;
}
BString*
get_or_put(const char *cmd, const char *path1, const char *path2)
{
pid_t pid = fork();
BString *output = new BString;
char buf[BUFSIZ];
//open pipe
int fd[2];
pipe(fd);
if(pid < 0)
{
return output; //error
}
if(pid == 0)
{
//child
//make stdout the pipe
dup2(fd[0],STDOUT_FILENO);
execlp("python","python",cmd,path1,path2,(char*)0);
}
else //parent
{
dup2(fd[1],STDIN_FILENO);
//wait for child process to finish
int status;
waitpid(pid, &status, 0);
//use read-end of pipe to fill in BString return value.
while(fgets(buf,BUFSIZ,stdin) !=NULL)
{
output->Append("RAWR");
output->Append(buf);
}
printf("output:\n%s\n",output->String());
}
return output;
}
BString*
one_path_arg(const char *cmd, const char *path)
{
pid_t pid = fork();
BString *output = new BString;
char buf[BUFSIZ];
int fd[2];
pipe(fd);
if(pid < 0)
{
dup2(fd[0],STDOUT_FILENO);
execlp("python","python",cmd,path);
}
else //parent
{
dup2(fd[1],STDIN_FILENO);
while(fgets(buf,BUFSIZ,stdin) != NULL)
output->Append(buf);
}
return output;
}
int
parse_command(BString command)
{
if(command.Compare("RESET\n") == 0)
{
printf("Burn Everything. 8D\n");
run_script("rm -rf ~/Dropbox");
create_directory("/boot/home/Dropbox", 0x0777);
}
else if(command.Compare("FILE ",5) == 0)
{
BString path, dirpath;
command.CopyInto(path,5,command.FindLast(" ") - 5);
printf("create a file at |%s|\n",path.String());
int32 split = path.FindLast("/");
path.CopyInto(dirpath,0,split);
if(dirpath != "")
create_directory(dirpath,0x0777);
//run_script(BString("python db_get.py ") << path << " /boot/home/Dropbox/" << path);
get_or_put("db_get.py",path.String(), db_to_local_filepath(path.String()));
}
else if(command.Compare("FOLDER ",7) == 0)
{
BString path;
int last = command.FindLast(" ");
command.CopyInto(path,7,last - 7);
printf("create a folder at |%s|\n", path.String());
path.Prepend("/boot/home/Dropbox");
create_directory(path, 0x0777);
}
else if(command.Compare("REMOVE ",7) == 0)
{
BString path;
command.CopyInto(path,7,command.FindLast(" ") - 7);
printf("Remove whatever is at |%s|\n", path.String());
}
else
{
printf("Something more specific.\n");
}
return 0;
}
int32
get_next_line(BString *src, BString *dest)
{
int32 eol = src->FindFirst('\n');
if(eol == B_ERROR)
return B_ERROR;
src->MoveInto(*dest,0,eol+1);
return B_OK;
}
/*
* Sets up the Node Monitoring for Dropbox folder and contents
* and creates data structure for determining which files are deleted or edited
*/
App::App(void)
: BApplication("application/x-vnd.lh-MyDropboxClient")
{
//ask Dropbox for deltas!
BString *delta_commands = run_script("python db_delta.py");
BString line;
while(get_next_line(delta_commands,&line) == B_OK)
{
(void) parse_command(line);
}
//start watching ~/Dropbox folder contents (create, delete, move)
BDirectory dir("/boot/home/Dropbox"); //don't use ~ here
node_ref nref;
status_t err;
if(dir.InitCheck() == B_OK){
dir.GetNodeRef(&nref);
err = watch_node(&nref, B_WATCH_DIRECTORY, BMessenger(this));
if(err != B_OK)
printf("Watch Node: Not OK\n");
}
// record each file in the folder so that we know the name on deletion
BEntry *entry = new BEntry;
status_t err2;
err = dir.GetNextEntry(entry);
BPath *path;
BFile *file;
while(err == B_OK) //loop over files
{
file = new BFile(entry, B_READ_ONLY);
this->tracked_files.AddItem((void*)(file)); //add file to my list
path = new BPath;
entry->GetPath(path);
printf("tracking: %s\n",path->Path());
this->tracked_filepaths.AddItem((void*)path);
err2 = entry->GetNodeRef(&nref);
if(err2 == B_OK)
{
err2 = watch_node(&nref, B_WATCH_STAT|B_WATCH_DIRECTORY, be_app_messenger); //watch for edits
if(err2 != B_OK)
printf("Watch file Node: Not OK\n");
}
entry = new BEntry;
err = dir.GetNextEntry(entry);
}
//delete that last BEntry...
}
/*
* Given a local file path,
* call the script to delete the corresponding Dropbox file
*/
void
delete_file_on_dropbox(const char * filepath)
{
printf("Telling Dropbox to Delete\n");
BString s, dbfp;
s = BString(filepath);
s.RemoveFirst("/boot/home/Dropbox");
dbfp << "python db_rm.py " << s;
printf("%s\n",dbfp.String());
run_script(dbfp);
}
/*
* Convert a local absolute filepath to a Dropbox one
* by removing the <path to Dropbox> from the beginning
*/
BString local_to_db_filepath(const char * local_path)
{
BString s;
s = BString(local_path);
s.RemoveFirst("/boot/home/Dropbox/");
return s;
}
/*
* Given the local file path of a new file,
* run the script to upload it to Dropbox
*/
void
add_file_to_dropbox(const char * filepath)
{
get_or_put("db_put.py",filepath, local_to_db_filepath(filepath));
/*
BString s, dbfp;
dbfp = local_to_db_filepath(filepath);
s << "python db_put.py " << BString(filepath) << " " << dbfp;
printf("local filepath:%s\n",filepath);
printf("dropbox filepath:%s\n",dbfp.String());
run_script(s.String());
*/
}
/*
* Given the local file path of a new folder,
* run the script to mkdir on Dropbox
*/
void
add_folder_to_dropbox(const char * filepath)
{
one_path_arg("db_mkdir.py",local_to_db_filepath(filepath));
/*
BString s;
s << "python db_mkdir.py " << local_to_db_filepath(filepath);
printf("local filepath: %s\n", filepath);
printf("db filepath: %s\n", local_to_db_filepath(filepath).String());
run_script(s.String());
*/
}
/*
* TODO
* Given a "file/folder moved" message,
* figure out whether to call add or delete
* and with what file path
* and then call add/delete.
*/
void
moved_file(BMessage *msg)
{
//is this file being move into or out of ~/Dropbox?
run_script("python db_ls.py");
}
/*
* Given a local file path,
* update the corresponding file on Dropbox
*/
void
update_file_in_dropbox(const char * filepath)
{
printf("Putting %s to Dropbox.\n", filepath);
add_file_to_dropbox(filepath); //just put it?
}
/*
* Message Handling Function
* If it's a node monitor message,
* then figure out what to do based on it.
* Otherwise, let BApplication handle it.
*/
void
App::MessageReceived(BMessage *msg)
{
switch(msg->what)
{
case B_NODE_MONITOR:
{
printf("Received Node Monitor Alert\n");
status_t err;
int32 opcode;
err = msg->FindInt32("opcode",&opcode);
if(err == B_OK)
{
printf("what:%d\topcode:%d\n",msg->what, opcode);
switch(opcode)
{
case B_ENTRY_CREATED:
{
printf("NEW FILE\n");
entry_ref ref;
BPath path;
const char * name;
// unpack the message
msg->FindInt32("device",&ref.device);
msg->FindInt64("directory",&ref.directory);
msg->FindString("name",&name);
printf("name:%s\n",name);
ref.set_name(name);
BEntry new_file = BEntry(&ref);
if(new_file.IsDirectory())
{
printf("Actually, it's a directory!\n");
//add to Dropbox
new_file.GetPath(&path);
add_folder_to_dropbox(path.Path());
//do I need a global data structure for BDirectories?
//track folder
node_ref nref;
err = new_file.GetNodeRef(&nref);
if(err == B_OK)
{
err = watch_node(&nref, B_WATCH_STAT | B_WATCH_DIRECTORY, be_app_messenger);
if(err != B_OK)
printf("Watch new folder %s: Not Ok.\n", path.Path());
}
}
else //it's a file (or sym link)
{
// add the new file to Dropbox
new_file.GetPath(&path);
add_file_to_dropbox(path.Path());
// add the new file to global tracking lists
BFile *file = new BFile(&new_file, B_READ_ONLY);
this->tracked_files.AddItem((void*)file);
BPath *path2 = new BPath;
new_file.GetPath(path2);
this->tracked_filepaths.AddItem((void*)path2);
// listen for EDIT alerts on the new file
node_ref nref;
err = new_file.GetNodeRef(&nref);
if(err == B_OK)
{
err = watch_node(&nref, B_WATCH_STAT, be_app_messenger);
if(err != B_OK)
printf("Watch new file %s: Not Ok.\n", path2->Path());
}
}
break;
}
case B_ENTRY_MOVED:
{
printf("MOVED FILE\n");
moved_file(msg);
break;
}
case B_ENTRY_REMOVED:
{
printf("DELETED FILE\n");
node_ref nref, cref;
msg->FindInt32("device",&nref.device);
msg->FindInt64("node",&nref.node);
BFile *filePtr;
int32 ktr = 0;
int32 limit = this->tracked_files.CountItems();
printf("About to loop %d times\n", limit);
while((filePtr = (BFile*)this->tracked_files.ItemAt(ktr))&&(ktr<limit))
{
printf("In loop.\n");
filePtr->GetNodeRef(&cref);
printf("GotNodeRef\n");
if(nref == cref)
{
printf("Deleting it\n");
BPath *path = (BPath*)this->tracked_filepaths.ItemAt(ktr);
printf("%s\n",path->Path());
delete_file_on_dropbox(path->Path());
this->tracked_files.RemoveItem(ktr);
this->tracked_filepaths.RemoveItem(ktr);
break; //break out of loop
}
ktr++;
}
break;
}
case B_STAT_CHANGED:
{
printf("EDITED FILE\n");
node_ref nref1,nref2;
msg->FindInt32("device",&nref1.device);
msg->FindInt64("node",&nref1.node);
BFile * filePtr;
int32 ktr = 0;
while((filePtr = (BFile *)this->tracked_files.ItemAt(ktr++)))
{
filePtr->GetNodeRef(&nref2);
if(nref1 == nref2)
{
BPath *path;
path = (BPath*)this->tracked_filepaths.ItemAt(ktr-1);
update_file_in_dropbox(path->Path());
break;
}
}
break;
}
default:
{
printf("default case opcode...\n");
}
}
}
break;
}
default:
{
printf("default msg\n");
BApplication::MessageReceived(msg);
break;
}
}
}
int
main(void)
{
//set up application (watch Dropbox folder & contents)
App *app = new App();
//start the application
app->Run();
//clean up now that we're shutting down
delete app;
return 0;
}
<|endoftext|>
|
<commit_before>// Copyright [2015] Takashi Ogura<t.ogura@gmail.com>
#include "cv_camera/capture.h"
#include <sstream>
#include <string>
namespace cv_camera
{
namespace enc = sensor_msgs::image_encodings;
Capture::Capture(ros::NodeHandle &node, const std::string &topic_name,
int32_t buffer_size, const std::string &frame_id,
const std::string& camera_name)
: node_(node),
it_(node_),
topic_name_(topic_name),
buffer_size_(buffer_size),
frame_id_(frame_id),
info_manager_(node_, camera_name),
capture_delay_(ros::Duration(node_.param("capture_delay", 0.0)))
{
}
void Capture::loadCameraInfo()
{
std::string url;
if (node_.getParam("camera_info_url", url))
{
if (info_manager_.validateURL(url))
{
info_manager_.loadCameraInfo(url);
}
}
rescale_camera_info_ = node_.param<bool>("rescale_camera_info", false);
for (int i = 0;; ++i)
{
int code = 0;
double value = 0.0;
std::stringstream stream;
stream << "property_" << i << "_code";
const std::string param_for_code = stream.str();
stream.str("");
stream << "property_" << i << "_value";
const std::string param_for_value = stream.str();
if (!node_.getParam(param_for_code, code) || !node_.getParam(param_for_value, value))
{
break;
}
if (!cap_.set(code, value))
{
ROS_ERROR_STREAM("Setting with code " << code << " and value " << value << " failed"
<< std::endl);
}
}
}
void Capture::rescaleCameraInfo(int width, int height)
{
double width_coeff = static_cast<double>(width) / info_.width;
double height_coeff = static_cast<double>(height) / info_.height;
info_.width = width;
info_.height = height;
// See http://docs.ros.org/api/sensor_msgs/html/msg/CameraInfo.html for clarification
info_.K[0] *= width_coeff;
info_.K[2] *= width_coeff;
info_.K[4] *= height_coeff;
info_.K[5] *= height_coeff;
info_.P[0] *= width_coeff;
info_.P[2] *= width_coeff;
info_.P[5] *= height_coeff;
info_.P[6] *= height_coeff;
}
void Capture::open(int32_t device_id)
{
cap_.open(device_id);
if (!cap_.isOpened())
{
std::stringstream stream;
stream << "device_id" << device_id << " cannot be opened";
throw DeviceError(stream.str());
}
pub_ = it_.advertiseCamera(topic_name_, buffer_size_);
loadCameraInfo();
}
void Capture::open(const std::string &device_path)
{
cap_.open(device_path, cv::CAP_V4L);
if (!cap_.isOpened())
{
throw DeviceError("device_path " + device_path + " cannot be opened");
}
pub_ = it_.advertiseCamera(topic_name_, buffer_size_);
loadCameraInfo();
}
void Capture::open()
{
open(0);
}
void Capture::openFile(const std::string &file_path)
{
cap_.open(file_path);
if (!cap_.isOpened())
{
std::stringstream stream;
stream << "file " << file_path << " cannot be opened";
throw DeviceError(stream.str());
}
pub_ = it_.advertiseCamera(topic_name_, buffer_size_);
std::string url;
if (node_.getParam("camera_info_url", url))
{
if (info_manager_.validateURL(url))
{
info_manager_.loadCameraInfo(url);
}
}
}
bool Capture::capture()
{
if (cap_.read(bridge_.image))
{
ros::Time stamp = ros::Time::now() - capture_delay_;
bridge_.encoding = enc::BGR8;
bridge_.header.stamp = stamp;
bridge_.header.frame_id = frame_id_;
info_ = info_manager_.getCameraInfo();
if (info_.height == 0 && info_.width == 0)
{
info_.height = bridge_.image.rows;
info_.width = bridge_.image.cols;
}
else if (info_.height != bridge_.image.rows || info_.width != bridge_.image.cols)
{
if (rescale_camera_info_)
{
int old_width = info_.width;
int old_height = info_.height;
rescaleCameraInfo(bridge_.image.cols, bridge_.image.rows);
ROS_INFO_ONCE("Camera calibration automatically rescaled from %dx%d to %dx%d",
old_width, old_height, bridge_.image.cols, bridge_.image.rows);
}
else
{
ROS_WARN_ONCE("Calibration resolution %dx%d does not match camera resolution %dx%d. "
"Use rescale_camera_info param for rescaling",
info_.width, info_.height, bridge_.image.cols, bridge_.image.rows);
}
}
info_.header.stamp = stamp;
info_.header.frame_id = frame_id_;
return true;
}
return false;
}
void Capture::publish()
{
pub_.publish(*getImageMsgPtr(), info_);
}
bool Capture::setPropertyFromParam(int property_id, const std::string ¶m_name)
{
if (cap_.isOpened())
{
double value = 0.0;
if (node_.getParam(param_name, value))
{
ROS_INFO("setting property %s = %lf", param_name.c_str(), value);
return cap_.set(property_id, value);
}
}
return true;
}
} // namespace cv_camera
<commit_msg>Adding MONO8 format if number of channels is 1<commit_after>// Copyright [2015] Takashi Ogura<t.ogura@gmail.com>
#include "cv_camera/capture.h"
#include <sstream>
#include <string>
namespace cv_camera
{
namespace enc = sensor_msgs::image_encodings;
Capture::Capture(ros::NodeHandle &node, const std::string &topic_name,
int32_t buffer_size, const std::string &frame_id,
const std::string& camera_name)
: node_(node),
it_(node_),
topic_name_(topic_name),
buffer_size_(buffer_size),
frame_id_(frame_id),
info_manager_(node_, camera_name),
capture_delay_(ros::Duration(node_.param("capture_delay", 0.0)))
{
}
void Capture::loadCameraInfo()
{
std::string url;
if (node_.getParam("camera_info_url", url))
{
if (info_manager_.validateURL(url))
{
info_manager_.loadCameraInfo(url);
}
}
rescale_camera_info_ = node_.param<bool>("rescale_camera_info", false);
for (int i = 0;; ++i)
{
int code = 0;
double value = 0.0;
std::stringstream stream;
stream << "property_" << i << "_code";
const std::string param_for_code = stream.str();
stream.str("");
stream << "property_" << i << "_value";
const std::string param_for_value = stream.str();
if (!node_.getParam(param_for_code, code) || !node_.getParam(param_for_value, value))
{
break;
}
if (!cap_.set(code, value))
{
ROS_ERROR_STREAM("Setting with code " << code << " and value " << value << " failed"
<< std::endl);
}
}
}
void Capture::rescaleCameraInfo(int width, int height)
{
double width_coeff = static_cast<double>(width) / info_.width;
double height_coeff = static_cast<double>(height) / info_.height;
info_.width = width;
info_.height = height;
// See http://docs.ros.org/api/sensor_msgs/html/msg/CameraInfo.html for clarification
info_.K[0] *= width_coeff;
info_.K[2] *= width_coeff;
info_.K[4] *= height_coeff;
info_.K[5] *= height_coeff;
info_.P[0] *= width_coeff;
info_.P[2] *= width_coeff;
info_.P[5] *= height_coeff;
info_.P[6] *= height_coeff;
}
void Capture::open(int32_t device_id)
{
cap_.open(device_id);
if (!cap_.isOpened())
{
std::stringstream stream;
stream << "device_id" << device_id << " cannot be opened";
throw DeviceError(stream.str());
}
pub_ = it_.advertiseCamera(topic_name_, buffer_size_);
loadCameraInfo();
}
void Capture::open(const std::string &device_path)
{
cap_.open(device_path, cv::CAP_V4L);
if (!cap_.isOpened())
{
throw DeviceError("device_path " + device_path + " cannot be opened");
}
pub_ = it_.advertiseCamera(topic_name_, buffer_size_);
loadCameraInfo();
}
void Capture::open()
{
open(0);
}
void Capture::openFile(const std::string &file_path)
{
cap_.open(file_path);
if (!cap_.isOpened())
{
std::stringstream stream;
stream << "file " << file_path << " cannot be opened";
throw DeviceError(stream.str());
}
pub_ = it_.advertiseCamera(topic_name_, buffer_size_);
std::string url;
if (node_.getParam("camera_info_url", url))
{
if (info_manager_.validateURL(url))
{
info_manager_.loadCameraInfo(url);
}
}
}
bool Capture::capture()
{
if (cap_.read(bridge_.image))
{
ros::Time stamp = ros::Time::now() - capture_delay_;
bridge_.encoding = bridge_.image.channels() == 3 ? enc::BGR8 : enc::MONO8;
bridge_.header.stamp = stamp;
bridge_.header.frame_id = frame_id_;
info_ = info_manager_.getCameraInfo();
if (info_.height == 0 && info_.width == 0)
{
info_.height = bridge_.image.rows;
info_.width = bridge_.image.cols;
}
else if (info_.height != bridge_.image.rows || info_.width != bridge_.image.cols)
{
if (rescale_camera_info_)
{
int old_width = info_.width;
int old_height = info_.height;
rescaleCameraInfo(bridge_.image.cols, bridge_.image.rows);
ROS_INFO_ONCE("Camera calibration automatically rescaled from %dx%d to %dx%d",
old_width, old_height, bridge_.image.cols, bridge_.image.rows);
}
else
{
ROS_WARN_ONCE("Calibration resolution %dx%d does not match camera resolution %dx%d. "
"Use rescale_camera_info param for rescaling",
info_.width, info_.height, bridge_.image.cols, bridge_.image.rows);
}
}
info_.header.stamp = stamp;
info_.header.frame_id = frame_id_;
return true;
}
return false;
}
void Capture::publish()
{
pub_.publish(*getImageMsgPtr(), info_);
}
bool Capture::setPropertyFromParam(int property_id, const std::string ¶m_name)
{
if (cap_.isOpened())
{
double value = 0.0;
if (node_.getParam(param_name, value))
{
ROS_INFO("setting property %s = %lf", param_name.c_str(), value);
return cap_.set(property_id, value);
}
}
return true;
}
} // namespace cv_camera
<|endoftext|>
|
<commit_before>#include "types.h"
#include "kernel.hh"
#include "amd64.h"
#include "spinlock.h"
#include "condvar.h"
#include "proc.hh"
#include "cpu.hh"
#include "sched.hh"
#include "percpu.hh"
// XXX(sbw) these should be padded out
struct idle : public pad {
struct proc *cur;
struct proc *heir;
SLIST_HEAD(zombies, proc) zombies;
struct spinlock lock;
};
static percpu<idle> idlem;
struct proc * idlep[NCPU] __mpalign__;
struct heir {
struct proc *proc;
__padout__;
} __mpalign__;
struct heir heir[NCPU] __mpalign__;
void idleloop(void);
struct proc *
idleproc(void)
{
assert(mycpu()->ncli > 0);
return idlep[mycpu()->id];
}
void
idlezombie(struct proc *p)
{
acquire(&idlem[mycpu()->id].lock);
SLIST_INSERT_HEAD(&idlem[mycpu()->id].zombies, p, child_next);
release(&idlem[mycpu()->id].lock);
}
void
idlebequeath(void)
{
// Only the current idle thread may call this function
struct heir *h;
assert(mycpu()->ncli > 0);
assert(myproc() == idlep[mycpu()->id]);
h = &heir[mycpu()->id];
assert(h->proc != nullptr);
idlep[mycpu()->id] = h->proc;
acquire(&h->proc->lock);
h->proc->set_state(RUNNABLE);
release(&h->proc->lock);
}
static void
idleheir(void *x)
{
post_swtch();
heir[mycpu()->id].proc = nullptr;
idleloop();
}
static inline void
finishzombies(void)
{
struct idle *i = &idlem[mycpu()->id];
if (!SLIST_EMPTY(&i->zombies)) {
struct proc *p, *np;
acquire(&i->lock);
SLIST_FOREACH_SAFE(p, &i->zombies, child_next, np) {
SLIST_REMOVE(&i->zombies, p, proc, child_next);
finishproc(p);
}
release(&i->lock);
}
}
void
idleloop(void)
{
struct heir *h;
h = &heir[mycpu()->id];
// Test the work queue
//extern void testwq(void);
//testwq();
//extern void benchwq(void);
//benchwq();
// Enabling mtrace calls in scheduler generates many mtrace_call_entrys.
// mtrace_call_set(1, cpu->id);
//mtstart(scheduler, idlep);
sti();
for (;;) {
acquire(&myproc()->lock);
myproc()->set_state(RUNNABLE);
sched();
finishzombies();
if (steal() == 0) {
int worked;
do {
assert(mycpu()->ncli == 0);
// If we don't have an heir, try to allocate one
if (h->proc == nullptr) {
struct proc *p;
p = allocproc();
if (p == nullptr)
break;
snprintf(p->name, sizeof(p->name), "idleh_%u", mycpu()->id);
p->cpuid = mycpu()->id;
p->cpu_pin = 1;
p->context->rip = (u64)idleheir;
p->cwd = nullptr;
h->proc = p;
}
worked = wq_trywork();
// If we are no longer the idle thread, exit
if (worked && idlep[mycpu()->id] != myproc())
exit();
} while(worked);
sti();
}
}
}
void
initidle(void)
{
struct proc *p = allocproc();
if (!p)
panic("initidle allocproc");
SLIST_INIT(&idlem[cpunum()].zombies);
initlock(&idlem[cpunum()].lock, "idle_lock", LOCKSTAT_IDLE);
snprintf(p->name, sizeof(p->name), "idle_%u", cpunum());
mycpu()->proc = p;
myproc()->cpuid = cpunum();
myproc()->cpu_pin = 1;
idlep[cpunum()] = p;
}
<commit_msg>Try using percpu in idle.cc<commit_after>#include "types.h"
#include "kernel.hh"
#include "amd64.h"
#include "spinlock.h"
#include "condvar.h"
#include "proc.hh"
#include "cpu.hh"
#include "sched.hh"
#include "percpu.hh"
struct idle : public pad {
struct proc *cur;
struct proc *heir;
SLIST_HEAD(zombies, proc) zombies;
struct spinlock lock;
};
static percpu<idle> idlem;
void idleloop(void);
struct proc *
idleproc(void)
{
assert(mycpu()->ncli > 0);
return idlem->cur;
}
void
idlezombie(struct proc *p)
{
acquire(&idlem[mycpu()->id].lock);
SLIST_INSERT_HEAD(&idlem[mycpu()->id].zombies, p, child_next);
release(&idlem[mycpu()->id].lock);
}
void
idlebequeath(void)
{
// Only the current idle thread may call this function
assert(mycpu()->ncli > 0);
assert(myproc() == idlem->cur);
assert(idlem->heir != nullptr);
idlem->cur = idlem->heir;
acquire(&idlem->heir->lock);
idlem->heir->set_state(RUNNABLE);
release(&idlem->heir->lock);
}
static void
idleheir(void *x)
{
post_swtch();
idlem->heir = nullptr;
idleloop();
}
static inline void
finishzombies(void)
{
struct idle *i = &idlem[mycpu()->id];
if (!SLIST_EMPTY(&i->zombies)) {
struct proc *p, *np;
acquire(&i->lock);
SLIST_FOREACH_SAFE(p, &i->zombies, child_next, np) {
SLIST_REMOVE(&i->zombies, p, proc, child_next);
finishproc(p);
}
release(&i->lock);
}
}
void
idleloop(void)
{
// Test the work queue
//extern void testwq(void);
//testwq();
//extern void benchwq(void);
//benchwq();
// Enabling mtrace calls in scheduler generates many mtrace_call_entrys.
// mtrace_call_set(1, cpu->id);
//mtstart(scheduler, idlep);
sti();
for (;;) {
acquire(&myproc()->lock);
myproc()->set_state(RUNNABLE);
sched();
finishzombies();
if (steal() == 0) {
int worked;
do {
assert(mycpu()->ncli == 0);
// If we don't have an heir, try to allocate one
if (idlem->heir == nullptr) {
struct proc *p;
p = allocproc();
if (p == nullptr)
break;
snprintf(p->name, sizeof(p->name), "idleh_%u", mycpu()->id);
p->cpuid = mycpu()->id;
p->cpu_pin = 1;
p->context->rip = (u64)idleheir;
p->cwd = nullptr;
idlem->heir = p;
}
worked = wq_trywork();
// If we are no longer the idle thread, exit
if (worked && idlem->cur != myproc())
exit();
} while(worked);
sti();
}
}
}
void
initidle(void)
{
struct proc *p = allocproc();
if (!p)
panic("initidle allocproc");
SLIST_INIT(&idlem[cpunum()].zombies);
initlock(&idlem[cpunum()].lock, "idle_lock", LOCKSTAT_IDLE);
snprintf(p->name, sizeof(p->name), "idle_%u", cpunum());
mycpu()->proc = p;
myproc()->cpuid = cpunum();
myproc()->cpu_pin = 1;
idlem->cur = p;
}
<|endoftext|>
|
<commit_before>#include "types.h"
#include "mmu.h"
#include "kernel.hh"
#include "spinlock.h"
#include "condvar.h"
#include "queue.h"
#include "proc.hh"
#include "fs.h"
#include "file.hh"
#include "cpu.hh"
#define PIPESIZE 512
struct pipe {
struct spinlock lock;
struct condvar cv;
int flag; // Ordered?
char data[PIPESIZE];
u32 nread; // number of bytes read
u32 nwrite; // number of bytes written
int readopen; // read fd is still open
int writeopen; // write fd is still open
};
int
pipealloc(struct file **f0, struct file **f1, int flag)
{
struct pipe *p;
p = 0;
*f0 = *f1 = 0;
if((*f0 = file::alloc()) == 0 || (*f1 = file::alloc()) == 0)
goto bad;
// XXX Use new
if((p = (pipe*)kmalloc(sizeof(*p), "pipe")) == 0)
goto bad;
p->readopen = 1;
p->writeopen = 1;
p->nwrite = 0;
p->nread = 0;
p->flag = flag;
new (&p->lock) spinlock("pipe", LOCKSTAT_PIPE);
new (&p->cv) condvar("pipe");
(*f0)->type = file::FD_PIPE;
(*f0)->readable = 1;
(*f0)->writable = 0;
(*f0)->pipe = p;
(*f1)->type = file::FD_PIPE;
(*f1)->readable = 0;
(*f1)->writable = 1;
(*f1)->pipe = p;
return 0;
//PAGEBREAK: 20
bad:
if(p) {
p->cv.~condvar();
p->lock.~spinlock();
kmfree((char*)p, sizeof(*p));
}
if(*f0)
(*f0)->dec();
if(*f1)
(*f1)->dec();
return -1;
}
void
pipeclose(struct pipe *p, int writable)
{
acquire(&p->lock);
if(writable){
p->writeopen = 0;
} else {
p->readopen = 0;
}
p->cv.wake_all();
if(p->readopen == 0 && p->writeopen == 0){
release(&p->lock);
p->lock.~spinlock();
kmfree((char*)p, sizeof(*p));
} else
release(&p->lock);
}
//PAGEBREAK: 40
int
pipewrite(struct pipe *p, const char *addr, int n)
{
int i;
acquire(&p->lock);
for(i = 0; i < n; i++){
while(p->nwrite == p->nread + PIPESIZE){ //DOC: pipewrite-full
if(p->readopen == 0 || myproc()->killed){
release(&p->lock);
return -1;
}
p->cv.wake_all();
p->cv.sleep(&p->lock); //DOC: pipewrite-sleep
}
p->data[p->nwrite++ % PIPESIZE] = addr[i];
}
p->cv.wake_all(); //DOC: pipewrite-wakeup1
release(&p->lock);
return n;
}
int
piperead(struct pipe *p, char *addr, int n)
{
int i;
acquire(&p->lock);
while(p->nread == p->nwrite && p->writeopen){ //DOC: pipe-empty
if(myproc()->killed){
release(&p->lock);
return -1;
}
p->cv.sleep(&p->lock); //DOC: piperead-sleep
}
for(i = 0; i < n; i++){ //DOC: piperead-copy
if(p->nread == p->nwrite)
break;
addr[i] = p->data[p->nread++ % PIPESIZE];
}
p->cv.wake_all(); //DOC: piperead-wakeup
release(&p->lock);
return i;
}
<commit_msg>A bit more C++<commit_after>#include "types.h"
#include "mmu.h"
#include "kernel.hh"
#include "spinlock.h"
#include "condvar.h"
#include "queue.h"
#include "proc.hh"
#include "fs.h"
#include "file.hh"
#include "cpu.hh"
#include "ilist.hh"
#define PIPESIZE 512
struct corepipe {
u32 nread; // number of bytes read
u32 nwrite; // number of bytes written
char data[PIPESIZE];
};
struct pipe {
struct spinlock lock;
struct condvar cv;
int flag; // Ordered?
int readopen; // read fd is still open
int writeopen; // write fd is still open
u32 nread; // number of bytes read
u32 nwrite; // number of bytes written
char data[PIPESIZE];
#if 0
struct corepipe pipes[NCPU]; // if unordered
#endif
pipe(int f) : flag(f), readopen(1), writeopen(1), nread(0), nwrite(0) {
lock = spinlock("pipe", LOCKSTAT_PIPE);
cv = condvar("pipe");
};
~pipe();
NEW_DELETE_OPS(pipe);
};
int
pipealloc(struct file **f0, struct file **f1, int flag)
{
struct pipe *p;
p = 0;
*f0 = *f1 = 0;
if((*f0 = file::alloc()) == 0 || (*f1 = file::alloc()) == 0)
goto bad;
p = new pipe(flag);
(*f0)->type = file::FD_PIPE;
(*f0)->readable = 1;
(*f0)->writable = 0;
(*f0)->pipe = p;
(*f1)->type = file::FD_PIPE;
(*f1)->readable = 0;
(*f1)->writable = 1;
(*f1)->pipe = p;
return 0;
//PAGEBREAK: 20
bad:
if(p) {
p->~pipe();
}
if(*f0)
(*f0)->dec();
if(*f1)
(*f1)->dec();
return -1;
}
void
pipeclose(struct pipe *p, int writable)
{
acquire(&p->lock);
if(writable){
p->writeopen = 0;
} else {
p->readopen = 0;
}
p->cv.wake_all();
if(p->readopen == 0 && p->writeopen == 0){
release(&p->lock);
p->lock.~spinlock();
kmfree((char*)p, sizeof(*p));
} else
release(&p->lock);
}
//PAGEBREAK: 40
int
pipewrite(struct pipe *p, const char *addr, int n)
{
int i;
acquire(&p->lock);
for(i = 0; i < n; i++){
while(p->nwrite == p->nread + PIPESIZE){ //DOC: pipewrite-full
if(p->readopen == 0 || myproc()->killed){
release(&p->lock);
return -1;
}
p->cv.wake_all();
p->cv.sleep(&p->lock); //DOC: pipewrite-sleep
}
p->data[p->nwrite++ % PIPESIZE] = addr[i];
}
p->cv.wake_all(); //DOC: pipewrite-wakeup1
release(&p->lock);
return n;
}
int
piperead(struct pipe *p, char *addr, int n)
{
int i;
acquire(&p->lock);
while(p->nread == p->nwrite && p->writeopen){ //DOC: pipe-empty
if(myproc()->killed){
release(&p->lock);
return -1;
}
p->cv.sleep(&p->lock); //DOC: piperead-sleep
}
for(i = 0; i < n; i++){ //DOC: piperead-copy
if(p->nread == p->nwrite)
break;
addr[i] = p->data[p->nread++ % PIPESIZE];
}
p->cv.wake_all(); //DOC: piperead-wakeup
release(&p->lock);
return i;
}
<|endoftext|>
|
<commit_before>#include "types.h"
#include "mmu.h"
#include "kernel.hh"
#include "spinlock.h"
#include "condvar.h"
#include "queue.h"
#include "proc.hh"
#include "fs.h"
#include "file.hh"
#include "cpu.hh"
#include "ilist.hh"
#include "uk/unistd.h"
#include "rnd.hh"
#define PIPESIZE 512
struct pipe {
virtual ~pipe() { };
virtual int write(const char *addr, int n) = 0;
virtual int read(char *addr, int n) = 0;
virtual int close(int writable) = 0;
NEW_DELETE_OPS(pipe);
};
struct ordered : pipe {
struct spinlock lock;
struct condvar cv;
int readopen; // read fd is still open
int writeopen; // write fd is still open
u32 nread; // number of bytes read
u32 nwrite; // number of bytes written
char data[PIPESIZE];
ordered() : readopen(1), writeopen(1), nread(0), nwrite(0) {
lock = spinlock("pipe", LOCKSTAT_PIPE);
cv = condvar("pipe");
};
~ordered() {
};
NEW_DELETE_OPS(ordered);
virtual int write(const char *addr, int n) {
acquire(&lock);
for(int i = 0; i < n; i++){
while(nwrite == nread + PIPESIZE){
if(readopen == 0 || myproc()->killed){
release(&lock);
return -1;
}
cv.wake_all();
cv.sleep(&lock);
}
data[nwrite++ % PIPESIZE] = addr[i];
}
cv.wake_all();
release(&lock);
return n;
}
virtual int read(char *addr, int n) {
int i;
acquire(&lock);
while(nread == nwrite && writeopen) {
if(myproc()->killed){
release(&lock);
return -1;
}
cv.sleep(&lock);
}
for(i = 0; i < n; i++) {
if(nread == nwrite)
break;
addr[i] = data[nread++ % PIPESIZE];
}
cv.wake_all();
release(&lock);
return i;
}
virtual int close(int writable) {
acquire(&lock);
if(writable){
writeopen = 0;
} else {
readopen = 0;
}
cv.wake_all();
if(readopen == 0 && writeopen == 0){
release(&lock);
return 1;
} else
release(&lock);
return 0;
}
};
// Initial support for unordered pipes by having per-core pipes. A writer
// writes n bytes as a single unit in its local per-core pipe, from which the
// neighbor is intended to read the n bytes. If a writer's local pipe is full,
// it sleeps until a reader to wake it up. A reader cycles through all per-core
// pipes, starting from the next core. If it reads from a full pipe, it wakes up
// the local writer. If all pipes are empty, then it keeps trying.
//
// tension between load balance and performance: if there is no need for load
// balance, reader and writer should agree on a given pipe and use only that
// one.
//
// tension between space sharing and time sharing: maybe should read from local
// pipe, maybe should give up cpu when no pipe has data.
//
// XXX shouldn't cpuid has index in pipes because process may be rescheduled.
//
// XXX Should pipe track #readers, #writers? so that we don't have to allocate
// NCPU per-core pipes.
struct corepipe {
u32 nread;
u32 nwrite;
int readopen;
char data[PIPESIZE];
struct spinlock lock;
struct condvar cv;
corepipe() : nread(0), nwrite(0), readopen(1),
lock("corepipe", LOCKSTAT_PIPE),
cv("pipe") {};
~corepipe() {};
NEW_DELETE_OPS(corepipe);
int write(const char *addr, int n, int sleep) {
int r = 0;
acquire(&lock);
while (1) {
if(readopen == 0 || myproc()->killed) {
r = -1;
break;
}
if (nwrite + n < nread + PIPESIZE) {
for (int i = 0; i < n; i++)
data[nwrite++ % PIPESIZE] = addr[i];
r = n;
break;
} else if (sleep) {
cprintf("w");
cv.sleep(&lock);
} else {
break;
}
}
release(&lock);
return r;
}
int read(char *addr, int n) {
int r = 0;
acquire(&lock);
if (nread + n <= nwrite) {
for(int i = 0; i < n; i++)
addr[i] = data[nread++ % PIPESIZE];
r = n;
// cv.wake_all(); // XXX only wakeup when it was full?
}
release(&lock);
return r;
}
};
struct unordered : pipe {
atomic<corepipe*> pipes[NCPU];
int writeopen;
unordered() : writeopen(1) {
for (int i = 0; i < NCPU; i++)
pipes[i] = 0;
};
~unordered() {
for (int i = 0; i < NCPU; i++) {
corepipe* c = pipes[i].load();
if (c)
delete c;
}
};
NEW_DELETE_OPS(unordered);
corepipe* mycorepipe(int id) {
for (;;) {
corepipe* c = pipes[id];
if (c)
return c;
c = new corepipe;
if (cmpxch(&pipes[id], (corepipe*) 0, c))
return c;
delete c;
}
}
int write(const char *addr, int n) {
int r;
corepipe *cp = mycorepipe((mycpu()->id) % NCPU);
do {
r = cp->write(addr, n, 0);
if (r < 0) break;
cp = mycorepipe(rnd() % NCPU); // try another pipe if cp is full
// XXX should we give up the CPU at some point?
} while (r != n);
return r;
};
int read(char *addr, int n) {
int r;
while (1) {
for (int i = (mycpu()->id + 1) % NCPU; i != mycpu()->id;
i = (i + 1) % NCPU) {
r = mycorepipe(i)->read(addr, n);
if (r == n) return r;
}
if (writeopen == 0 || myproc()->killed) return -1;
r = mycorepipe(mycpu()->id)->read(addr, n);
if (r == n) return r;
// XXX should we give up the CPU at some point?
}
return r;
}
int close(int writeable) {
int readopen = 1;
int r = 0;
for (int i = 0; i < NCPU; i++) acquire(&mycorepipe(i)->lock);
if(writeable){
writeopen = 0;
} else {
for (int i = 0; i < NCPU; i++) mycorepipe(i)->readopen = 0;
readopen = 0;
}
for (int i = 0; i < NCPU; i++) mycorepipe(i)->cv.wake_all();
if(readopen == 0 && writeopen == 0) {
r = 1;
}
for (int i = 0; i < NCPU; i++) release(&mycorepipe(i)->lock);
return r;
}
};
int
pipealloc(struct file **f0, struct file **f1, int flag)
{
struct pipe *p;
p = 0;
*f0 = *f1 = 0;
if((*f0 = file::alloc()) == 0 || (*f1 = file::alloc()) == 0)
goto bad;
if (flag & PIPE_UNORDED) {
p = new unordered();
} else {
p = new ordered();
}
(*f0)->type = file::FD_PIPE;
(*f0)->readable = 1;
(*f0)->writable = 0;
(*f0)->pipe = p;
(*f1)->type = file::FD_PIPE;
(*f1)->readable = 0;
(*f1)->writable = 1;
(*f1)->pipe = p;
return 0;
bad:
if(p)
delete p;
if(*f0)
(*f0)->dec();
if(*f1)
(*f1)->dec();
return -1;
}
void
pipeclose(struct pipe *p, int writable)
{
if (p->close(writable))
delete p;
}
int
pipewrite(struct pipe *p, const char *addr, int n)
{
return p->write(addr, n);
}
int
piperead(struct pipe *p, char *addr, int n)
{
return p->read(addr, n);
}
<commit_msg>minor corepipe cleanup<commit_after>#include "types.h"
#include "mmu.h"
#include "kernel.hh"
#include "spinlock.h"
#include "condvar.h"
#include "queue.h"
#include "proc.hh"
#include "fs.h"
#include "file.hh"
#include "cpu.hh"
#include "ilist.hh"
#include "uk/unistd.h"
#include "rnd.hh"
#define PIPESIZE 512
struct pipe {
virtual ~pipe() { };
virtual int write(const char *addr, int n) = 0;
virtual int read(char *addr, int n) = 0;
virtual int close(int writable) = 0;
NEW_DELETE_OPS(pipe);
};
struct ordered : pipe {
struct spinlock lock;
struct condvar cv;
int readopen; // read fd is still open
int writeopen; // write fd is still open
u32 nread; // number of bytes read
u32 nwrite; // number of bytes written
char data[PIPESIZE];
ordered() : readopen(1), writeopen(1), nread(0), nwrite(0) {
lock = spinlock("pipe", LOCKSTAT_PIPE);
cv = condvar("pipe");
};
~ordered() {
};
NEW_DELETE_OPS(ordered);
virtual int write(const char *addr, int n) {
acquire(&lock);
for(int i = 0; i < n; i++){
while(nwrite == nread + PIPESIZE){
if(readopen == 0 || myproc()->killed){
release(&lock);
return -1;
}
cv.wake_all();
cv.sleep(&lock);
}
data[nwrite++ % PIPESIZE] = addr[i];
}
cv.wake_all();
release(&lock);
return n;
}
virtual int read(char *addr, int n) {
int i;
acquire(&lock);
while(nread == nwrite && writeopen) {
if(myproc()->killed){
release(&lock);
return -1;
}
cv.sleep(&lock);
}
for(i = 0; i < n; i++) {
if(nread == nwrite)
break;
addr[i] = data[nread++ % PIPESIZE];
}
cv.wake_all();
release(&lock);
return i;
}
virtual int close(int writable) {
acquire(&lock);
if(writable){
writeopen = 0;
} else {
readopen = 0;
}
cv.wake_all();
if(readopen == 0 && writeopen == 0){
release(&lock);
return 1;
} else
release(&lock);
return 0;
}
};
// Initial support for unordered pipes by having per-core pipes. A writer
// writes n bytes as a single unit in its local per-core pipe, from which the
// neighbor is intended to read the n bytes. If a writer's local pipe is full,
// it sleeps until a reader to wake it up. A reader cycles through all per-core
// pipes, starting from the next core. If it reads from a full pipe, it wakes up
// the local writer. If all pipes are empty, then it keeps trying.
//
// tension between load balance and performance: if there is no need for load
// balance, reader and writer should agree on a given pipe and use only that
// one.
//
// tension between space sharing and time sharing: maybe should read from local
// pipe, maybe should give up cpu when no pipe has data.
//
// XXX shouldn't cpuid has index in pipes because process may be rescheduled.
//
// XXX Should pipe track #readers, #writers? so that we don't have to allocate
// NCPU per-core pipes.
struct corepipe {
u32 nread;
u32 nwrite;
int readopen;
char data[PIPESIZE];
struct spinlock lock;
corepipe() : nread(0), nwrite(0), readopen(1),
lock("corepipe", LOCKSTAT_PIPE) {};
~corepipe() {};
NEW_DELETE_OPS(corepipe);
int write(const char *addr, int n) {
scoped_acquire l(&lock);
if (readopen == 0 || myproc()->killed)
return -1;
if (nwrite + n < nread + PIPESIZE) {
for (int i = 0; i < n; i++)
data[nwrite++ % PIPESIZE] = addr[i];
return n;
}
return 0;
}
int read(char *addr, int n) {
scoped_acquire l(&lock);
if (nread + n <= nwrite) {
for (int i = 0; i < n; i++)
addr[i] = data[nread++ % PIPESIZE];
return n;
}
return 0;
}
};
struct unordered : pipe {
atomic<corepipe*> pipes[NCPU];
int writeopen;
unordered() : writeopen(1) {
for (int i = 0; i < NCPU; i++)
pipes[i] = 0;
};
~unordered() {
for (int i = 0; i < NCPU; i++) {
corepipe* c = pipes[i].load();
if (c)
delete c;
}
};
NEW_DELETE_OPS(unordered);
corepipe* mycorepipe(int id) {
for (;;) {
corepipe* c = pipes[id];
if (c)
return c;
c = new corepipe;
if (cmpxch(&pipes[id], (corepipe*) 0, c))
return c;
delete c;
}
}
int write(const char *addr, int n) {
int r;
corepipe *cp = mycorepipe((mycpu()->id) % NCPU);
do {
r = cp->write(addr, n);
if (r < 0) break;
cp = mycorepipe(rnd() % NCPU); // try another pipe if cp is full
// XXX should we give up the CPU at some point?
} while (r != n);
return r;
};
int read(char *addr, int n) {
int r;
while (1) {
for (int i = (mycpu()->id + 1) % NCPU; i != mycpu()->id;
i = (i + 1) % NCPU) {
r = mycorepipe(i)->read(addr, n);
if (r == n) return r;
}
if (writeopen == 0 || myproc()->killed) return -1;
r = mycorepipe(mycpu()->id)->read(addr, n);
if (r == n) return r;
// XXX should we give up the CPU at some point?
}
return r;
}
int close(int writeable) {
int readopen = 1;
int r = 0;
for (int i = 0; i < NCPU; i++) acquire(&mycorepipe(i)->lock);
if(writeable){
writeopen = 0;
} else {
for (int i = 0; i < NCPU; i++) mycorepipe(i)->readopen = 0;
readopen = 0;
}
if(readopen == 0 && writeopen == 0) {
r = 1;
}
for (int i = 0; i < NCPU; i++) release(&mycorepipe(i)->lock);
return r;
}
};
int
pipealloc(struct file **f0, struct file **f1, int flag)
{
struct pipe *p;
p = 0;
*f0 = *f1 = 0;
if((*f0 = file::alloc()) == 0 || (*f1 = file::alloc()) == 0)
goto bad;
if (flag & PIPE_UNORDED) {
p = new unordered();
} else {
p = new ordered();
}
(*f0)->type = file::FD_PIPE;
(*f0)->readable = 1;
(*f0)->writable = 0;
(*f0)->pipe = p;
(*f1)->type = file::FD_PIPE;
(*f1)->readable = 0;
(*f1)->writable = 1;
(*f1)->pipe = p;
return 0;
bad:
if(p)
delete p;
if(*f0)
(*f0)->dec();
if(*f1)
(*f1)->dec();
return -1;
}
void
pipeclose(struct pipe *p, int writable)
{
if (p->close(writable))
delete p;
}
int
pipewrite(struct pipe *p, const char *addr, int n)
{
return p->write(addr, n);
}
int
piperead(struct pipe *p, char *addr, int n)
{
return p->read(addr, n);
}
<|endoftext|>
|
<commit_before>// Copyright 2019 Global Phasing Ltd.
//
// convert SF-mmCIF to MTZ
#include <algorithm>
#include <cstdlib> // for exit
#include <stdio.h>
#ifndef GEMMI_ALL_IN_ONE
# define GEMMI_WRITE_IMPLEMENTATION 1
#endif
#include <gemmi/atox.hpp> // for read_word
#include <gemmi/fileutil.hpp> // for file_open
#include <gemmi/gzread.hpp> // for read_cif_gz
#include <gemmi/mtz.hpp> // for Mtz
#include <gemmi/refln.hpp> // for ReflnBlock
#include <gemmi/version.hpp> // for GEMMI_VERSION
#define GEMMI_PROG cif2mtz
#include "options.h"
namespace cif = gemmi::cif;
enum OptionIndex { Verbose=3, BlockName, Dir, Title, History };
static const option::Descriptor Usage[] = {
{ NoOp, 0, "", "", Arg::None,
"Usage:"
"\n " EXE_NAME " [options] CIF_FILE MTZ_FILE"
"\n " EXE_NAME " [options] CIF_FILE --dir=DIRECTORY"
"\nOptions:"},
{ Help, 0, "h", "help", Arg::None, " -h, --help \tPrint usage and exit." },
{ Version, 0, "V", "version", Arg::None,
" -V, --version \tPrint version and exit." },
{ Verbose, 0, "v", "verbose", Arg::None, " --verbose \tVerbose output." },
{ BlockName, 0, "b", "block", Arg::Required,
" -b NAME, --block=NAME \tmmCIF block to convert." },
{ Dir, 0, "d", "dir", Arg::Required,
" -d DIR, --dir=NAME \tOutput directory." },
{ Title, 0, "", "title", Arg::Required,
" --title \tMTZ title." },
{ History, 0, "-H", "history", Arg::Required,
" -H LINE, --history=LINE \tAdd a history line." },
{ NoOp, 0, "", "", Arg::None,
"\nFirst variant: converts the first block of CIF_FILE, or the block"
"\nspecified with --block=NAME, to MTZ file with given name."
"\n\nSecond variant: converts each block of CIF_FILE to one MTZ file"
"\n(block-name.mtz) in the specified DIRECTORY."
"\n\nIf CIF_FILE is -, the input is read from stdin."
},
{ 0, 0, 0, 0, 0, 0 }
};
struct Entry {
const char* refln_tag;
const char* col_label;
char col_type;
unsigned char dataset_id;
};
// When we have a few alternative mmCIF tags for the same MTZ label,
// they are in consecutive rows and all but the last one have null col_label.
static Entry conv_table[] = {
{"index_h", "H", 'H', 0},
{"index_k", "K", 'H', 0},
{"index_l", "L", 'H', 0},
{"pdbx_r_free_flag", nullptr, 'I', 0},
{"status", "FreeR_flag", 's', 0}, // s is a special flag
{"intensity_meas", nullptr, 'J', 1},
{"intensity_net", "I", 'J', 1},
{"intensity_sigma", "SIGI", 'Q', 1},
{"pdbx_I_plus", "I(+)", 'K', 1},
{"pdbx_I_plus_sigma", "SIGI(+)", 'M', 1},
{"pdbx_I_minus", "I(-)", 'K', 1},
{"pdbx_I_minus_sigma", "SIGI(-)", 'M', 1},
{"F_meas_au", "FP", 'F', 1},
{"F_meas_sigma_au", "SIGFP", 'Q', 1},
{"pdbx_F_plus", "F(+)", 'G', 1},
{"pdbx_F_plus_sigma", "SIGF(+)", 'L', 1},
{"pdbx_F_minus", "F(-)", 'G', 1},
{"pdbx_F_minus_sigma", "SIGF(-)", 'L', 1},
{"pdbx_anom_difference", "DP", 'D', 1},
{"pdbx_anom_difference_sigma", "SIGDP", 'Q', 1},
{"F_calc", "FC", 'F', 1},
{"phase_calc", "PHIC", 'P', 1},
{"fom", nullptr, 'W', 1},
{"weight", "FOM", 'W', 1},
{"pdbx_HL_A_iso", "HLA", 'A', 1},
{"pdbx_HL_B_iso", "HLB", 'A', 1},
{"pdbx_HL_C_iso", "HLC", 'A', 1},
{"pdbx_HL_D_iso", "HLD", 'A', 1},
{"pdbx_FWT", "FWT", 'F', 1},
{"pdbx_PHWT", "PHWT", 'P', 1},
{"pdbx_DELFWT", "DELFWT", 'F', 1},
{"pdbx_DELPHWT", "DELPHWT", 'P', 1},
};
inline float status_to_freeflag(const std::string& str) {
char c = str[0];
if (c == '\'' || c == '"')
c = str[1];
if (c == 'o')
return 1.f;
if (c == 'f')
return 0.f;
return NAN;
}
static
gemmi::ReflnBlock& get_block_by_name(std::vector<gemmi::ReflnBlock>& rblocks,
const std::string& name) {
for (gemmi::ReflnBlock& rb : rblocks)
if (rb.block.name == name)
return rb;
gemmi::fail("block not found: " + name);
}
static
void convert_cif_block_to_mtz(const gemmi::ReflnBlock& rb,
const std::string& mtz_path,
const std::vector<option::Option>& options) {
gemmi::Mtz mtz;
if (options[Title])
mtz.title = options[Title].arg;
for (const option::Option* opt = options[History]; opt; opt = opt->next())
mtz.history.push_back(opt->arg);
mtz.cell = rb.cell;
mtz.spacegroup = rb.spacegroup;
mtz.add_dataset("HKL_base");
mtz.add_dataset("unknown").wavelength = rb.wavelength;
const cif::Loop* loop = rb.refln_loop ? rb.refln_loop : rb.diffrn_refln_loop;
if (!loop)
gemmi::fail("_refln category not found in mmCIF block: " + rb.block.name);
if (options[Verbose])
fprintf(stderr, "Searching tags with known MTZ equivalents ...\n");
bool uses_status = false;
std::vector<int> indices;
std::string tag = loop->tags[0].substr(0, loop->tags[0].find('.') + 1);
const size_t len = tag.length();
for (auto c = std::begin(conv_table); c != std::end(conv_table); ++c) {
tag.replace(len, std::string::npos, c->refln_tag);
int index = loop->find_tag(tag);
if (index != -1) {
indices.push_back(index);
mtz.columns.emplace_back();
gemmi::Mtz::Column& col = mtz.columns.back();
col.dataset_id = c->dataset_id;
col.type = c->col_type;
if (col.type == 's') {
col.type = 'I';
uses_status = true;
}
while (!c->col_label)
++c;
col.label = c->col_label;
col.parent = &mtz;
col.idx = mtz.columns.size() - 1;
if (options[Verbose])
fprintf(stderr, " %s -> %s\n", tag.c_str(), col.label.c_str());
} else if (c->col_type == 'H') {
gemmi::fail("Miller index tag not found: " + tag);
}
}
mtz.nreflections = loop->length();
mtz.data.resize(mtz.columns.size() * mtz.nreflections);
int k = 0;
for (size_t i = 0; i < loop->values.size(); i += loop->tags.size()) {
size_t j = 0;
for (; j != 3; ++j)
mtz.data[k++] = (float) cif::as_int(loop->values[i + indices[j]]);
if (uses_status)
mtz.data[k++] = status_to_freeflag(loop->values[i + indices[j++]]);
for (; j != indices.size(); ++j)
mtz.data[k++] = (float) cif::as_number(loop->values[i + indices[j]]);
}
if (options[Verbose])
fprintf(stderr, "Writing %s ...\n", mtz_path.c_str());
try {
mtz.write_to_file(mtz_path);
} catch (std::runtime_error& e) {
fprintf(stderr, "ERROR writing %s: %s\n", mtz_path.c_str(), e.what());
std::exit(3);
}
}
int GEMMI_MAIN(int argc, char **argv) {
OptParser p(EXE_NAME);
p.simple_parse(argc, argv, Usage);
bool convert_all = p.options[Dir];
p.require_positional_args(convert_all ? 1 : 2);
bool verbose = p.options[Verbose];
const char* cif_path = p.nonOption(0);
if (verbose)
fprintf(stderr, "Reading %s ...\n", cif_path);
auto rblocks = gemmi::as_refln_blocks(gemmi::read_cif_gz(cif_path).blocks);
if (convert_all) {
bool ok = true;
for (gemmi::ReflnBlock& rb : rblocks) {
std::string path = p.options[Dir].arg;
path += '/';
path += rb.block.name;
path += ".mtz";
try {
convert_cif_block_to_mtz(rb, path, p.options);
} catch (std::runtime_error& e) {
fprintf(stderr, "ERROR: %s\n", e.what());
ok = false;
}
}
if (!ok)
return 1;
} else {
const char* mtz_path = p.nonOption(1);
try {
const gemmi::ReflnBlock& rb = p.options[BlockName]
? get_block_by_name(rblocks, p.options[BlockName].arg)
: rblocks.at(0);
convert_cif_block_to_mtz(rb, mtz_path, p.options);
} catch (std::runtime_error& e) {
fprintf(stderr, "ERROR: %s\n", e.what());
return 1;
}
}
if (verbose)
fprintf(stderr, "Done.\n");
return 0;
}
// vim:sw=2:ts=2:et:path^=../include,../third_party
<commit_msg>cif2mtz.cpp: better error handling<commit_after>// Copyright 2019 Global Phasing Ltd.
//
// convert SF-mmCIF to MTZ
#include <algorithm>
#include <cstdlib> // for exit
#include <stdio.h>
#ifndef GEMMI_ALL_IN_ONE
# define GEMMI_WRITE_IMPLEMENTATION 1
#endif
#include <gemmi/atox.hpp> // for read_word
#include <gemmi/fileutil.hpp> // for file_open
#include <gemmi/gzread.hpp> // for read_cif_gz
#include <gemmi/mtz.hpp> // for Mtz
#include <gemmi/refln.hpp> // for ReflnBlock
#include <gemmi/version.hpp> // for GEMMI_VERSION
#define GEMMI_PROG cif2mtz
#include "options.h"
namespace cif = gemmi::cif;
enum OptionIndex { Verbose=3, BlockName, Dir, Title, History };
static const option::Descriptor Usage[] = {
{ NoOp, 0, "", "", Arg::None,
"Usage:"
"\n " EXE_NAME " [options] CIF_FILE MTZ_FILE"
"\n " EXE_NAME " [options] CIF_FILE --dir=DIRECTORY"
"\nOptions:"},
{ Help, 0, "h", "help", Arg::None, " -h, --help \tPrint usage and exit." },
{ Version, 0, "V", "version", Arg::None,
" -V, --version \tPrint version and exit." },
{ Verbose, 0, "v", "verbose", Arg::None, " --verbose \tVerbose output." },
{ BlockName, 0, "b", "block", Arg::Required,
" -b NAME, --block=NAME \tmmCIF block to convert." },
{ Dir, 0, "d", "dir", Arg::Required,
" -d DIR, --dir=NAME \tOutput directory." },
{ Title, 0, "", "title", Arg::Required,
" --title \tMTZ title." },
{ History, 0, "-H", "history", Arg::Required,
" -H LINE, --history=LINE \tAdd a history line." },
{ NoOp, 0, "", "", Arg::None,
"\nFirst variant: converts the first block of CIF_FILE, or the block"
"\nspecified with --block=NAME, to MTZ file with given name."
"\n\nSecond variant: converts each block of CIF_FILE to one MTZ file"
"\n(block-name.mtz) in the specified DIRECTORY."
"\n\nIf CIF_FILE is -, the input is read from stdin."
},
{ 0, 0, 0, 0, 0, 0 }
};
struct Entry {
const char* refln_tag;
const char* col_label;
char col_type;
unsigned char dataset_id;
};
// When we have a few alternative mmCIF tags for the same MTZ label,
// they are in consecutive rows and all but the last one have null col_label.
static Entry conv_table[] = {
{"index_h", "H", 'H', 0},
{"index_k", "K", 'H', 0},
{"index_l", "L", 'H', 0},
{"pdbx_r_free_flag", nullptr, 'I', 0},
{"status", "FreeR_flag", 's', 0}, // s is a special flag
{"intensity_meas", nullptr, 'J', 1},
{"intensity_net", "I", 'J', 1},
{"intensity_sigma", "SIGI", 'Q', 1},
{"pdbx_I_plus", "I(+)", 'K', 1},
{"pdbx_I_plus_sigma", "SIGI(+)", 'M', 1},
{"pdbx_I_minus", "I(-)", 'K', 1},
{"pdbx_I_minus_sigma", "SIGI(-)", 'M', 1},
{"F_meas_au", "FP", 'F', 1},
{"F_meas_sigma_au", "SIGFP", 'Q', 1},
{"pdbx_F_plus", "F(+)", 'G', 1},
{"pdbx_F_plus_sigma", "SIGF(+)", 'L', 1},
{"pdbx_F_minus", "F(-)", 'G', 1},
{"pdbx_F_minus_sigma", "SIGF(-)", 'L', 1},
{"pdbx_anom_difference", "DP", 'D', 1},
{"pdbx_anom_difference_sigma", "SIGDP", 'Q', 1},
{"F_calc", "FC", 'F', 1},
{"phase_calc", "PHIC", 'P', 1},
{"fom", nullptr, 'W', 1},
{"weight", "FOM", 'W', 1},
{"pdbx_HL_A_iso", "HLA", 'A', 1},
{"pdbx_HL_B_iso", "HLB", 'A', 1},
{"pdbx_HL_C_iso", "HLC", 'A', 1},
{"pdbx_HL_D_iso", "HLD", 'A', 1},
{"pdbx_FWT", "FWT", 'F', 1},
{"pdbx_PHWT", "PHWT", 'P', 1},
{"pdbx_DELFWT", "DELFWT", 'F', 1},
{"pdbx_DELPHWT", "DELPHWT", 'P', 1},
};
inline float status_to_freeflag(const std::string& str) {
char c = str[0];
if (c == '\'' || c == '"')
c = str[1];
if (c == 'o')
return 1.f;
if (c == 'f')
return 0.f;
return NAN;
}
static
gemmi::ReflnBlock& get_block_by_name(std::vector<gemmi::ReflnBlock>& rblocks,
const std::string& name) {
for (gemmi::ReflnBlock& rb : rblocks)
if (rb.block.name == name)
return rb;
gemmi::fail("block not found: " + name);
}
static
void convert_cif_block_to_mtz(const gemmi::ReflnBlock& rb,
const std::string& mtz_path,
const std::vector<option::Option>& options) {
gemmi::Mtz mtz;
if (options[Title])
mtz.title = options[Title].arg;
for (const option::Option* opt = options[History]; opt; opt = opt->next())
mtz.history.push_back(opt->arg);
mtz.cell = rb.cell;
mtz.spacegroup = rb.spacegroup;
mtz.add_dataset("HKL_base");
mtz.add_dataset("unknown").wavelength = rb.wavelength;
const cif::Loop* loop = rb.refln_loop ? rb.refln_loop : rb.diffrn_refln_loop;
if (!loop)
gemmi::fail("_refln category not found in mmCIF block: " + rb.block.name);
if (options[Verbose])
fprintf(stderr, "Searching tags with known MTZ equivalents ...\n");
bool uses_status = false;
std::vector<int> indices;
std::string tag = loop->tags[0].substr(0, loop->tags[0].find('.') + 1);
const size_t len = tag.length();
for (auto c = std::begin(conv_table); c != std::end(conv_table); ++c) {
tag.replace(len, std::string::npos, c->refln_tag);
int index = loop->find_tag(tag);
if (index != -1) {
indices.push_back(index);
mtz.columns.emplace_back();
gemmi::Mtz::Column& col = mtz.columns.back();
col.dataset_id = c->dataset_id;
col.type = c->col_type;
if (col.type == 's') {
col.type = 'I';
uses_status = true;
}
while (!c->col_label)
++c;
col.label = c->col_label;
col.parent = &mtz;
col.idx = mtz.columns.size() - 1;
if (options[Verbose])
fprintf(stderr, " %s -> %s\n", tag.c_str(), col.label.c_str());
} else if (c->col_type == 'H') {
gemmi::fail("Miller index tag not found: " + tag);
}
}
mtz.nreflections = loop->length();
mtz.data.resize(mtz.columns.size() * mtz.nreflections);
int k = 0;
for (size_t i = 0; i < loop->values.size(); i += loop->tags.size()) {
size_t j = 0;
for (; j != 3; ++j)
mtz.data[k++] = (float) cif::as_int(loop->values[i + indices[j]]);
if (uses_status)
mtz.data[k++] = status_to_freeflag(loop->values[i + indices[j++]]);
for (; j != indices.size(); ++j)
mtz.data[k++] = (float) cif::as_number(loop->values[i + indices[j]]);
}
if (options[Verbose])
fprintf(stderr, "Writing %s ...\n", mtz_path.c_str());
try {
mtz.write_to_file(mtz_path);
} catch (std::runtime_error& e) {
fprintf(stderr, "ERROR writing %s: %s\n", mtz_path.c_str(), e.what());
std::exit(3);
}
}
int GEMMI_MAIN(int argc, char **argv) {
OptParser p(EXE_NAME);
p.simple_parse(argc, argv, Usage);
bool convert_all = p.options[Dir];
p.require_positional_args(convert_all ? 1 : 2);
bool verbose = p.options[Verbose];
const char* cif_path = p.nonOption(0);
if (verbose)
fprintf(stderr, "Reading %s ...\n", cif_path);
try {
auto rblocks = gemmi::as_refln_blocks(gemmi::read_cif_gz(cif_path).blocks);
if (convert_all) {
bool ok = true;
for (gemmi::ReflnBlock& rb : rblocks) {
std::string path = p.options[Dir].arg;
path += '/';
path += rb.block.name;
path += ".mtz";
try {
convert_cif_block_to_mtz(rb, path, p.options);
} catch (std::runtime_error& e) {
fprintf(stderr, "ERROR: %s\n", e.what());
ok = false;
}
}
if (!ok)
return 1;
} else {
const char* mtz_path = p.nonOption(1);
const gemmi::ReflnBlock& rb = p.options[BlockName]
? get_block_by_name(rblocks, p.options[BlockName].arg)
: rblocks.at(0);
convert_cif_block_to_mtz(rb, mtz_path, p.options);
}
} catch (std::runtime_error& e) {
fprintf(stderr, "ERROR: %s\n", e.what());
return 1;
}
if (verbose)
fprintf(stderr, "Done.\n");
return 0;
}
// vim:sw=2:ts=2:et:path^=../include,../third_party
<|endoftext|>
|
<commit_before>#include "circles.h"
using namespace cv;
circleFinder::circleFinder(int in_var)
{
my_pri_val = in_var;
my_pub_val = in_var;
}
int circleFinder::getVal()
{
return my_pri_val;
}
<commit_msg>notes<commit_after>#include "circles.h"
using namespace cv;
/*
The class circleFinder is the visual front end that provides the pixel locations
of spheres in the given frame. This can be replaced by any other class so long
as it generates information for the structureFromMotion object in a compatible
format.
*/
// perhaps this class is passed to the sfm object upon initialization
// I would need to look into the best way to do this, perhaps inheritance
circleFinder::circleFinder(int in_var)
{
my_pri_val = in_var;
my_pub_val = in_var;
}
int circleFinder::getVal()
{
return my_pri_val;
}
<|endoftext|>
|
<commit_before>// Time: O(2 * (1 + (9/49) + (9/49)^2 + ...)) = O(2/(1-(9/49)) = O(2.45)
// Space: O(1)
// The rand7() API is already defined for you.
// int rand7();
// @return a random integer in the range 1 to 7
class Solution {
public:
int rand10() {
while (true) {
int x = (rand7() - 1) * 7 + (rand7() - 1);
if (x < 40) {
return x % 10 + 1;
}
}
}
};
<commit_msg>Update implement-rand10-using-rand7.cpp<commit_after>// Time: O(1.199), counted by statistics, limit would be O(log10/log7) = O(1.183)
// Space: O(1)
// The rand7() API is already defined for you.
// int rand7();
// @return a random integer in the range 1 to 7
// Reference: https://leetcode.com/problems/implement-rand10-using-rand7/discuss/151567/C++JavaPython-Average-1.199-Call-rand7-Per-rand10
class Solution {
public:
int rand10() {
while (cache_.empty()) {
generate();
}
auto result = cache_.back(); cache_.pop_back();
return result;
}
private:
void generate() {
static const int n = 19;
uint64_t curr = 0, range = static_cast<uint64_t>(pow(7, n));
for (int i = 0; i < n; ++i) {
curr += static_cast<uint64_t>(pow(7, i)) * (rand7() - 1);
}
while (curr < range / 10 * 10) {
cache_.emplace_back(curr % 10 + 1);
curr /= 10;
range /= 10;
}
}
vector<int> cache_;
};
// Time: O(2 * (1 + (9/49) + (9/49)^2 + ...)) = O(2/(1-(9/49)) = O(2.45)
// Space: O(1)
class Solution 2{
public:
int rand10() {
while (true) {
int x = (rand7() - 1) * 7 + (rand7() - 1);
if (x < 40) {
return x % 10 + 1;
}
}
}
};
<|endoftext|>
|
<commit_before>//
// Copyright (c) 2009, Markus Rickert
// 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.
//
#include <QStatusBar>
#include <rl/math/Constants.h>
#include <rl/math/Rotation.h>
#include <rl/mdl/Exception.h>
#include <rl/mdl/Kinematic.h>
#include <rl/mdl/JacobianInverseKinematics.h>
#include <rl/sg/Body.h>
#ifdef RL_MDL_NLOPT
#include <rl/mdl/NloptInverseKinematics.h>
#endif
#include "ConfigurationModel.h"
#include "OperationalModel.h"
#include "MainWindow.h"
OperationalModel::OperationalModel(QObject* parent) :
QAbstractTableModel(parent),
id(0)
{
}
OperationalModel::~OperationalModel()
{
}
int
OperationalModel::columnCount(const QModelIndex& parent) const
{
return 6;
}
void
OperationalModel::configurationChanged(const QModelIndex& topLeft, const QModelIndex& bottomRight)
{
this->beginResetModel();
this->endResetModel();
}
QVariant
OperationalModel::data(const QModelIndex& index, int role) const
{
if (nullptr == MainWindow::instance()->kinematicModels[this->id])
{
return QVariant();
}
if (!index.isValid())
{
return QVariant();
}
const rl::math::Transform& transform = MainWindow::instance()->kinematicModels[this->id]->getOperationalPosition(index.row());
rl::math::Transform::ConstTranslationPart position = transform.translation();
rl::math::Vector3 orientation = transform.rotation().eulerAngles(2, 1, 0).reverse();
switch (role)
{
case Qt::CheckStateRole:
switch (index.column())
{
case 0:
return MainWindow::instance()->operationalGoals[this->id][index.row()] ? Qt::Checked : Qt::Unchecked;
break;
default:
break;
}
break;
case Qt::DisplayRole:
switch (index.column())
{
case 0:
case 1:
case 2:
return QString::number(position(index.column()), 'f', 4) + QString(" m");
break;
case 3:
case 4:
case 5:
return QString::number(orientation(index.column() - 3) * rl::math::constants::rad2deg, 'f', 2) + QChar(176);
break;
default:
break;
}
break;
case Qt::EditRole:
switch (index.column())
{
case 0:
case 1:
case 2:
return position(index.column());
break;
case 3:
case 4:
case 5:
return orientation(index.column() - 3) * rl::math::constants::rad2deg;
break;
default:
break;
}
break;
case Qt::TextAlignmentRole:
return QVariant(Qt::AlignRight | Qt::AlignVCenter);
break;
default:
break;
}
return QVariant();
}
Qt::ItemFlags
OperationalModel::flags(const QModelIndex &index) const
{
if (!index.isValid())
{
return Qt::NoItemFlags;
}
if (0 == index.column())
{
return QAbstractItemModel::flags(index) | Qt::ItemIsEditable | Qt::ItemIsUserCheckable;
}
return QAbstractItemModel::flags(index) | Qt::ItemIsEditable;
}
QVariant
OperationalModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (nullptr == MainWindow::instance()->kinematicModels[this->id])
{
return QVariant();
}
if (Qt::DisplayRole == role && Qt::Horizontal == orientation)
{
switch (section)
{
case 0:
return "x";
break;
case 1:
return "y";
break;
case 2:
return "z";
break;
case 3:
return "a";
break;
case 4:
return "b";
break;
case 5:
return "c";
break;
default:
break;
}
}
if (Qt::DisplayRole == role && Qt::Vertical == orientation)
{
return section;
}
return QVariant();
}
int
OperationalModel::rowCount(const QModelIndex& parent) const
{
if (nullptr == MainWindow::instance()->kinematicModels[this->id])
{
return 0;
}
return MainWindow::instance()->kinematicModels[this->id]->getOperationalDof();
}
bool
OperationalModel::setData(const QModelIndex& index, const QVariant& value, int role)
{
if (nullptr == MainWindow::instance()->kinematicModels[this->id])
{
return false;
}
if (!index.isValid())
{
return false;
}
if (Qt::CheckStateRole == role)
{
if (0 == index.column())
{
MainWindow::instance()->operationalGoals[this->id][index.row()] = value.value<bool>();
}
}
else if (Qt::EditRole == role)
{
if (rl::mdl::Kinematic* kinematic = dynamic_cast<rl::mdl::Kinematic*>(MainWindow::instance()->kinematicModels[this->id].get()))
{
rl::math::Transform transform = kinematic->getOperationalPosition(index.row());
rl::math::Vector3 orientation = transform.linear().eulerAngles(2, 1, 0).reverse();
switch (index.column())
{
case 0:
case 1:
case 2:
transform.translation()(index.column()) = value.value<rl::math::Real>();
break;
case 3:
transform.linear() = (
rl::math::AngleAxis(orientation.z(), rl::math::Vector3::UnitZ()) *
rl::math::AngleAxis(orientation.y(), rl::math::Vector3::UnitY()) *
rl::math::AngleAxis(value.value<rl::math::Real>() * rl::math::constants::deg2rad, rl::math::Vector3::UnitX())
).toRotationMatrix();
break;
case 4:
transform.linear() = (
rl::math::AngleAxis(orientation.z(), rl::math::Vector3::UnitZ()) *
rl::math::AngleAxis(value.value<rl::math::Real>() * rl::math::constants::deg2rad, rl::math::Vector3::UnitY()) *
rl::math::AngleAxis(orientation.x(), rl::math::Vector3::UnitX())
).toRotationMatrix();
break;
case 5:
transform.linear() = (
rl::math::AngleAxis(value.value<rl::math::Real>() * rl::math::constants::deg2rad, rl::math::Vector3::UnitZ()) *
rl::math::AngleAxis(orientation.y(), rl::math::Vector3::UnitY()) *
rl::math::AngleAxis(orientation.x(), rl::math::Vector3::UnitX())
).toRotationMatrix();
break;
default:
break;
}
rl::math::Vector q = kinematic->getPosition();
std::shared_ptr<rl::mdl::InverseKinematics> ik;
if ("JacobianInverseKinematics" == MainWindow::instance()->ikAlgorithmComboBox->currentText())
{
ik = std::make_shared<rl::mdl::JacobianInverseKinematics>(kinematic);
rl::mdl::JacobianInverseKinematics* jacobianIk = static_cast<rl::mdl::JacobianInverseKinematics*>(ik.get());
jacobianIk->setDuration(std::chrono::milliseconds(MainWindow::instance()->ikDurationSpinBox->cleanText().toUInt()));
jacobianIk->setIterations(MainWindow::instance()->ikIterationsSpinBox->cleanText().toUInt());
if ("DLS" == MainWindow::instance()->ikJacobianComboBox->currentText())
{
jacobianIk->setMethod(rl::mdl::JacobianInverseKinematics::Method::dls);
}
else if ("SVD" == MainWindow::instance()->ikJacobianComboBox->currentText())
{
jacobianIk->setMethod(rl::mdl::JacobianInverseKinematics::Method::svd);
}
else if ("Transpose" == MainWindow::instance()->ikJacobianComboBox->currentText())
{
jacobianIk->setMethod(rl::mdl::JacobianInverseKinematics::Method::transpose);
}
}
#ifdef RL_MDL_NLOPT
else if ("NloptInverseKinematics" == MainWindow::instance()->ikAlgorithmComboBox->currentText())
{
ik = std::make_shared<rl::mdl::NloptInverseKinematics>(kinematic);
rl::mdl::NloptInverseKinematics* nloptIk = static_cast<rl::mdl::NloptInverseKinematics*>(ik.get());
nloptIk->setDuration(std::chrono::milliseconds(MainWindow::instance()->ikDurationSpinBox->cleanText().toUInt()));
nloptIk->setIterations(MainWindow::instance()->ikIterationsSpinBox->cleanText().toUInt());
}
#endif
for (std::size_t i = 0; i < kinematic->getOperationalDof(); ++i)
{
if (MainWindow::instance()->operationalGoals[this->id][i])
{
ik->addGoal(i == index.row() ? transform : kinematic->getOperationalPosition(i), i);
}
}
std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now();
bool solved = ik->solve();
std::chrono::steady_clock::time_point stop = std::chrono::steady_clock::now();
if (solved)
{
MainWindow::instance()->statusBar()->showMessage("IK solved in " + QString::number(std::chrono::duration<double>(stop - start).count() * rl::math::constants::unit2milli) + " ms", 2000);
kinematic->forwardPosition();
for (std::size_t i = 0; i < MainWindow::instance()->geometryModels[this->id]->getNumBodies(); ++i)
{
MainWindow::instance()->geometryModels[this->id]->getBody(i)->setFrame(kinematic->getBodyFrame(i));
}
emit dataChanged(this->createIndex(0, 0), this->createIndex(this->rowCount(), this->columnCount()));
return true;
}
else
{
MainWindow::instance()->statusBar()->showMessage("IK failed", 2000);
kinematic->setPosition(q);
kinematic->forwardPosition();
}
}
}
return false;
}
<commit_msg>Update row label to use name of frame<commit_after>//
// Copyright (c) 2009, Markus Rickert
// 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.
//
#include <QStatusBar>
#include <rl/math/Constants.h>
#include <rl/math/Rotation.h>
#include <rl/mdl/Exception.h>
#include <rl/mdl/Kinematic.h>
#include <rl/mdl/JacobianInverseKinematics.h>
#include <rl/sg/Body.h>
#ifdef RL_MDL_NLOPT
#include <rl/mdl/NloptInverseKinematics.h>
#endif
#include "ConfigurationModel.h"
#include "OperationalModel.h"
#include "MainWindow.h"
OperationalModel::OperationalModel(QObject* parent) :
QAbstractTableModel(parent),
id(0)
{
}
OperationalModel::~OperationalModel()
{
}
int
OperationalModel::columnCount(const QModelIndex& parent) const
{
return 6;
}
void
OperationalModel::configurationChanged(const QModelIndex& topLeft, const QModelIndex& bottomRight)
{
this->beginResetModel();
this->endResetModel();
}
QVariant
OperationalModel::data(const QModelIndex& index, int role) const
{
if (nullptr == MainWindow::instance()->kinematicModels[this->id])
{
return QVariant();
}
if (!index.isValid())
{
return QVariant();
}
const rl::math::Transform& transform = MainWindow::instance()->kinematicModels[this->id]->getOperationalPosition(index.row());
rl::math::Transform::ConstTranslationPart position = transform.translation();
rl::math::Vector3 orientation = transform.rotation().eulerAngles(2, 1, 0).reverse();
switch (role)
{
case Qt::CheckStateRole:
switch (index.column())
{
case 0:
return MainWindow::instance()->operationalGoals[this->id][index.row()] ? Qt::Checked : Qt::Unchecked;
break;
default:
break;
}
break;
case Qt::DisplayRole:
switch (index.column())
{
case 0:
case 1:
case 2:
return QString::number(position(index.column()), 'f', 4) + QString(" m");
break;
case 3:
case 4:
case 5:
return QString::number(orientation(index.column() - 3) * rl::math::constants::rad2deg, 'f', 2) + QChar(176);
break;
default:
break;
}
break;
case Qt::EditRole:
switch (index.column())
{
case 0:
case 1:
case 2:
return position(index.column());
break;
case 3:
case 4:
case 5:
return orientation(index.column() - 3) * rl::math::constants::rad2deg;
break;
default:
break;
}
break;
case Qt::TextAlignmentRole:
return QVariant(Qt::AlignRight | Qt::AlignVCenter);
break;
default:
break;
}
return QVariant();
}
Qt::ItemFlags
OperationalModel::flags(const QModelIndex &index) const
{
if (!index.isValid())
{
return Qt::NoItemFlags;
}
if (0 == index.column())
{
return QAbstractItemModel::flags(index) | Qt::ItemIsEditable | Qt::ItemIsUserCheckable;
}
return QAbstractItemModel::flags(index) | Qt::ItemIsEditable;
}
QVariant
OperationalModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (nullptr == MainWindow::instance()->kinematicModels[this->id])
{
return QVariant();
}
if (Qt::DisplayRole == role && Qt::Horizontal == orientation)
{
switch (section)
{
case 0:
return "x";
break;
case 1:
return "y";
break;
case 2:
return "z";
break;
case 3:
return "a";
break;
case 4:
return "b";
break;
case 5:
return "c";
break;
default:
break;
}
}
if (Qt::DisplayRole == role && Qt::Vertical == orientation)
{
return QString::fromStdString(MainWindow::instance()->kinematicModels[this->id]->getOperationalFrame(section)->getName());
}
return QVariant();
}
int
OperationalModel::rowCount(const QModelIndex& parent) const
{
if (nullptr == MainWindow::instance()->kinematicModels[this->id])
{
return 0;
}
return MainWindow::instance()->kinematicModels[this->id]->getOperationalDof();
}
bool
OperationalModel::setData(const QModelIndex& index, const QVariant& value, int role)
{
if (nullptr == MainWindow::instance()->kinematicModels[this->id])
{
return false;
}
if (!index.isValid())
{
return false;
}
if (Qt::CheckStateRole == role)
{
if (0 == index.column())
{
MainWindow::instance()->operationalGoals[this->id][index.row()] = value.value<bool>();
}
}
else if (Qt::EditRole == role)
{
if (rl::mdl::Kinematic* kinematic = dynamic_cast<rl::mdl::Kinematic*>(MainWindow::instance()->kinematicModels[this->id].get()))
{
rl::math::Transform transform = kinematic->getOperationalPosition(index.row());
rl::math::Vector3 orientation = transform.linear().eulerAngles(2, 1, 0).reverse();
switch (index.column())
{
case 0:
case 1:
case 2:
transform.translation()(index.column()) = value.value<rl::math::Real>();
break;
case 3:
transform.linear() = (
rl::math::AngleAxis(orientation.z(), rl::math::Vector3::UnitZ()) *
rl::math::AngleAxis(orientation.y(), rl::math::Vector3::UnitY()) *
rl::math::AngleAxis(value.value<rl::math::Real>() * rl::math::constants::deg2rad, rl::math::Vector3::UnitX())
).toRotationMatrix();
break;
case 4:
transform.linear() = (
rl::math::AngleAxis(orientation.z(), rl::math::Vector3::UnitZ()) *
rl::math::AngleAxis(value.value<rl::math::Real>() * rl::math::constants::deg2rad, rl::math::Vector3::UnitY()) *
rl::math::AngleAxis(orientation.x(), rl::math::Vector3::UnitX())
).toRotationMatrix();
break;
case 5:
transform.linear() = (
rl::math::AngleAxis(value.value<rl::math::Real>() * rl::math::constants::deg2rad, rl::math::Vector3::UnitZ()) *
rl::math::AngleAxis(orientation.y(), rl::math::Vector3::UnitY()) *
rl::math::AngleAxis(orientation.x(), rl::math::Vector3::UnitX())
).toRotationMatrix();
break;
default:
break;
}
rl::math::Vector q = kinematic->getPosition();
std::shared_ptr<rl::mdl::InverseKinematics> ik;
if ("JacobianInverseKinematics" == MainWindow::instance()->ikAlgorithmComboBox->currentText())
{
ik = std::make_shared<rl::mdl::JacobianInverseKinematics>(kinematic);
rl::mdl::JacobianInverseKinematics* jacobianIk = static_cast<rl::mdl::JacobianInverseKinematics*>(ik.get());
jacobianIk->setDuration(std::chrono::milliseconds(MainWindow::instance()->ikDurationSpinBox->cleanText().toUInt()));
jacobianIk->setIterations(MainWindow::instance()->ikIterationsSpinBox->cleanText().toUInt());
if ("DLS" == MainWindow::instance()->ikJacobianComboBox->currentText())
{
jacobianIk->setMethod(rl::mdl::JacobianInverseKinematics::Method::dls);
}
else if ("SVD" == MainWindow::instance()->ikJacobianComboBox->currentText())
{
jacobianIk->setMethod(rl::mdl::JacobianInverseKinematics::Method::svd);
}
else if ("Transpose" == MainWindow::instance()->ikJacobianComboBox->currentText())
{
jacobianIk->setMethod(rl::mdl::JacobianInverseKinematics::Method::transpose);
}
}
#ifdef RL_MDL_NLOPT
else if ("NloptInverseKinematics" == MainWindow::instance()->ikAlgorithmComboBox->currentText())
{
ik = std::make_shared<rl::mdl::NloptInverseKinematics>(kinematic);
rl::mdl::NloptInverseKinematics* nloptIk = static_cast<rl::mdl::NloptInverseKinematics*>(ik.get());
nloptIk->setDuration(std::chrono::milliseconds(MainWindow::instance()->ikDurationSpinBox->cleanText().toUInt()));
nloptIk->setIterations(MainWindow::instance()->ikIterationsSpinBox->cleanText().toUInt());
}
#endif
for (std::size_t i = 0; i < kinematic->getOperationalDof(); ++i)
{
if (MainWindow::instance()->operationalGoals[this->id][i])
{
ik->addGoal(i == index.row() ? transform : kinematic->getOperationalPosition(i), i);
}
}
std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now();
bool solved = ik->solve();
std::chrono::steady_clock::time_point stop = std::chrono::steady_clock::now();
if (solved)
{
MainWindow::instance()->statusBar()->showMessage("IK solved in " + QString::number(std::chrono::duration<double>(stop - start).count() * rl::math::constants::unit2milli) + " ms", 2000);
kinematic->forwardPosition();
for (std::size_t i = 0; i < MainWindow::instance()->geometryModels[this->id]->getNumBodies(); ++i)
{
MainWindow::instance()->geometryModels[this->id]->getBody(i)->setFrame(kinematic->getBodyFrame(i));
}
emit dataChanged(this->createIndex(0, 0), this->createIndex(this->rowCount(), this->columnCount()));
return true;
}
else
{
MainWindow::instance()->statusBar()->showMessage("IK failed", 2000);
kinematic->setPosition(q);
kinematic->forwardPosition();
}
}
}
return false;
}
<|endoftext|>
|
<commit_before>#ifndef MP_INTRUSIVEPTR_HPP
#define MP_INTRUSIVEPTR_HPP
#include <boost/atomic.hpp>
// boost::intrusive_ptr but safe/atomic
template<typename T>
struct IntrusivePtr {
boost::atomic<T*> ptr;
IntrusivePtr(T* _p = NULL) : ptr(NULL) {
if(_p) {
intrusive_ptr_add_ref(_p);
ptr = _p;
}
}
IntrusivePtr(const IntrusivePtr& other) : ptr(NULL) {
T* p = other.ptr.load();
swap(IntrusivePtr(p));
}
~IntrusivePtr() {
T* _p = ptr.exchange(NULL);
if(_p)
intrusive_ptr_release(_p);
}
IntrusivePtr& operator=(const IntrusivePtr& other) {
T* p = other.ptr.load();
swap(IntrusivePtr(p));
return *this;
}
T* get() const { return ptr; }
T& operator*() const { return *ptr; }
T* operator->() const { return ptr; }
operator bool() const { return ptr; }
operator T*() const { return ptr; }
bool operator==(const IntrusivePtr& other) const { return ptr == other.ptr; }
bool operator!=(const IntrusivePtr& other) const { return ptr != other.ptr; }
IntrusivePtr& swap(IntrusivePtr&& other) {
T* old = ptr.exchange(other.ptr);
other.ptr = old;
return other;
}
IntrusivePtr exchange(T* other) {
IntrusivePtr old = swap(IntrusivePtr(other));
return old;
}
bool compare_exchange(T* expected, T* desired, T** old = NULL) {
bool success = ptr.compare_exchange_strong(expected, desired);
if(success && expected != desired) {
intrusive_ptr_add_ref(desired);
intrusive_ptr_release(expected);
}
if(old)
*old = expected;
return success;
}
void reset(T* _p = NULL) {
swap(IntrusivePtr(_p));
}
};
#endif // INTRUSIVEPTR_HPP
<commit_msg>comment IntrusivePtr<commit_after>#ifndef MP_INTRUSIVEPTR_HPP
#define MP_INTRUSIVEPTR_HPP
#include <boost/atomic.hpp>
// boost::intrusive_ptr but safe/atomic.
// I.e. pointer to an object with an embedded reference count.
// intrusive_ptr_add_ref(T*) and intrusive_ptr_release(T*) must be declared.
// You can also derive from boost::intrusive_ref_counter.
template<typename T>
struct IntrusivePtr {
boost::atomic<T*> ptr;
IntrusivePtr(T* _p = NULL) : ptr(NULL) {
if(_p) {
intrusive_ptr_add_ref(_p);
ptr = _p;
}
}
IntrusivePtr(const IntrusivePtr& other) : ptr(NULL) {
T* p = other.ptr.load();
swap(IntrusivePtr(p));
}
~IntrusivePtr() {
T* _p = ptr.exchange(NULL);
if(_p)
intrusive_ptr_release(_p);
}
IntrusivePtr& operator=(const IntrusivePtr& other) {
T* p = other.ptr.load();
swap(IntrusivePtr(p));
return *this;
}
T* get() const { return ptr; }
T& operator*() const { return *ptr; }
T* operator->() const { return ptr; }
operator bool() const { return ptr; }
operator T*() const { return ptr; }
bool operator==(const IntrusivePtr& other) const { return ptr == other.ptr; }
bool operator!=(const IntrusivePtr& other) const { return ptr != other.ptr; }
IntrusivePtr& swap(IntrusivePtr&& other) {
T* old = ptr.exchange(other.ptr);
other.ptr = old;
return other;
}
IntrusivePtr exchange(T* other) {
IntrusivePtr old = swap(IntrusivePtr(other));
return old;
}
bool compare_exchange(T* expected, T* desired, T** old = NULL) {
bool success = ptr.compare_exchange_strong(expected, desired);
if(success && expected != desired) {
intrusive_ptr_add_ref(desired);
intrusive_ptr_release(expected);
}
if(old)
*old = expected;
return success;
}
void reset(T* _p = NULL) {
swap(IntrusivePtr(_p));
}
};
#endif // INTRUSIVEPTR_HPP
<|endoftext|>
|
<commit_before>// @(#)root/rootx:$Name: $:$Id: rootx.cxx,v 1.18 2005/09/04 09:13:27 brun Exp $
// Author: Fons Rademakers 19/02/98
//////////////////////////////////////////////////////////////////////////
// //
// Rootx //
// //
// Rootx is a small front-end program that starts the main ROOT module. //
// This program is called "root" in the $ROOTSYS/bin directory and the //
// real ROOT executable is now called "root.exe" (formerly "root"). //
// Rootx puts up a splash screen giving some info about the current //
// version of ROOT and, more importanly, it sets up the required //
// LD_LIBRARY_PATH, SHLIB_PATH and LIBPATH environment variables //
// (depending on the platform). //
// //
//////////////////////////////////////////////////////////////////////////
#ifdef HAVE_CONFIG
#include "config.h"
#endif
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <signal.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <errno.h>
#include <netdb.h>
#include <sys/socket.h>
#if defined(__sgi) || defined(__sun)
#define HAVE_UTMPX_H
#define UTMP_NO_ADDR
#endif
#if (defined(__alpha) && !defined(__linux)) || defined(_AIX) || \
defined(__FreeBSD__) || defined(__Lynx__) || defined(__APPLE__) || \
defined(__OpenBSD__)
#define UTMP_NO_ADDR
#endif
#ifdef __sun
# ifndef _REENTRANT
# if __SUNPRO_CC > 0x420
# define GLOBAL_ERRNO
# endif
# endif
#endif
#ifndef __VMS
# ifdef HAVE_UTMPX_H
# include <utmpx.h>
# define STRUCT_UTMP struct utmpx
# else
# if defined(__linux) && defined(__powerpc) && (__GNUC__ == 2) && (__GNUC_MINOR__ < 90)
extern "C" {
# endif
# include <utmp.h>
# define STRUCT_UTMP struct utmp
# endif
#endif
#if !defined(UTMP_FILE) && defined(_PATH_UTMP) // 4.4BSD
#define UTMP_FILE _PATH_UTMP
#endif
#if defined(UTMPX_FILE) // Solaris, SysVr4
#undef UTMP_FILE
#define UTMP_FILE UTMPX_FILE
#endif
#ifndef UTMP_FILE
#define UTMP_FILE "/etc/utmp"
#endif
#if defined(__CYGWIN__) && defined(__GNUC__)
#define ROOTBINARY "root_exe.exe"
#else
#define ROOTBINARY "root.exe"
#endif
extern void PopupLogo(bool);
extern void WaitLogo();
extern void PopdownLogo();
extern void CloseDisplay();
static STRUCT_UTMP *gUtmpContents;
static bool gNoLogo = false;
static int GetErrno()
{
#ifdef GLOBAL_ERRNO
return ::errno;
#else
return errno;
#endif
}
static void ResetErrno()
{
#ifdef GLOBAL_ERRNO
::errno = 0;
#else
errno = 0;
#endif
}
static int ReadUtmp()
{
FILE *utmp;
struct stat file_stats;
size_t n_read, size;
gUtmpContents = 0;
utmp = fopen(UTMP_FILE, "r");
if (!utmp)
return 0;
fstat(fileno(utmp), &file_stats);
size = file_stats.st_size;
if (size <= 0) {
fclose(utmp);
return 0;
}
gUtmpContents = (STRUCT_UTMP *) malloc(size);
if (!gUtmpContents) return 0;
n_read = fread(gUtmpContents, 1, size, utmp);
if (ferror(utmp) || fclose(utmp) == EOF || n_read < size) {
free(gUtmpContents);
gUtmpContents = 0;
return 0;
}
return size / sizeof(STRUCT_UTMP);
}
static STRUCT_UTMP *SearchEntry(int n, const char *tty)
{
STRUCT_UTMP *ue = gUtmpContents;
while (n--) {
if (ue->ut_name[0] && !strncmp(tty, ue->ut_line, sizeof(ue->ut_line)))
return ue;
ue++;
}
return 0;
}
static void SetDisplay()
{
// Set DISPLAY environment variable.
if (!getenv("DISPLAY")) {
char *tty = ttyname(0); // device user is logged in on
if (tty) {
tty += 5; // remove "/dev/"
STRUCT_UTMP *utmp_entry = SearchEntry(ReadUtmp(), tty);
if (utmp_entry) {
static char display[64];
if (utmp_entry->ut_host[0]) {
if (strchr(utmp_entry->ut_host, ':')) {
sprintf(display, "DISPLAY=%s", utmp_entry->ut_host);
fprintf(stderr, "*** DISPLAY not set, setting it to %s\n",
utmp_entry->ut_host);
} else {
sprintf(display, "DISPLAY=%s:0.0", utmp_entry->ut_host);
fprintf(stderr, "*** DISPLAY not set, setting it to %s:0.0\n",
utmp_entry->ut_host);
}
putenv((char *)display);
#ifndef UTMP_NO_ADDR
} else if (utmp_entry->ut_addr) {
struct hostent *he;
if ((he = gethostbyaddr((const char*)&utmp_entry->ut_addr,
sizeof(utmp_entry->ut_addr), AF_INET))) {
sprintf(display, "DISPLAY=%s:0.0", he->h_name);
fprintf(stderr, "*** DISPLAY not set, setting it to %s:0.0\n",
he->h_name);
putenv((char *)display);
}
#endif
}
}
free(gUtmpContents);
}
}
}
static void SetLibraryPath()
{
#ifndef ROOTLIBDIR
// Set library path for the different platforms.
char *msg;
# if defined(__hpux) || defined(_HIUX_SOURCE)
if (getenv("SHLIB_PATH")) {
msg = new char [strlen(getenv("ROOTSYS"))+strlen(getenv("SHLIB_PATH"))+100];
sprintf(msg, "SHLIB_PATH=%s/lib:%s", getenv("ROOTSYS"),
getenv("SHLIB_PATH"));
} else {
msg = new char [strlen(getenv("ROOTSYS"))+100];
sprintf(msg, "SHLIB_PATH=%s/lib", getenv("ROOTSYS"));
}
# elif defined(_AIX)
if (getenv("LIBPATH")) {
msg = new char [strlen(getenv("ROOTSYS"))+strlen(getenv("LIBPATH"))+100];
sprintf(msg, "LIBPATH=%s/lib:%s", getenv("ROOTSYS"),
getenv("LIBPATH"));
} else {
msg = new char [strlen(getenv("ROOTSYS"))+100];
sprintf(msg, "LIBPATH=%s/lib:/lib:/usr/lib", getenv("ROOTSYS"));
}
# elif defined(__APPLE__)
if (getenv("DYLD_LIBRARY_PATH")) {
msg = new char [strlen(getenv("ROOTSYS"))+strlen(getenv("DYLD_LIBRARY_PATH"))+100];
sprintf(msg, "DYLD_LIBRARY_PATH=%s/lib:%s", getenv("ROOTSYS"),
getenv("DYLD_LIBRARY_PATH"));
} else {
msg = new char [strlen(getenv("ROOTSYS"))+100];
sprintf(msg, "DYLD_LIBRARY_PATH=%s/lib", getenv("ROOTSYS"));
}
# else
if (getenv("LD_LIBRARY_PATH")) {
msg = new char [strlen(getenv("ROOTSYS"))+strlen(getenv("LD_LIBRARY_PATH"))+100];
sprintf(msg, "LD_LIBRARY_PATH=%s/lib:%s", getenv("ROOTSYS"),
getenv("LD_LIBRARY_PATH"));
} else {
msg = new char [strlen(getenv("ROOTSYS"))+100];
# if defined(__sun)
sprintf(msg, "LD_LIBRARY_PATH=%s/lib:/usr/dt/lib", getenv("ROOTSYS"));
# else
sprintf(msg, "LD_LIBRARY_PATH=%s/lib", getenv("ROOTSYS"));
# endif
}
# endif
putenv(msg);
#endif
}
extern "C" {
static void SigUsr1(int);
}
static void SigUsr1(int)
{
// When we get SIGUSR1 from child (i.e. ROOT) then pop down logo.
if (!gNoLogo)
PopdownLogo();
}
static void WaitChild(int childpid)
{
// Wait till child (i.e. ROOT) is finished.
int status;
do {
while (waitpid(childpid, &status, WUNTRACED) < 0) {
if (GetErrno() != EINTR)
break;
ResetErrno();
}
if (WIFEXITED(status))
exit(WEXITSTATUS(status));
if (WIFSIGNALED(status))
exit(WTERMSIG(status));
if (WIFSTOPPED(status)) { // child got ctlr-Z
raise(SIGTSTP); // stop also parent
kill(childpid, SIGCONT); // if parent wakes up, wake up child
}
} while (WIFSTOPPED(status));
exit(0);
}
static void PrintUsage(char *pname)
{
// This is a copy of the text in TApplication::GetOptions().
fprintf(stderr, "Usage: %s [-l] [-b] [-n] [-q] [dir] [file1.C ... fileN.C]\n", pname);
fprintf(stderr, "Options:\n");
fprintf(stderr, " -b : run in batch mode without graphics\n");
fprintf(stderr, " -n : do not execute logon and logoff macros as specified in .rootrc\n");
fprintf(stderr, " -q : exit after processing command line macro files\n");
fprintf(stderr, " -l : do not show splash screen\n");
fprintf(stderr, " dir : if dir is a valid directory cd to it before executing\n");
fprintf(stderr, "\n");
fprintf(stderr, " -? : print usage\n");
fprintf(stderr, " -h : print usage\n");
fprintf(stderr, " --help : print usage\n");
fprintf(stderr, " -config : print ./configure options\n");
fprintf(stderr, "\n");
}
int main(int argc, char **argv)
{
const int kMAXARGS = 256;
char *argvv[kMAXARGS];
char arg0[2048];
#ifndef ROOTPREFIX
if (!getenv("ROOTSYS")) {
fprintf(stderr, "%s: ROOTSYS not set. Set it before trying to run %s.\n",
argv[0], argv[0]);
return 1;
}
#endif
// In batch mode don't show splash screen, idem for no logo mode,
// in about mode show always splash screen
bool batch = false, about = false;
int i;
for (i = 1; i < argc; i++) {
if (!strcmp(argv[i], "-?") || !strncmp(argv[i], "-h", 2) ||
!strncmp(argv[i], "--help", 6)) {
PrintUsage(argv[0]);
return 1;
}
if (!strcmp(argv[i], "-b")) batch = true;
if (!strcmp(argv[i], "-l")) gNoLogo = true;
if (!strcmp(argv[i], "-a")) about = true;
if (!strcmp(argv[i], "-config")) gNoLogo = true;
}
if (batch)
gNoLogo = true;
if (about) {
batch = false;
gNoLogo = false;
}
if (!batch) {
SetDisplay();
if (!getenv("DISPLAY")) {
fprintf(stderr, "%s: can't figure out DISPLAY, set it manually\n", argv[0]);
return 1;
}
if (about) {
PopupLogo(true);
WaitLogo();
return 0;
} else if (!gNoLogo)
PopupLogo(false);
}
// Ignore SIGINT and SIGQUIT. Install handler for SIGUSR1.
struct sigaction ignore, handle, saveintr, savequit, saveusr1;
#if defined(__sun) && !defined(__i386) && !defined(__SVR4)
ignore.sa_handler = (void (*)())SIG_IGN;
#elif defined(__sun) && defined(__SVR4)
ignore.sa_handler = (void (*)(int))SIG_IGN;
#else
ignore.sa_handler = SIG_IGN;
#endif
sigemptyset(&ignore.sa_mask);
ignore.sa_flags = 0;
handle = ignore;
#if defined(__sun) && !defined(__i386) && !defined(__SVR4)
handle.sa_handler = (void (*)())SigUsr1;
#elif defined(__sun) && defined(__SVR4)
handle.sa_handler = SigUsr1;
#elif (defined(__sgi) && !defined(__KCC)) || defined(__Lynx__)
# if defined(IRIX64) || (__GNUG__>=3)
handle.sa_handler = SigUsr1;
# else
handle.sa_handler = (void (*)(...))SigUsr1;
# endif
#else
handle.sa_handler = SigUsr1;
#endif
sigaction(SIGINT, &ignore, &saveintr);
sigaction(SIGQUIT, &ignore, &savequit);
sigaction(SIGUSR1, &handle, &saveusr1);
// Create child...
int childpid;
if ((childpid = fork()) < 0) {
fprintf(stderr, "%s: error forking child\n", argv[0]);
return 1;
} else if (childpid > 0) {
if (!gNoLogo)
WaitLogo();
WaitChild(childpid);
}
// Continue with child...
// Restore original signal actions
sigaction(SIGINT, &saveintr, 0);
sigaction(SIGQUIT, &savequit, 0);
sigaction(SIGUSR1, &saveusr1, 0);
// Close X display connection
CloseDisplay();
// Child is going to overlay itself with the actual ROOT module...
// Build argv vector
#ifdef ROOTBINDIR
sprintf(arg0, "%s/%s", ROOTBINDIR, ROOTBINARY);
#else
sprintf(arg0, "%s/bin/%s", getenv("ROOTSYS"), ROOTBINARY);
#endif
argvv[0] = arg0;
argvv[1] = (char *) "-splash";
int iargc = argc;
if (iargc > kMAXARGS-2) iargc = kMAXARGS-2;
for (i = 1; i < iargc; i++)
argvv[1+i] = argv[i];
argvv[1+i] = 0;
// Make sure library path is set
SetLibraryPath();
// Execute actual ROOT module
execv(arg0, argvv);
// Exec failed
#ifndef ROOTBINDIR
fprintf(stderr,
"%s: can't start ROOT -- check that %s/bin/%s exists!\n",
argv[0], getenv("ROOTSYS"), ROOTBINARY);
#else
fprintf(stderr, "%s: can't start ROOT -- check that %s/%s exists!\n",
argv[0], ROOTBINDIR, ROOTBINARY);
#endif
return 1;
}
<commit_msg>make sure that the utmp host field is not truncated. Could easily happen on Mac OS X where the host field is only 16 long.<commit_after>// @(#)root/rootx:$Name: $:$Id: rootx.cxx,v 1.19 2005/09/13 13:29:51 rdm Exp $
// Author: Fons Rademakers 19/02/98
//////////////////////////////////////////////////////////////////////////
// //
// Rootx //
// //
// Rootx is a small front-end program that starts the main ROOT module. //
// This program is called "root" in the $ROOTSYS/bin directory and the //
// real ROOT executable is now called "root.exe" (formerly "root"). //
// Rootx puts up a splash screen giving some info about the current //
// version of ROOT and, more importanly, it sets up the required //
// LD_LIBRARY_PATH, SHLIB_PATH and LIBPATH environment variables //
// (depending on the platform). //
// //
//////////////////////////////////////////////////////////////////////////
#ifdef HAVE_CONFIG
#include "config.h"
#endif
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <signal.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <errno.h>
#include <netdb.h>
#include <sys/socket.h>
#if defined(__sgi) || defined(__sun)
#define HAVE_UTMPX_H
#define UTMP_NO_ADDR
#endif
#if (defined(__alpha) && !defined(__linux)) || defined(_AIX) || \
defined(__FreeBSD__) || defined(__Lynx__) || defined(__APPLE__) || \
defined(__OpenBSD__)
#define UTMP_NO_ADDR
#endif
#ifdef __sun
# ifndef _REENTRANT
# if __SUNPRO_CC > 0x420
# define GLOBAL_ERRNO
# endif
# endif
#endif
#ifndef __VMS
# ifdef HAVE_UTMPX_H
# include <utmpx.h>
# define STRUCT_UTMP struct utmpx
# else
# if defined(__linux) && defined(__powerpc) && (__GNUC__ == 2) && (__GNUC_MINOR__ < 90)
extern "C" {
# endif
# include <utmp.h>
# define STRUCT_UTMP struct utmp
# endif
#endif
#if !defined(UTMP_FILE) && defined(_PATH_UTMP) // 4.4BSD
#define UTMP_FILE _PATH_UTMP
#endif
#if defined(UTMPX_FILE) // Solaris, SysVr4
#undef UTMP_FILE
#define UTMP_FILE UTMPX_FILE
#endif
#ifndef UTMP_FILE
#define UTMP_FILE "/etc/utmp"
#endif
#if defined(__CYGWIN__) && defined(__GNUC__)
#define ROOTBINARY "root_exe.exe"
#else
#define ROOTBINARY "root.exe"
#endif
extern void PopupLogo(bool);
extern void WaitLogo();
extern void PopdownLogo();
extern void CloseDisplay();
static STRUCT_UTMP *gUtmpContents;
static bool gNoLogo = false;
static int GetErrno()
{
#ifdef GLOBAL_ERRNO
return ::errno;
#else
return errno;
#endif
}
static void ResetErrno()
{
#ifdef GLOBAL_ERRNO
::errno = 0;
#else
errno = 0;
#endif
}
static int ReadUtmp()
{
FILE *utmp;
struct stat file_stats;
size_t n_read, size;
gUtmpContents = 0;
utmp = fopen(UTMP_FILE, "r");
if (!utmp)
return 0;
fstat(fileno(utmp), &file_stats);
size = file_stats.st_size;
if (size <= 0) {
fclose(utmp);
return 0;
}
gUtmpContents = (STRUCT_UTMP *) malloc(size);
if (!gUtmpContents) return 0;
n_read = fread(gUtmpContents, 1, size, utmp);
if (ferror(utmp) || fclose(utmp) == EOF || n_read < size) {
free(gUtmpContents);
gUtmpContents = 0;
return 0;
}
return size / sizeof(STRUCT_UTMP);
}
static STRUCT_UTMP *SearchEntry(int n, const char *tty)
{
STRUCT_UTMP *ue = gUtmpContents;
while (n--) {
if (ue->ut_name[0] && !strncmp(tty, ue->ut_line, sizeof(ue->ut_line)))
return ue;
ue++;
}
return 0;
}
static void SetDisplay()
{
// Set DISPLAY environment variable.
if (!getenv("DISPLAY")) {
char *tty = ttyname(0); // device user is logged in on
if (tty) {
tty += 5; // remove "/dev/"
STRUCT_UTMP *utmp_entry = SearchEntry(ReadUtmp(), tty);
if (utmp_entry) {
static char display[64];
if (utmp_entry->ut_host[0] &&
!utmp_entry->ut_host[sizeof(utmp_entry->ut_host)-1]) {
if (strchr(utmp_entry->ut_host, ':')) {
sprintf(display, "DISPLAY=%s", utmp_entry->ut_host);
fprintf(stderr, "*** DISPLAY not set, setting it to %s\n",
utmp_entry->ut_host);
} else {
sprintf(display, "DISPLAY=%s:0.0", utmp_entry->ut_host);
fprintf(stderr, "*** DISPLAY not set, setting it to %s:0.0\n",
utmp_entry->ut_host);
}
putenv((char *)display);
#ifndef UTMP_NO_ADDR
} else if (utmp_entry->ut_addr) {
struct hostent *he;
if ((he = gethostbyaddr((const char*)&utmp_entry->ut_addr,
sizeof(utmp_entry->ut_addr), AF_INET))) {
sprintf(display, "DISPLAY=%s:0.0", he->h_name);
fprintf(stderr, "*** DISPLAY not set, setting it to %s:0.0\n",
he->h_name);
putenv((char *)display);
}
#endif
}
}
free(gUtmpContents);
}
}
}
static void SetLibraryPath()
{
#ifndef ROOTLIBDIR
// Set library path for the different platforms.
char *msg;
# if defined(__hpux) || defined(_HIUX_SOURCE)
if (getenv("SHLIB_PATH")) {
msg = new char [strlen(getenv("ROOTSYS"))+strlen(getenv("SHLIB_PATH"))+100];
sprintf(msg, "SHLIB_PATH=%s/lib:%s", getenv("ROOTSYS"),
getenv("SHLIB_PATH"));
} else {
msg = new char [strlen(getenv("ROOTSYS"))+100];
sprintf(msg, "SHLIB_PATH=%s/lib", getenv("ROOTSYS"));
}
# elif defined(_AIX)
if (getenv("LIBPATH")) {
msg = new char [strlen(getenv("ROOTSYS"))+strlen(getenv("LIBPATH"))+100];
sprintf(msg, "LIBPATH=%s/lib:%s", getenv("ROOTSYS"),
getenv("LIBPATH"));
} else {
msg = new char [strlen(getenv("ROOTSYS"))+100];
sprintf(msg, "LIBPATH=%s/lib:/lib:/usr/lib", getenv("ROOTSYS"));
}
# elif defined(__APPLE__)
if (getenv("DYLD_LIBRARY_PATH")) {
msg = new char [strlen(getenv("ROOTSYS"))+strlen(getenv("DYLD_LIBRARY_PATH"))+100];
sprintf(msg, "DYLD_LIBRARY_PATH=%s/lib:%s", getenv("ROOTSYS"),
getenv("DYLD_LIBRARY_PATH"));
} else {
msg = new char [strlen(getenv("ROOTSYS"))+100];
sprintf(msg, "DYLD_LIBRARY_PATH=%s/lib", getenv("ROOTSYS"));
}
# else
if (getenv("LD_LIBRARY_PATH")) {
msg = new char [strlen(getenv("ROOTSYS"))+strlen(getenv("LD_LIBRARY_PATH"))+100];
sprintf(msg, "LD_LIBRARY_PATH=%s/lib:%s", getenv("ROOTSYS"),
getenv("LD_LIBRARY_PATH"));
} else {
msg = new char [strlen(getenv("ROOTSYS"))+100];
# if defined(__sun)
sprintf(msg, "LD_LIBRARY_PATH=%s/lib:/usr/dt/lib", getenv("ROOTSYS"));
# else
sprintf(msg, "LD_LIBRARY_PATH=%s/lib", getenv("ROOTSYS"));
# endif
}
# endif
putenv(msg);
#endif
}
extern "C" {
static void SigUsr1(int);
}
static void SigUsr1(int)
{
// When we get SIGUSR1 from child (i.e. ROOT) then pop down logo.
if (!gNoLogo)
PopdownLogo();
}
static void WaitChild(int childpid)
{
// Wait till child (i.e. ROOT) is finished.
int status;
do {
while (waitpid(childpid, &status, WUNTRACED) < 0) {
if (GetErrno() != EINTR)
break;
ResetErrno();
}
if (WIFEXITED(status))
exit(WEXITSTATUS(status));
if (WIFSIGNALED(status))
exit(WTERMSIG(status));
if (WIFSTOPPED(status)) { // child got ctlr-Z
raise(SIGTSTP); // stop also parent
kill(childpid, SIGCONT); // if parent wakes up, wake up child
}
} while (WIFSTOPPED(status));
exit(0);
}
static void PrintUsage(char *pname)
{
// This is a copy of the text in TApplication::GetOptions().
fprintf(stderr, "Usage: %s [-l] [-b] [-n] [-q] [dir] [file1.C ... fileN.C]\n", pname);
fprintf(stderr, "Options:\n");
fprintf(stderr, " -b : run in batch mode without graphics\n");
fprintf(stderr, " -n : do not execute logon and logoff macros as specified in .rootrc\n");
fprintf(stderr, " -q : exit after processing command line macro files\n");
fprintf(stderr, " -l : do not show splash screen\n");
fprintf(stderr, " dir : if dir is a valid directory cd to it before executing\n");
fprintf(stderr, "\n");
fprintf(stderr, " -? : print usage\n");
fprintf(stderr, " -h : print usage\n");
fprintf(stderr, " --help : print usage\n");
fprintf(stderr, " -config : print ./configure options\n");
fprintf(stderr, "\n");
}
int main(int argc, char **argv)
{
const int kMAXARGS = 256;
char *argvv[kMAXARGS];
char arg0[2048];
#ifndef ROOTPREFIX
if (!getenv("ROOTSYS")) {
fprintf(stderr, "%s: ROOTSYS not set. Set it before trying to run %s.\n",
argv[0], argv[0]);
return 1;
}
#endif
// In batch mode don't show splash screen, idem for no logo mode,
// in about mode show always splash screen
bool batch = false, about = false;
int i;
for (i = 1; i < argc; i++) {
if (!strcmp(argv[i], "-?") || !strncmp(argv[i], "-h", 2) ||
!strncmp(argv[i], "--help", 6)) {
PrintUsage(argv[0]);
return 1;
}
if (!strcmp(argv[i], "-b")) batch = true;
if (!strcmp(argv[i], "-l")) gNoLogo = true;
if (!strcmp(argv[i], "-a")) about = true;
if (!strcmp(argv[i], "-config")) gNoLogo = true;
}
if (batch)
gNoLogo = true;
if (about) {
batch = false;
gNoLogo = false;
}
if (!batch) {
SetDisplay();
if (!getenv("DISPLAY")) {
fprintf(stderr, "%s: can't figure out DISPLAY, set it manually\n", argv[0]);
return 1;
}
if (about) {
PopupLogo(true);
WaitLogo();
return 0;
} else if (!gNoLogo)
PopupLogo(false);
}
// Ignore SIGINT and SIGQUIT. Install handler for SIGUSR1.
struct sigaction ignore, handle, saveintr, savequit, saveusr1;
#if defined(__sun) && !defined(__i386) && !defined(__SVR4)
ignore.sa_handler = (void (*)())SIG_IGN;
#elif defined(__sun) && defined(__SVR4)
ignore.sa_handler = (void (*)(int))SIG_IGN;
#else
ignore.sa_handler = SIG_IGN;
#endif
sigemptyset(&ignore.sa_mask);
ignore.sa_flags = 0;
handle = ignore;
#if defined(__sun) && !defined(__i386) && !defined(__SVR4)
handle.sa_handler = (void (*)())SigUsr1;
#elif defined(__sun) && defined(__SVR4)
handle.sa_handler = SigUsr1;
#elif (defined(__sgi) && !defined(__KCC)) || defined(__Lynx__)
# if defined(IRIX64) || (__GNUG__>=3)
handle.sa_handler = SigUsr1;
# else
handle.sa_handler = (void (*)(...))SigUsr1;
# endif
#else
handle.sa_handler = SigUsr1;
#endif
sigaction(SIGINT, &ignore, &saveintr);
sigaction(SIGQUIT, &ignore, &savequit);
sigaction(SIGUSR1, &handle, &saveusr1);
// Create child...
int childpid;
if ((childpid = fork()) < 0) {
fprintf(stderr, "%s: error forking child\n", argv[0]);
return 1;
} else if (childpid > 0) {
if (!gNoLogo)
WaitLogo();
WaitChild(childpid);
}
// Continue with child...
// Restore original signal actions
sigaction(SIGINT, &saveintr, 0);
sigaction(SIGQUIT, &savequit, 0);
sigaction(SIGUSR1, &saveusr1, 0);
// Close X display connection
CloseDisplay();
// Child is going to overlay itself with the actual ROOT module...
// Build argv vector
#ifdef ROOTBINDIR
sprintf(arg0, "%s/%s", ROOTBINDIR, ROOTBINARY);
#else
sprintf(arg0, "%s/bin/%s", getenv("ROOTSYS"), ROOTBINARY);
#endif
argvv[0] = arg0;
argvv[1] = (char *) "-splash";
int iargc = argc;
if (iargc > kMAXARGS-2) iargc = kMAXARGS-2;
for (i = 1; i < iargc; i++)
argvv[1+i] = argv[i];
argvv[1+i] = 0;
// Make sure library path is set
SetLibraryPath();
// Execute actual ROOT module
execv(arg0, argvv);
// Exec failed
#ifndef ROOTBINDIR
fprintf(stderr,
"%s: can't start ROOT -- check that %s/bin/%s exists!\n",
argv[0], getenv("ROOTSYS"), ROOTBINARY);
#else
fprintf(stderr, "%s: can't start ROOT -- check that %s/%s exists!\n",
argv[0], ROOTBINDIR, ROOTBINARY);
#endif
return 1;
}
<|endoftext|>
|
<commit_before>
#ifndef __CLIENT_HPP__
#define __CLIENT_HPP__
#include <pthread.h>
#include "protocol.hpp"
#include "sqlite_protocol.hpp"
#include <stdint.h>
#include "assert.h"
#define update_salt 6830
using namespace std;
/* Information shared between clients */
struct shared_t {
public:
shared_t(config_t *_config)
: config(_config),
qps_offset(0), latencies_offset(0),
qps_fd(NULL), latencies_fd(NULL),
last_qps(0), n_op(1), n_tick(1), n_ops_so_far(0)
{
pthread_mutex_init(&mutex, NULL);
if(config->qps_file[0] != 0) {
qps_fd = fopen(config->qps_file, "wa");
}
if(config->latency_file[0] != 0) {
latencies_fd = fopen(config->latency_file, "wa");
}
value_buf = new char[config->values.max];
memset((void *) value_buf, 'A', config->values.max);
}
~shared_t() {
if(qps_fd) {
fwrite(qps, 1, qps_offset, qps_fd);
fclose(qps_fd);
}
if(latencies_fd) {
fwrite(latencies, 1, latencies_offset, latencies_fd);
fclose(latencies_fd);
}
pthread_mutex_destroy(&mutex);
delete value_buf;
}
void push_qps(int _qps, int tick) {
if(!qps_fd && !latencies_fd)
return;
lock();
// Collect qps info from all clients before attempting to print
if(config->clients > 1) {
int qps_count = 0, agg_qps = 0;
map<int, pair<int, int> >::iterator op = qps_map.find(tick);
if(op != qps_map.end()) {
qps_count = op->second.first;
agg_qps = op->second.second;
}
qps_count += 1;
agg_qps += _qps;
if(qps_count == config->clients) {
_qps = agg_qps;
qps_map.erase(op);
} else {
qps_map[tick] = pair<int, int>(qps_count, agg_qps);
unlock();
return;
}
}
last_qps = _qps;
if(!qps_fd) {
unlock();
return;
}
int _off = snprintf(qps + qps_offset, sizeof(qps) - qps_offset, "%d\t\t%d\n", n_tick, _qps);
if(_off >= sizeof(qps) - qps_offset) {
// Couldn't write everything, flush
fwrite(qps, 1, qps_offset, qps_fd);
// Write again
qps_offset = 0;
_off = snprintf(qps + qps_offset, sizeof(qps) - qps_offset, "%d\t\t%d\n", n_tick, _qps);
}
qps_offset += _off;
n_tick++;
unlock();
}
void push_latency(float latency) {
lock();
n_ops_so_far++;
unlock();
/*
if(n_ops_so_far % 200000 == 0)
printf("%ld\n", n_ops_so_far);
*/
if(!latencies_fd || last_qps == 0)
return;
// We cannot possibly write every latency because that stalls
// the client, so we want to scale that by the number of qps
// (we'll sample latencies for roughly N random ops every
// second).
const int samples_per_second = 20;
if(rand() % (last_qps / samples_per_second) != 0) {
return;
}
lock();
int _off = snprintf(latencies + latencies_offset, sizeof(latencies) - latencies_offset, "%ld\t\t%.2f\n", n_op, latency);
if(_off >= sizeof(latencies) - latencies_offset) {
// Couldn't write everything, flush
fwrite(latencies, 1, latencies_offset, latencies_fd);
// Write again
latencies_offset = 0;
_off = snprintf(latencies + latencies_offset, sizeof(latencies) - latencies_offset, "%ld\t\t%.2f\n", n_op, latency);
}
latencies_offset += _off;
n_op++;
unlock();
}
private:
config_t *config;
map<int, pair<int, int> > qps_map;
char qps[40960], latencies[40960];
int qps_offset, latencies_offset;
FILE *qps_fd, *latencies_fd;
pthread_mutex_t mutex;
int last_qps;
long n_op;
int n_tick;
long n_ops_so_far;
public:
// We have one value shared among all the threads.
char *value_buf;
private:
void lock() {
pthread_mutex_lock(&mutex);
}
void unlock() {
pthread_mutex_unlock(&mutex);
}
};
/* Communication structure for main thread and clients */
struct client_data_t {
config_t *config;
server_t *server;
shared_t *shared;
protocol_t *proto;
sqlite_protocol_t *sqlite;
int id;
int min_seed, max_seed;
};
/* The function that does the work */
void* run_client(void* data) {
// Grab the config
client_data_t *client_data = (client_data_t*)data;
config_t *config = client_data->config;
server_t *server = client_data->server;
shared_t *shared = client_data->shared;
protocol_t *proto = client_data->proto;
sqlite_protocol_t *sqlite = client_data->sqlite;
if(sqlite)
sqlite->set_id(client_data->id);
const size_t per_key_size = config->keys.calculate_max_length(config->clients - 1);
// Perform the ops
ticks_t last_time = get_ticks(), start_time = last_time, last_qps_time = last_time, now_time;
int qps = 0, tick = 0;
int total_queries = 0;
int total_inserts = 0;
int total_deletes = 0;
bool keep_running = true;
while(keep_running) {
// Generate the command
load_t::load_op_t cmd = config->load.toss((config->batch_factor.min + config->batch_factor.max) / 2.0f);
payload_t op_keys[config->batch_factor.max];
char key_space[per_key_size * config->batch_factor.max];
for (int i = 0; i < config->batch_factor.max; i++)
op_keys[i].first = key_space + (per_key_size * i);
payload_t op_vals[config->batch_factor.max];
for (int i = 0; i < config->batch_factor.max; i++)
op_vals[i].first = shared->value_buf;
char val_verifcation_buffer[MAX_VALUE_SIZE];
char *old_val_buffer;
int j, k, l; // because we can't declare in the loop
int count;
int keyn; //same deal
uint64_t id_salt = client_data->id;
id_salt += id_salt << 32;
// TODO: If an workload contains contains no inserts and there are no keys available for a particular client (and the duration is specified in q/i), it'll just loop forever.
try {
switch(cmd) {
case load_t::delete_op:
if (client_data->min_seed == client_data->max_seed)
break;
config->keys.toss(op_keys, client_data->min_seed ^ id_salt, client_data->id, config->clients - 1);
// Delete it from the server
proto->remove(op_keys->first, op_keys->second);
if (sqlite && (client_data->min_seed % RELIABILITY) == 0)
sqlite->remove(op_keys->first, op_keys->second);
client_data->min_seed++;
qps++;
total_queries++;
total_deletes++;
break;
case load_t::update_op:
// Find the key and generate the payload
if (client_data->min_seed == client_data->max_seed)
break;
keyn = random(client_data->min_seed, client_data->max_seed);
config->keys.toss(op_keys, keyn ^ id_salt, client_data->id, config->clients - 1);
op_vals[0].second = seeded_random(config->values.min, config->values.max, client_data->max_seed ^ id_salt ^ update_salt);
// Send it to server
proto->update(op_keys->first, op_keys->second, op_vals[0].first, op_vals[0].second);
if (sqlite && (keyn % RELIABILITY) == 0)
sqlite->update(op_keys->first, op_keys->second, op_vals[0].first, op_vals[0].second);
// Free the value
qps++;
total_queries++;
break;
case load_t::insert_op:
// Generate the payload
config->keys.toss(op_keys, client_data->max_seed ^ id_salt, client_data->id, config->clients - 1);
op_vals[0].second = seeded_random(config->values.min, config->values.max, client_data->max_seed ^ id_salt);
// Send it to server
proto->insert(op_keys->first, op_keys->second, op_vals[0].first, op_vals[0].second);
if (sqlite && (client_data->max_seed % RELIABILITY) == 0)
sqlite->insert(op_keys->first, op_keys->second, op_vals[0].first, op_vals[0].second);
client_data->max_seed++;
// Free the value and save the key
qps++;
total_queries++;
total_inserts++;
break;
case load_t::read_op:
// Find the key
if(client_data->min_seed == client_data->max_seed)
break;
j = random(config->batch_factor.min, config->batch_factor.max);
j = std::min(j, client_data->max_seed - client_data->min_seed);
l = random(client_data->min_seed, client_data->max_seed - 1);
for (k = 0; k < j; k++) {
config->keys.toss(&op_keys[k], l ^ id_salt, client_data->id, config->clients - 1);
l++;
if(l >= client_data->max_seed)
l = client_data->min_seed;
}
// Read it from the server
proto->read(&op_keys[0], j);
qps += j;
total_queries += j;
break;
case load_t::append_op:
//TODO, this doesn't check if we'll be making the value too big. Gotta check for that.
//Find the key
if (client_data->min_seed == client_data->max_seed)
break;
keyn = random(client_data->min_seed, client_data->max_seed);
config->keys.toss(op_keys, keyn ^ id_salt, client_data->id, config->clients - 1);
op_vals[0].second = seeded_random(config->values.min, config->values.max, client_data->max_seed ^ id_salt);
proto->append(op_keys->first, op_keys->second, op_vals->first, op_vals->second);
if (sqlite && (keyn % RELIABILITY) == 0)
sqlite->append(op_keys->first, op_keys->second, op_vals->first, op_vals->second);
qps++;
total_queries++;
break;
case load_t::prepend_op:
//Find the key
if (client_data->min_seed == client_data->max_seed)
break;
keyn = random(client_data->min_seed, client_data->max_seed);
config->keys.toss(op_keys, keyn ^ id_salt, client_data->id, config->clients - 1);
op_vals[0].second = seeded_random(config->values.min, config->values.max, client_data->max_seed ^ id_salt);
proto->prepend(op_keys->first, op_keys->second, op_vals->first, op_vals->second);
if (sqlite && (keyn % RELIABILITY) == 0)
sqlite->prepend(op_keys->first, op_keys->second, op_vals->first, op_vals->second);
qps++;
total_queries++;
break;
case load_t::verify_op:
/* this is a very expensive operation it will first do a very
* expensive operation on the SQLITE reference db and then it will
* do several queries on the db that's being stressed (and only add
* 1 total query), it does not make sense to use this as part of a
* benchmarking run */
// we can't do anything without a reference
if (!sqlite)
break;
/* this is hacky but whatever */
old_val_buffer = op_vals[0].first;
op_vals[0].first = val_verifcation_buffer;
op_vals[0].second = 0;
sqlite->dump_start();
while (sqlite->dump_next(op_keys, op_vals)) {
proto->read(op_keys, 1, op_vals);
}
sqlite->dump_end();
op_vals[0].first = old_val_buffer;
qps++;
total_queries++;
break;
default:
fprintf(stderr, "Uknown operation\n");
exit(-1);
};
} catch (const protocol_error_t& e) {
fprintf(stderr, "Protocol error: %s\n", e.c_str());
exit(-1);
}
now_time = get_ticks();
// Deal with individual op latency
ticks_t latency = now_time - last_time;
shared->push_latency(ticks_to_us(latency));
last_time = now_time;
// Deal with QPS
if(ticks_to_secs(now_time - last_qps_time) >= 1.0f) {
shared->push_qps(qps, tick);
last_qps_time = now_time;
qps = 0;
tick++;
}
// See if we should keep running
if (config->duration.duration != -1) {
switch(config->duration.units) {
case duration_t::queries_t:
keep_running = total_queries < config->duration.duration / config->clients;
break;
case duration_t::seconds_t:
keep_running = ticks_to_secs(now_time - start_time) < config->duration.duration;
break;
case duration_t::inserts_t:
keep_running = total_inserts - total_deletes < config->duration.duration / config->clients;
break;
default:
fprintf(stderr, "Unknown duration unit\n");
exit(-1);
}
}
}
}
#endif // __CLIENT_HPP__
<commit_msg>Fix the stress clients behavior for high latency situations<commit_after>
#ifndef __CLIENT_HPP__
#define __CLIENT_HPP__
#include <pthread.h>
#include "protocol.hpp"
#include "sqlite_protocol.hpp"
#include <stdint.h>
#include "assert.h"
#define update_salt 6830
using namespace std;
/* Information shared between clients */
struct shared_t {
public:
shared_t(config_t *_config)
: config(_config),
qps_offset(0), latencies_offset(0),
qps_fd(NULL), latencies_fd(NULL),
last_qps(0), n_op(1), n_tick(1), n_ops_so_far(0)
{
pthread_mutex_init(&mutex, NULL);
if(config->qps_file[0] != 0) {
qps_fd = fopen(config->qps_file, "wa");
}
if(config->latency_file[0] != 0) {
latencies_fd = fopen(config->latency_file, "wa");
}
value_buf = new char[config->values.max];
memset((void *) value_buf, 'A', config->values.max);
}
~shared_t() {
if(qps_fd) {
fwrite(qps, 1, qps_offset, qps_fd);
fclose(qps_fd);
}
if(latencies_fd) {
fwrite(latencies, 1, latencies_offset, latencies_fd);
fclose(latencies_fd);
}
pthread_mutex_destroy(&mutex);
delete value_buf;
}
void push_qps(int _qps, int tick) {
if(!qps_fd && !latencies_fd)
return;
lock();
// Collect qps info from all clients before attempting to print
if(config->clients > 1) {
int qps_count = 0, agg_qps = 0;
map<int, pair<int, int> >::iterator op = qps_map.find(tick);
if(op != qps_map.end()) {
qps_count = op->second.first;
agg_qps = op->second.second;
}
qps_count += 1;
agg_qps += _qps;
if(qps_count == config->clients) {
_qps = agg_qps;
qps_map.erase(op);
} else {
qps_map[tick] = pair<int, int>(qps_count, agg_qps);
unlock();
return;
}
}
last_qps = _qps;
if(!qps_fd) {
unlock();
return;
}
int _off = snprintf(qps + qps_offset, sizeof(qps) - qps_offset, "%d\t\t%d\n", n_tick, _qps);
if(_off >= sizeof(qps) - qps_offset) {
// Couldn't write everything, flush
fwrite(qps, 1, qps_offset, qps_fd);
// Write again
qps_offset = 0;
_off = snprintf(qps + qps_offset, sizeof(qps) - qps_offset, "%d\t\t%d\n", n_tick, _qps);
}
qps_offset += _off;
n_tick++;
unlock();
}
void push_latency(float latency) {
lock();
n_ops_so_far++;
unlock();
/*
if(n_ops_so_far % 200000 == 0)
printf("%ld\n", n_ops_so_far);
*/
if(!latencies_fd || last_qps == 0)
return;
// We cannot possibly write every latency because that stalls
// the client, so we want to scale that by the number of qps
// (we'll sample latencies for roughly N random ops every
// second).
const int samples_per_second = 20;
if(rand() % (last_qps / samples_per_second) != 0) {
return;
}
lock();
int _off = snprintf(latencies + latencies_offset, sizeof(latencies) - latencies_offset, "%ld\t\t%.2f\n", n_op, latency);
if(_off >= sizeof(latencies) - latencies_offset) {
// Couldn't write everything, flush
fwrite(latencies, 1, latencies_offset, latencies_fd);
// Write again
latencies_offset = 0;
_off = snprintf(latencies + latencies_offset, sizeof(latencies) - latencies_offset, "%ld\t\t%.2f\n", n_op, latency);
}
latencies_offset += _off;
n_op++;
unlock();
}
private:
config_t *config;
map<int, pair<int, int> > qps_map;
char qps[40960], latencies[40960];
int qps_offset, latencies_offset;
FILE *qps_fd, *latencies_fd;
pthread_mutex_t mutex;
int last_qps;
long n_op;
int n_tick;
long n_ops_so_far;
public:
// We have one value shared among all the threads.
char *value_buf;
private:
void lock() {
pthread_mutex_lock(&mutex);
}
void unlock() {
pthread_mutex_unlock(&mutex);
}
};
/* Communication structure for main thread and clients */
struct client_data_t {
config_t *config;
server_t *server;
shared_t *shared;
protocol_t *proto;
sqlite_protocol_t *sqlite;
int id;
int min_seed, max_seed;
};
/* The function that does the work */
void* run_client(void* data) {
// Grab the config
client_data_t *client_data = (client_data_t*)data;
config_t *config = client_data->config;
server_t *server = client_data->server;
shared_t *shared = client_data->shared;
protocol_t *proto = client_data->proto;
sqlite_protocol_t *sqlite = client_data->sqlite;
if(sqlite)
sqlite->set_id(client_data->id);
const size_t per_key_size = config->keys.calculate_max_length(config->clients - 1);
// Perform the ops
ticks_t last_time = get_ticks(), start_time = last_time, last_qps_time = last_time, now_time;
int qps = 0, tick = 0;
int total_queries = 0;
int total_inserts = 0;
int total_deletes = 0;
bool keep_running = true;
while(keep_running) {
// Generate the command
load_t::load_op_t cmd = config->load.toss((config->batch_factor.min + config->batch_factor.max) / 2.0f);
payload_t op_keys[config->batch_factor.max];
char key_space[per_key_size * config->batch_factor.max];
for (int i = 0; i < config->batch_factor.max; i++)
op_keys[i].first = key_space + (per_key_size * i);
payload_t op_vals[config->batch_factor.max];
for (int i = 0; i < config->batch_factor.max; i++)
op_vals[i].first = shared->value_buf;
char val_verifcation_buffer[MAX_VALUE_SIZE];
char *old_val_buffer;
int j, k, l; // because we can't declare in the loop
int count;
int keyn; //same deal
uint64_t id_salt = client_data->id;
id_salt += id_salt << 32;
// TODO: If an workload contains contains no inserts and there are no keys available for a particular client (and the duration is specified in q/i), it'll just loop forever.
try {
switch(cmd) {
case load_t::delete_op:
if (client_data->min_seed == client_data->max_seed)
break;
config->keys.toss(op_keys, client_data->min_seed ^ id_salt, client_data->id, config->clients - 1);
// Delete it from the server
proto->remove(op_keys->first, op_keys->second);
if (sqlite && (client_data->min_seed % RELIABILITY) == 0)
sqlite->remove(op_keys->first, op_keys->second);
client_data->min_seed++;
qps++;
total_queries++;
total_deletes++;
break;
case load_t::update_op:
// Find the key and generate the payload
if (client_data->min_seed == client_data->max_seed)
break;
keyn = random(client_data->min_seed, client_data->max_seed);
config->keys.toss(op_keys, keyn ^ id_salt, client_data->id, config->clients - 1);
op_vals[0].second = seeded_random(config->values.min, config->values.max, client_data->max_seed ^ id_salt ^ update_salt);
// Send it to server
proto->update(op_keys->first, op_keys->second, op_vals[0].first, op_vals[0].second);
if (sqlite && (keyn % RELIABILITY) == 0)
sqlite->update(op_keys->first, op_keys->second, op_vals[0].first, op_vals[0].second);
// Free the value
qps++;
total_queries++;
break;
case load_t::insert_op:
// Generate the payload
config->keys.toss(op_keys, client_data->max_seed ^ id_salt, client_data->id, config->clients - 1);
op_vals[0].second = seeded_random(config->values.min, config->values.max, client_data->max_seed ^ id_salt);
// Send it to server
proto->insert(op_keys->first, op_keys->second, op_vals[0].first, op_vals[0].second);
if (sqlite && (client_data->max_seed % RELIABILITY) == 0)
sqlite->insert(op_keys->first, op_keys->second, op_vals[0].first, op_vals[0].second);
client_data->max_seed++;
// Free the value and save the key
qps++;
total_queries++;
total_inserts++;
break;
case load_t::read_op:
// Find the key
if(client_data->min_seed == client_data->max_seed)
break;
j = random(config->batch_factor.min, config->batch_factor.max);
j = std::min(j, client_data->max_seed - client_data->min_seed);
l = random(client_data->min_seed, client_data->max_seed - 1);
for (k = 0; k < j; k++) {
config->keys.toss(&op_keys[k], l ^ id_salt, client_data->id, config->clients - 1);
l++;
if(l >= client_data->max_seed)
l = client_data->min_seed;
}
// Read it from the server
proto->read(&op_keys[0], j);
qps += j;
total_queries += j;
break;
case load_t::append_op:
//TODO, this doesn't check if we'll be making the value too big. Gotta check for that.
//Find the key
if (client_data->min_seed == client_data->max_seed)
break;
keyn = random(client_data->min_seed, client_data->max_seed);
config->keys.toss(op_keys, keyn ^ id_salt, client_data->id, config->clients - 1);
op_vals[0].second = seeded_random(config->values.min, config->values.max, client_data->max_seed ^ id_salt);
proto->append(op_keys->first, op_keys->second, op_vals->first, op_vals->second);
if (sqlite && (keyn % RELIABILITY) == 0)
sqlite->append(op_keys->first, op_keys->second, op_vals->first, op_vals->second);
qps++;
total_queries++;
break;
case load_t::prepend_op:
//Find the key
if (client_data->min_seed == client_data->max_seed)
break;
keyn = random(client_data->min_seed, client_data->max_seed);
config->keys.toss(op_keys, keyn ^ id_salt, client_data->id, config->clients - 1);
op_vals[0].second = seeded_random(config->values.min, config->values.max, client_data->max_seed ^ id_salt);
proto->prepend(op_keys->first, op_keys->second, op_vals->first, op_vals->second);
if (sqlite && (keyn % RELIABILITY) == 0)
sqlite->prepend(op_keys->first, op_keys->second, op_vals->first, op_vals->second);
qps++;
total_queries++;
break;
case load_t::verify_op:
/* this is a very expensive operation it will first do a very
* expensive operation on the SQLITE reference db and then it will
* do several queries on the db that's being stressed (and only add
* 1 total query), it does not make sense to use this as part of a
* benchmarking run */
// we can't do anything without a reference
if (!sqlite)
break;
/* this is hacky but whatever */
old_val_buffer = op_vals[0].first;
op_vals[0].first = val_verifcation_buffer;
op_vals[0].second = 0;
sqlite->dump_start();
while (sqlite->dump_next(op_keys, op_vals)) {
proto->read(op_keys, 1, op_vals);
}
sqlite->dump_end();
op_vals[0].first = old_val_buffer;
qps++;
total_queries++;
break;
default:
fprintf(stderr, "Uknown operation\n");
exit(-1);
};
} catch (const protocol_error_t& e) {
fprintf(stderr, "Protocol error: %s\n", e.c_str());
exit(-1);
}
now_time = get_ticks();
// Deal with individual op latency
ticks_t latency = now_time - last_time;
shared->push_latency(ticks_to_us(latency));
last_time = now_time;
// Deal with QPS
if (ticks_to_secs(now_time - last_qps_time) >= 1.0f) {
// First deal with missed QPS
int qps_to_write = ticks_to_secs(now_time - last_qps_time);
while (qps_to_write > 1) {
shared->push_qps(0, tick);
//last_qps_time = now_time;
last_qps_time = last_qps_time + secs_to_ticks(1.0f);
tick++;
--qps_to_write;
}
shared->push_qps(qps, tick);
//last_qps_time = now_time;
last_qps_time = last_qps_time + secs_to_ticks(1.0f);
qps = 0;
tick++;
}
// See if we should keep running
if (config->duration.duration != -1) {
switch(config->duration.units) {
case duration_t::queries_t:
keep_running = total_queries < config->duration.duration / config->clients;
break;
case duration_t::seconds_t:
//keep_running = ticks_to_secs(now_time - start_time) < config->duration.duration;
keep_running = tick < config->duration.duration;
break;
case duration_t::inserts_t:
keep_running = total_inserts - total_deletes < config->duration.duration / config->clients;
break;
default:
fprintf(stderr, "Unknown duration unit\n");
exit(-1);
}
}
}
}
#endif // __CLIENT_HPP__
<|endoftext|>
|
<commit_before>/**
* @file
*/
#pragma once
#include "bi/io/indentable_ostream.hpp"
namespace bi {
/**
* C++ code generator.
*
* @ingroup compiler_io
*/
class CppBaseGenerator: public indentable_ostream {
public:
CppBaseGenerator(std::ostream& base, const int level = 0,
const bool header = false);
using indentable_ostream::visit;
virtual void visit(const Name* o);
virtual void visit(const List<Expression>* o);
virtual void visit(const Literal<bool>* o);
virtual void visit(const Literal<int64_t>* o);
virtual void visit(const Literal<double>* o);
virtual void visit(const Literal<const char*>* o);
virtual void visit(const Parentheses* o);
virtual void visit(const Brackets* o);
virtual void visit(const Call* o);
virtual void visit(const BinaryCall* o);
virtual void visit(const UnaryCall* o);
virtual void visit(const Slice* o);
virtual void visit(const Query* o);
virtual void visit(const Get* o);
virtual void visit(const LambdaFunction* o);
virtual void visit(const Span* o);
virtual void visit(const Index* o);
virtual void visit(const Range* o);
virtual void visit(const Member* o);
virtual void visit(const Super* o);
virtual void visit(const This* o);
virtual void visit(const Nil* o);
virtual void visit(const Parameter* o);
virtual void visit(const MemberParameter* o);
virtual void visit(const Identifier<Parameter>* o);
virtual void visit(const Identifier<MemberParameter>* o);
virtual void visit(const Identifier<GlobalVariable>* o);
virtual void visit(const Identifier<LocalVariable>* o);
virtual void visit(const Identifier<MemberVariable>* o);
virtual void visit(const OverloadedIdentifier<Function>* o);
virtual void visit(const OverloadedIdentifier<Fiber>* o);
virtual void visit(const OverloadedIdentifier<MemberFunction>* o);
virtual void visit(const OverloadedIdentifier<MemberFiber>* o);
virtual void visit(const OverloadedIdentifier<BinaryOperator>* o);
virtual void visit(const OverloadedIdentifier<UnaryOperator>* o);
virtual void visit(const File* o);
virtual void visit(const GlobalVariable* o);
virtual void visit(const LocalVariable* o);
virtual void visit(const MemberVariable* o);
virtual void visit(const List<Statement>* o);
virtual void visit(const Function* o);
virtual void visit(const Fiber* o);
virtual void visit(const MemberFunction* o);
virtual void visit(const MemberFiber* o);
virtual void visit(const Program* o);
virtual void visit(const BinaryOperator* o);
virtual void visit(const UnaryOperator* o);
virtual void visit(const AssignmentOperator* o);
virtual void visit(const ConversionOperator* o);
virtual void visit(const Basic* o);
virtual void visit(const Class* o);
virtual void visit(const Alias* o);
virtual void visit(const Assignment* o);
virtual void visit(const ExpressionStatement* o);
virtual void visit(const If* o);
virtual void visit(const For* o);
virtual void visit(const While* o);
virtual void visit(const Assert* o);
virtual void visit(const Return* o);
virtual void visit(const Yield* o);
virtual void visit(const Raw* o);
virtual void visit(const ListType* o);
virtual void visit(const EmptyType* o);
virtual void visit(const ArrayType* o);
virtual void visit(const ParenthesesType* o);
virtual void visit(const FunctionType* o);
virtual void visit(const FiberType* o);
virtual void visit(const OptionalType* o);
virtual void visit(const ClassType* o);
virtual void visit(const BasicType* o);
virtual void visit(const AliasType* o);
protected:
/**
* Generate the initialization of a variable, including the call to the
* constructor and/or assignment of the initial value.
*/
template<class T>
void genInit(const T* o);
/**
* Output header instead of source?
*/
bool header;
};
}
template<class T>
void bi::CppBaseGenerator::genInit(const T* o) {
if (o->type->isArray()) {
ArrayType* type = dynamic_cast<ArrayType*>(o->type);
assert(type);
middle('(');
if (!o->value->isEmpty()) {
middle(o->value << ", ");
}
middle("bi::make_frame(" << type->brackets << ')');
if (!o->parens->isEmpty()) {
middle(", " << o->parens->strip());
}
middle(')');
} else if (o->type->isClass()) {
ClassType* type = dynamic_cast<ClassType*>(o->type);
assert(type);
if (!o->parens->isEmpty()) {
middle(" = bi::make_object<bi::" << type->name << '>' << o->parens);
} else if (o->value->isEmpty()) {
middle(" = bi::make_object<bi::" << type->name << ">()");
}
} else if (!o->value->isEmpty()) {
middle(" = " << o->value);
}
}
<commit_msg>Fixed initialisation of objects when initial value given.<commit_after>/**
* @file
*/
#pragma once
#include "bi/io/indentable_ostream.hpp"
namespace bi {
/**
* C++ code generator.
*
* @ingroup compiler_io
*/
class CppBaseGenerator: public indentable_ostream {
public:
CppBaseGenerator(std::ostream& base, const int level = 0,
const bool header = false);
using indentable_ostream::visit;
virtual void visit(const Name* o);
virtual void visit(const List<Expression>* o);
virtual void visit(const Literal<bool>* o);
virtual void visit(const Literal<int64_t>* o);
virtual void visit(const Literal<double>* o);
virtual void visit(const Literal<const char*>* o);
virtual void visit(const Parentheses* o);
virtual void visit(const Brackets* o);
virtual void visit(const Call* o);
virtual void visit(const BinaryCall* o);
virtual void visit(const UnaryCall* o);
virtual void visit(const Slice* o);
virtual void visit(const Query* o);
virtual void visit(const Get* o);
virtual void visit(const LambdaFunction* o);
virtual void visit(const Span* o);
virtual void visit(const Index* o);
virtual void visit(const Range* o);
virtual void visit(const Member* o);
virtual void visit(const Super* o);
virtual void visit(const This* o);
virtual void visit(const Nil* o);
virtual void visit(const Parameter* o);
virtual void visit(const MemberParameter* o);
virtual void visit(const Identifier<Parameter>* o);
virtual void visit(const Identifier<MemberParameter>* o);
virtual void visit(const Identifier<GlobalVariable>* o);
virtual void visit(const Identifier<LocalVariable>* o);
virtual void visit(const Identifier<MemberVariable>* o);
virtual void visit(const OverloadedIdentifier<Function>* o);
virtual void visit(const OverloadedIdentifier<Fiber>* o);
virtual void visit(const OverloadedIdentifier<MemberFunction>* o);
virtual void visit(const OverloadedIdentifier<MemberFiber>* o);
virtual void visit(const OverloadedIdentifier<BinaryOperator>* o);
virtual void visit(const OverloadedIdentifier<UnaryOperator>* o);
virtual void visit(const File* o);
virtual void visit(const GlobalVariable* o);
virtual void visit(const LocalVariable* o);
virtual void visit(const MemberVariable* o);
virtual void visit(const List<Statement>* o);
virtual void visit(const Function* o);
virtual void visit(const Fiber* o);
virtual void visit(const MemberFunction* o);
virtual void visit(const MemberFiber* o);
virtual void visit(const Program* o);
virtual void visit(const BinaryOperator* o);
virtual void visit(const UnaryOperator* o);
virtual void visit(const AssignmentOperator* o);
virtual void visit(const ConversionOperator* o);
virtual void visit(const Basic* o);
virtual void visit(const Class* o);
virtual void visit(const Alias* o);
virtual void visit(const Assignment* o);
virtual void visit(const ExpressionStatement* o);
virtual void visit(const If* o);
virtual void visit(const For* o);
virtual void visit(const While* o);
virtual void visit(const Assert* o);
virtual void visit(const Return* o);
virtual void visit(const Yield* o);
virtual void visit(const Raw* o);
virtual void visit(const ListType* o);
virtual void visit(const EmptyType* o);
virtual void visit(const ArrayType* o);
virtual void visit(const ParenthesesType* o);
virtual void visit(const FunctionType* o);
virtual void visit(const FiberType* o);
virtual void visit(const OptionalType* o);
virtual void visit(const ClassType* o);
virtual void visit(const BasicType* o);
virtual void visit(const AliasType* o);
protected:
/**
* Generate the initialization of a variable, including the call to the
* constructor and/or assignment of the initial value.
*/
template<class T>
void genInit(const T* o);
/**
* Output header instead of source?
*/
bool header;
};
}
template<class T>
void bi::CppBaseGenerator::genInit(const T* o) {
if (o->type->isArray()) {
ArrayType* type = dynamic_cast<ArrayType*>(o->type);
assert(type);
middle('(');
if (!o->value->isEmpty()) {
middle(o->value << ", ");
}
middle("bi::make_frame(" << type->brackets << ')');
if (!o->parens->isEmpty()) {
middle(", " << o->parens->strip());
}
middle(')');
} else if (o->type->isClass()) {
ClassType* type = dynamic_cast<ClassType*>(o->type);
assert(type);
if (!o->parens->isEmpty()) {
middle(" = bi::make_object<bi::" << type->name << '>' << o->parens);
} else if (o->value->isEmpty()) {
middle(" = bi::make_object<bi::" << type->name << ">()");
}
if (!o->value->isEmpty()) {
middle(" = " << o->value);
}
} else if (!o->value->isEmpty()) {
middle(" = " << o->value);
}
}
<|endoftext|>
|
<commit_before>#include "L6470Stepper.h"
L6470Stepper::L6470Stepper(int pinCS, int nDaisyChain, int* motorSteps)
: SPIDaisyChain(pinCS, nDaisyChain)
{
_spiData = new L6470SpiData(nDaisyChain);
_motor = new L6470MotorData[nDaisyChain];
_readData = new uint32_t[nDaisyChain];
for (size_t i = 0; i < nDaisyChain; i++) {
_readData[i] = 0;
}
// pin settings
_pinBUSY = 0xFF; // NOT USE, default
_pinSTEP = 0xFF; // NOT USE, default
useBusy = false;
useStep = false;
for (int i=0; i<nDaisyChain; i++) {
if (motorSteps == NULL) _motor[i].setMotorStep(DEFAULT_MOTOR_STEP);
else _motor[i].setMotorStep(motorSteps[i]);
}
resetDriver();
}
L6470Stepper::~L6470Stepper()
{
delete[] _motor;
delete[] _spiData;
delete[] _readData;
}
void L6470Stepper::setup(registerStruct* regParamList, int size, int id)
{
// set motor driver as L6480
if (regParamList == NULL) regParamList = (registerStruct*)L6470DefaultRegParamList;
_writableRegNum = WRITABLE_REG_NUM_L6470;
for (int i=0; i<getDaisyChainNum(); i++) {
_motor[i].setup(L6470_REGISTER);
}
// initialize register
if (id < 0) {
for (int i=0; i<getDaisyChainNum(); i++) {
initRegister(regParamList, _writableRegNum, i);
}
} else {
if (size == 0) size = _writableRegNum;
initRegister(regParamList, size, id);
}
}
void L6470Stepper::angle(int degree)
{
for (int i=0; i<getDaisyChainNum(); i++) {
setAngle(degree, i);
}
transferAction();
}
void L6470Stepper::setAngle(int degree, int id)
{
if(id >= getDaisyChainNum())
return;
static int pre_degree = 0;
_motor[id].setAction(GOTO_DIR, degree, ((degree >= pre_degree) ? 1 : 0));
pre_degree = degree;
}
void L6470Stepper::step(int steps)
{
for (int i=0; i<getDaisyChainNum(); i++) {
setStep(steps, i);
}
transferAction();
}
void L6470Stepper::setStep(int steps, int id)
{
if(id >= getDaisyChainNum())
return;
if (steps < 0) {
_motor[id].setAction(MOVE, abs(steps), CCW);
} else {
_motor[id].setAction(MOVE, abs(steps), CW);
}
}
void L6470Stepper::rotate(motorDirection dir, int rps)
{
for (int i=0; i<getDaisyChainNum(); i++) {
setRotate(dir, i, rps);
}
transferAction();
}
void L6470Stepper::setRotate(motorDirection dir, int id, int rps)
{
if(id >= getDaisyChainNum())
return;
if (rps == 0) {
rps = _motor[id].getCurRps();
}
_motor[id].setAction(RUN, abs(rps), dir);
}
void L6470Stepper::setStepClockMode(_motorDirection dir, int id)
{
if(id >= getDaisyChainNum())
return;
_motor[id].setAction(STEPCLOCK, 0, dir);
transferAction();
}
long L6470Stepper::angleToStep(float angle, int motor_id)
{
long steps = (uint32_t)((double)_motor[motor_id].getMotorStep() * (double)pow(2, _motor[motor_id].getMicroStep()) * (double)angle / 360.0);
return steps;
}
float L6470Stepper::stepToAngle(long step, int motor_id)
{
unsigned long all_steps = (unsigned long)((double)_motor[motor_id].getMotorStep() * (double)pow(2, _motor[motor_id].getMicroStep()));
float angle = 360. * step / all_steps;
return angle;
}
void L6470Stepper::stepClock(float abs_angle, float ms, int motor_id)
{
float curr_angle = getCurrAngle();
float next_angle = abs_angle - curr_angle;
_motorDirection dir = (next_angle - curr_angle < 0) ? CCW : CW;
// long curr_step = getCurrStep();
// long next_step = angleToStep(abs_angle);
// long diff_step = next_step - curr_step;
// _motorDirection direction = (diff_step < 0) ? CCW : CW;
// diff_step = abs(diff_step);
stepClock(angleToStep(next_angle - curr_angle), dir, ms, motor_id);
}
void L6470Stepper::stepClock(long step, _motorDirection dir, float ms, int motor_id)
{
// noTone(_pinSTEP);
// delay(100);
setStepClockMode(dir, motor_id);
// delay(100);
unsigned int hz = 0;
if (ms <= 0) {
hz = 0xFFFF; // numeric_limits<int>::max() 16bit
} else {
hz = (unsigned int)getHzFrom(step, ms);
}
tone(_pinSTEP, hz);
}
long L6470Stepper::getHzFrom(long steps, float ms)
{
if (ms <= 0) {
return 0;
}
return (long)(1. / ((double)ms / 1000. / (double)steps));
}
void L6470Stepper::setRps(int rps)
{
for (int i=0; i<getDaisyChainNum(); i++) {
setRps(rps, i);
}
transferRegister();
}
void L6470Stepper::setRps(int rps, int id)
{
if(id >= getDaisyChainNum())
return;
_motor[id].setRegister(REG_MAX_SPEED, rps);
}
long L6470Stepper::readRegister(int reg, int motor_id)
{
for (int i=0; i<getDaisyChainNum(); i++) {
requestRegister(reg, i);
}
transferRegister();
long ret = 0;
if (reg == REG_ABS_POS) {
long sign = ((_readData[motor_id] & 0x200000) >> 21);
long val = (_readData[motor_id] & 0x1FFFFF);
if (sign == 0) {
ret = (long)val;
} else {
ret = (long)(-1) * (long)(0x200000 - val);
}
// Serial.print("sign : "); Serial.println(sign, HEX);
// Serial.print("value: "); Serial.println(val, HEX);
} else {
ret = (long)_readData[motor_id];
}
return ret;
}
void L6470Stepper::requestRegister(int reg, int id)
{
if(id >= getDaisyChainNum())
return;
_motor[id].requestRegister(reg);
}
long L6470Stepper::getCurrStep(int motor_id)
{
long step = readRegister(REG_ABS_POS, motor_id);
return step;
}
float L6470Stepper::getCurrAngle(int motor_id)
{
long step = getCurrStep();
return stepToAngle(step);
}
void L6470Stepper::execute()
{
bool needToSetReg = false;
bool needToSetCmd = false;
// check if spi action is needed
for (int i=0; i<getDaisyChainNum(); i++) {
needToSetReg |= _motor[i].isRegChanged();
needToSetCmd |= _motor[i].isCmdChanged();
}
if (needToSetReg) {
transferRegister();
}
if (needToSetCmd) {
transferAction();
}
}
void L6470Stepper::transferAction()
{
_spiData->updateAsAppCmd(_motor);
transferDaisyChain(_spiData->getCmd());
for (int i=SPI_VAL_MAXSIZE-_spiData->getSize(); i<SPI_VAL_MAXSIZE; i++) {
transferDaisyChain(_spiData->getVal(i));
}
}
void L6470Stepper::transferRegister()
{
// send data order / 0: MSB n: LSB
// read data order / 0: LSB n: MSB
_readUnion readUnion[getDaisyChainNum()];
_spiData->updateAsRegCmd(_motor);
for (size_t i = 0; i < getDaisyChainNum(); i++) {
for (size_t j = 0; j < 4; j++) {
readUnion[i].bval[j] = 0;
}
// readUnion[i].ival = 0;
}
// Serial.println("Send Command: ");
transferDaisyChain(_spiData->getCmd());
int startByte = SPI_VAL_MAXSIZE-_spiData->getSize();
for (int i=0; i<SPI_VAL_MAXSIZE; i++) {
if (i < startByte) {
for (size_t j = 0; j < getDaisyChainNum(); j++) {
readUnion[j].bval[SPI_VAL_MAXSIZE-1-i] = 0;
}
} else {
// Serial.println("Send Data and Read Register: ");
byte* readBytes;
readBytes = (byte*)transferDaisyChain(_spiData->getVal(i)); // get pointer, read data comes from MSB
for (int j=0; j<getDaisyChainNum(); j++) {
// Serial.println("Got Data: ");
readUnion[j].bval[SPI_VAL_MAXSIZE-1-i] = readBytes[j];
// Serial.println(readBytes[j], HEX);
// Serial.println(readUnion[j].bval[SPI_VAL_MAXSIZE-1-i], HEX);
}
}
}
// copy data to array
// Serial.println("final data: ");
for (int i=0; i<getDaisyChainNum(); i++) {
_readData[i] = readUnion[i].ival;
// for (size_t j = 0; j < 4; j++) {
// Serial.print(readUnion[i].bval[j], HEX); Serial.print(" ");
// }
// Serial.print("int: "); Serial.println(readUnion[i].ival, HEX);
// Serial.print("int: "); Serial.println(_readData[i], HEX);
}
}
void L6470Stepper::clearMotorActions()
{
for (int i=0; i<getDaisyChainNum(); i++) {
clearMotorAction(i);
}
}
void L6470Stepper::clearMotorAction(int id)
{
_motor[id].setAction(NOP);
_motor[id].setRegister(REG_NOP);
}
void L6470Stepper::resetDriver()
{
for (int i=0; i<getDaisyChainNum(); i++)
{
_motor[i].setAction(NOP);
}
transferAction();
for (int i=0; i<getDaisyChainNum(); i++)
{
_motor[i].setAction(RESETDEVICE);
}
transferAction();
}
void L6470Stepper::initRegister(registerStruct* regParamList, int size, int id)
{
for (int i=0; i<size; i++) {
for (int j=0; j<getDaisyChainNum(); j++) {
if (j == id) _motor[j].setRegister(regParamList[i].reg, regParamList[i].val);
else _motor[j].setRegister(REG_NOP, 0);
}
transferRegister();
}
}
// optional
void L6470Stepper::setBusyEnable(int pinBUSY)
{
_pinBUSY = pinBUSY;
useBusy = true;
}
void L6470Stepper::setStepEnable(int pinSTEP)
{
_pinSTEP = pinSTEP;
useStep = true;
}
boolean L6470Stepper::isBusy()
{
// todo: faster one
// todo: status register has the mirror
return !digitalRead(_pinBUSY); // BUSY: LOW, FREE: HIGH
}
L6480Stepper::L6480Stepper(int pinCS, int nDaisyChain, int* motorSteps)
:L6470Stepper(pinCS, nDaisyChain, motorSteps)
{
}
L6480Stepper::~L6480Stepper()
{
}
void L6480Stepper::setup(registerStruct* regParamList, int size, int id)
{
// set motor driver as L6480
if (regParamList == NULL) regParamList = (registerStruct*)L6480DefaultRegParamList;
_writableRegNum = WRITABLE_REG_NUM_L6480;
for (int i=0; i<getDaisyChainNum(); i++) {
_motor[i].setup(L6480_REGISTER);
}
// initialize register
if (id < 0) {
for (int i=0; i<getDaisyChainNum(); i++) {
initRegister(regParamList, _writableRegNum, i);
}
} else {
if (size == 0) size = _writableRegNum;
initRegister(regParamList, size, id);
}
}
<commit_msg>fix step-mode<commit_after>#include "L6470Stepper.h"
L6470Stepper::L6470Stepper(int pinCS, int nDaisyChain, int* motorSteps)
: SPIDaisyChain(pinCS, nDaisyChain)
{
_spiData = new L6470SpiData(nDaisyChain);
_motor = new L6470MotorData[nDaisyChain];
_readData = new uint32_t[nDaisyChain];
for (size_t i = 0; i < nDaisyChain; i++) {
_readData[i] = 0;
}
// pin settings
_pinBUSY = 0xFF; // NOT USE, default
_pinSTEP = 0xFF; // NOT USE, default
useBusy = false;
useStep = false;
for (int i=0; i<nDaisyChain; i++) {
if (motorSteps == NULL) _motor[i].setMotorStep(DEFAULT_MOTOR_STEP);
else _motor[i].setMotorStep(motorSteps[i]);
}
resetDriver();
}
L6470Stepper::~L6470Stepper()
{
delete[] _motor;
delete[] _spiData;
delete[] _readData;
}
void L6470Stepper::setup(registerStruct* regParamList, int size, int id)
{
// set motor driver as L6480
if (regParamList == NULL) regParamList = (registerStruct*)L6470DefaultRegParamList;
_writableRegNum = WRITABLE_REG_NUM_L6470;
for (int i=0; i<getDaisyChainNum(); i++) {
_motor[i].setup(L6470_REGISTER);
}
// initialize register
if (id < 0) {
for (int i=0; i<getDaisyChainNum(); i++) {
initRegister(regParamList, _writableRegNum, i);
}
} else {
if (size == 0) size = _writableRegNum;
initRegister(regParamList, size, id);
}
}
void L6470Stepper::angle(int degree)
{
for (int i=0; i<getDaisyChainNum(); i++) {
setAngle(degree, i);
}
transferAction();
}
void L6470Stepper::setAngle(int degree, int id)
{
if(id >= getDaisyChainNum())
return;
static int pre_degree = 0;
_motor[id].setAction(GOTO_DIR, degree, ((degree >= pre_degree) ? 1 : 0));
pre_degree = degree;
}
void L6470Stepper::step(int steps)
{
for (int i=0; i<getDaisyChainNum(); i++) {
setStep(steps, i);
}
transferAction();
}
void L6470Stepper::setStep(int steps, int id)
{
if(id >= getDaisyChainNum())
return;
if (steps < 0) {
_motor[id].setAction(MOVE, abs(steps), CCW);
} else {
_motor[id].setAction(MOVE, abs(steps), CW);
}
}
void L6470Stepper::rotate(motorDirection dir, int rps)
{
for (int i=0; i<getDaisyChainNum(); i++) {
setRotate(dir, i, rps);
}
transferAction();
}
void L6470Stepper::setRotate(motorDirection dir, int id, int rps)
{
if(id >= getDaisyChainNum())
return;
if (rps == 0) {
rps = _motor[id].getCurRps();
}
_motor[id].setAction(RUN, abs(rps), dir);
}
void L6470Stepper::setStepClockMode(_motorDirection dir, int id)
{
if(id >= getDaisyChainNum())
return;
_motor[id].setAction(STEPCLOCK, 0, dir);
transferAction();
}
long L6470Stepper::angleToStep(float angle, int motor_id)
{
long steps = (uint32_t)((double)_motor[motor_id].getMotorStep() * (double)pow(2, _motor[motor_id].getMicroStep()) * (double)angle / 360.0);
return steps;
}
float L6470Stepper::stepToAngle(long step, int motor_id)
{
unsigned long all_steps = (unsigned long)((double)_motor[motor_id].getMotorStep() * (double)pow(2, _motor[motor_id].getMicroStep()));
float angle = 360. * step / all_steps;
return angle;
}
void L6470Stepper::stepClock(float abs_angle, float ms, int motor_id)
{
long curr_step = getCurrStep();
long diff_step = angleToStep(abs_angle) - curr_step;
_motorDirection dir = (diff_step < 0) ? CCW : CW;
stepClock(abs(diff_step), dir, ms, motor_id);
}
void L6470Stepper::stepClock(long step, _motorDirection dir, float ms, int motor_id)
{
setStepClockMode(dir, motor_id);
unsigned int hz = 0;
if (ms <= 0) {
hz = 0xFFFF; // numeric_limits<int>::max() 16bit
tone(_pinSTEP, hz);
} else {
hz = (unsigned int)getHzFrom(step, ms);
if (hz > 65535) {
Serial.print("Too High Frequency !! : "); Serial.println(hz);
hz = 65535;
} else if (hz < 31) {
Serial.print("Too Low Frequency !! : "); Serial.println(hz);
hz = 31;
}
// Serial.print("frequency is : "); Serial.println(hz);
tone(_pinSTEP, hz, ms);
}
}
long L6470Stepper::getHzFrom(long steps, float ms)
{
if (ms <= 0) {
return 0;
}
return (long)(1. / ((double)ms / 1000. / (double)steps));
}
void L6470Stepper::setRps(int rps)
{
for (int i=0; i<getDaisyChainNum(); i++) {
setRps(rps, i);
}
transferRegister();
}
void L6470Stepper::setRps(int rps, int id)
{
if(id >= getDaisyChainNum())
return;
_motor[id].setRegister(REG_MAX_SPEED, rps);
}
long L6470Stepper::readRegister(int reg, int motor_id)
{
for (int i=0; i<getDaisyChainNum(); i++) {
requestRegister(reg, i);
}
transferRegister();
long ret = 0;
if (reg == REG_ABS_POS) {
long sign = ((_readData[motor_id] & 0x200000) >> 21);
long val = (_readData[motor_id] & 0x1FFFFF);
if (sign == 0) {
ret = (long)val;
} else {
ret = (long)(-1) * (long)(0x200000 - val);
}
// Serial.print("sign : "); Serial.println(sign, HEX);
// Serial.print("value: "); Serial.println(val, HEX);
} else {
ret = (long)_readData[motor_id];
}
return ret;
}
void L6470Stepper::requestRegister(int reg, int id)
{
if(id >= getDaisyChainNum())
return;
_motor[id].requestRegister(reg);
}
long L6470Stepper::getCurrStep(int motor_id)
{
long step = readRegister(REG_ABS_POS, motor_id);
return step;
}
float L6470Stepper::getCurrAngle(int motor_id)
{
long step = getCurrStep();
return stepToAngle(step);
}
void L6470Stepper::execute()
{
bool needToSetReg = false;
bool needToSetCmd = false;
// check if spi action is needed
for (int i=0; i<getDaisyChainNum(); i++) {
needToSetReg |= _motor[i].isRegChanged();
needToSetCmd |= _motor[i].isCmdChanged();
}
if (needToSetReg) {
transferRegister();
}
if (needToSetCmd) {
transferAction();
}
}
void L6470Stepper::transferAction()
{
_spiData->updateAsAppCmd(_motor);
transferDaisyChain(_spiData->getCmd());
for (int i=SPI_VAL_MAXSIZE-_spiData->getSize(); i<SPI_VAL_MAXSIZE; i++) {
transferDaisyChain(_spiData->getVal(i));
}
}
void L6470Stepper::transferRegister()
{
// send data order / 0: MSB n: LSB
// read data order / 0: LSB n: MSB
_readUnion readUnion[getDaisyChainNum()];
_spiData->updateAsRegCmd(_motor);
for (size_t i = 0; i < getDaisyChainNum(); i++) {
for (size_t j = 0; j < 4; j++) {
readUnion[i].bval[j] = 0;
}
// readUnion[i].ival = 0;
}
// Serial.println("Send Command: ");
transferDaisyChain(_spiData->getCmd());
int startByte = SPI_VAL_MAXSIZE-_spiData->getSize();
for (int i=0; i<SPI_VAL_MAXSIZE; i++) {
if (i < startByte) {
for (size_t j = 0; j < getDaisyChainNum(); j++) {
readUnion[j].bval[SPI_VAL_MAXSIZE-1-i] = 0;
}
} else {
// Serial.println("Send Data and Read Register: ");
byte* readBytes;
readBytes = (byte*)transferDaisyChain(_spiData->getVal(i)); // get pointer, read data comes from MSB
for (int j=0; j<getDaisyChainNum(); j++) {
// Serial.println("Got Data: ");
readUnion[j].bval[SPI_VAL_MAXSIZE-1-i] = readBytes[j];
// Serial.println(readBytes[j], HEX);
// Serial.println(readUnion[j].bval[SPI_VAL_MAXSIZE-1-i], HEX);
}
}
}
// copy data to array
// Serial.println("final data: ");
for (int i=0; i<getDaisyChainNum(); i++) {
_readData[i] = readUnion[i].ival;
// for (size_t j = 0; j < 4; j++) {
// Serial.print(readUnion[i].bval[j], HEX); Serial.print(" ");
// }
// Serial.print("int: "); Serial.println(readUnion[i].ival, HEX);
// Serial.print("int: "); Serial.println(_readData[i], HEX);
}
}
void L6470Stepper::clearMotorActions()
{
for (int i=0; i<getDaisyChainNum(); i++) {
clearMotorAction(i);
}
}
void L6470Stepper::clearMotorAction(int id)
{
_motor[id].setAction(NOP);
_motor[id].setRegister(REG_NOP);
}
void L6470Stepper::resetDriver()
{
for (int i=0; i<getDaisyChainNum(); i++)
{
_motor[i].setAction(NOP);
}
transferAction();
for (int i=0; i<getDaisyChainNum(); i++)
{
_motor[i].setAction(RESETDEVICE);
}
transferAction();
}
void L6470Stepper::initRegister(registerStruct* regParamList, int size, int id)
{
for (int i=0; i<size; i++) {
for (int j=0; j<getDaisyChainNum(); j++) {
if (j == id) _motor[j].setRegister(regParamList[i].reg, regParamList[i].val);
else _motor[j].setRegister(REG_NOP, 0);
}
transferRegister();
}
}
// optional
void L6470Stepper::setBusyEnable(int pinBUSY)
{
_pinBUSY = pinBUSY;
useBusy = true;
}
void L6470Stepper::setStepEnable(int pinSTEP)
{
_pinSTEP = pinSTEP;
useStep = true;
}
boolean L6470Stepper::isBusy()
{
// todo: faster one
// todo: status register has the mirror
return !digitalRead(_pinBUSY); // BUSY: LOW, FREE: HIGH
}
L6480Stepper::L6480Stepper(int pinCS, int nDaisyChain, int* motorSteps)
:L6470Stepper(pinCS, nDaisyChain, motorSteps)
{
}
L6480Stepper::~L6480Stepper()
{
}
void L6480Stepper::setup(registerStruct* regParamList, int size, int id)
{
// set motor driver as L6480
if (regParamList == NULL) regParamList = (registerStruct*)L6480DefaultRegParamList;
_writableRegNum = WRITABLE_REG_NUM_L6480;
for (int i=0; i<getDaisyChainNum(); i++) {
_motor[i].setup(L6480_REGISTER);
}
// initialize register
if (id < 0) {
for (int i=0; i<getDaisyChainNum(); i++) {
initRegister(regParamList, _writableRegNum, i);
}
} else {
if (size == 0) size = _writableRegNum;
initRegister(regParamList, size, id);
}
}
<|endoftext|>
|
<commit_before>#include <ros/ros.h>
//ROS libraries
#include <tf/transform_datatypes.h>
//ROS messages
#include <std_msgs/Float32.h>
#include <std_msgs/String.h>
#include <geometry_msgs/Quaternion.h>
#include <geometry_msgs/QuaternionStamped.h>
#include <geometry_msgs/Twist.h>
#include <nav_msgs/Odometry.h>
#include <sensor_msgs/Imu.h>
#include <sensor_msgs/Range.h>
//Package include
#include <usbSerial.h>
using namespace std;
//aBridge functions
void cmdHandler(const geometry_msgs::Twist::ConstPtr& message);
void fingerAngleHandler(const std_msgs::Float32::ConstPtr& angle);
void wristAngleHandler(const std_msgs::Float32::ConstPtr& angle);
void serialActivityTimer(const ros::TimerEvent& e);
void publishRosTopics();
void parseData(string data);
//Globals
geometry_msgs::QuaternionStamped fingerAngle;
geometry_msgs::QuaternionStamped wristAngle;
sensor_msgs::Imu imu;
nav_msgs::Odometry odom;
sensor_msgs::Range sonarLeft;
sensor_msgs::Range sonarCenter;
sensor_msgs::Range sonarRight;
USBSerial usb;
const int baud = 115200;
char dataCmd[] = "d\n";
char moveCmd[16];
char host[128];
char delimiter = ',';
vector<string> dataSet;
float linearSpeed = 0.;
float turnSpeed = 0.;
const float deltaTime = 0.1;
//Publishers
ros::Publisher fingerAnglePublish;
ros::Publisher wristAnglePublish;
ros::Publisher imuPublish;
ros::Publisher odomPublish;
ros::Publisher sonarLeftPublish;
ros::Publisher sonarCenterPublish;
ros::Publisher sonarRightPublish;
//Subscribers
ros::Subscriber velocitySubscriber;
ros::Subscriber fingerAngleSubscriber;
ros::Subscriber wristAngleSubscriber;
//Timers
ros::Timer publishTimer;
int main(int argc, char **argv) {
gethostname(host, sizeof (host));
string hostname(host);
string publishedName;
ros::init(argc, argv, (hostname + "_ABRIDGE"));
ros::NodeHandle param("~");
string devicePath;
param.param("device", devicePath, string("/dev/ttyUSB0"));
usb.openUSBPort(devicePath, baud);
sleep(5);
ros::NodeHandle aNH;
if (argc >= 2) {
publishedName = argv[1];
cout << "Welcome to the world of tomorrow " << publishedName << "! ABridge module started." << endl;
} else {
publishedName = hostname;
cout << "No Name Selected. Default is: " << publishedName << endl;
}
fingerAnglePublish = aNH.advertise<geometry_msgs::QuaternionStamped>((publishedName + "/fingerAngle/prev_cmd"), 10);
wristAnglePublish = aNH.advertise<geometry_msgs::QuaternionStamped>((publishedName + "/wristAngle/prev_cmd"), 10);
imuPublish = aNH.advertise<sensor_msgs::Imu>((publishedName + "/imu"), 10);
odomPublish = aNH.advertise<nav_msgs::Odometry>((publishedName + "/odom"), 10);
sonarLeftPublish = aNH.advertise<sensor_msgs::Range>((publishedName + "/sonarLeft"), 10);
sonarCenterPublish = aNH.advertise<sensor_msgs::Range>((publishedName + "/sonarCenter"), 10);
sonarRightPublish = aNH.advertise<sensor_msgs::Range>((publishedName + "/sonarRight"), 10);
velocitySubscriber = aNH.subscribe((publishedName + "/velocity"), 10, cmdHandler);
fingerAngleSubscriber = aNH.subscribe((publishedName + "/fingerAngle/cmd"), 1, fingerAngleHandler);
wristAngleSubscriber = aNH.subscribe((publishedName + "/wristAngle/cmd"), 1, wristAngleHandler);
publishTimer = aNH.createTimer(ros::Duration(deltaTime), serialActivityTimer);
imu.header.frame_id = publishedName+"/base_link";
odom.header.frame_id = publishedName+"/odom";
odom.child_frame_id = publishedName+"/base_link";
ros::spin();
return EXIT_SUCCESS;
}
void cmdHandler(const geometry_msgs::Twist::ConstPtr& message) {
// remove artificial factor that was multiplied for simulation. this scales it back down to -1.0 to +1.0
linearSpeed = (message->linear.x); // / 1.5;
turnSpeed = (message->angular.z); // / 8;
if (linearSpeed != 0.) {
sprintf(moveCmd, "m,%d\n", (int) (linearSpeed * 255));
usb.sendData(moveCmd);
} else if (turnSpeed != 0.) {
sprintf(moveCmd, "t,%d\n", (int) (turnSpeed * 255));
usb.sendData(moveCmd);
} else {
sprintf(moveCmd, "s\n");
usb.sendData(moveCmd);
}
memset(&moveCmd, '\0', sizeof (moveCmd));
}
// The finger and wrist handlers receive gripper angle commands in floating point
// radians, write them to a string and send that to the arduino
// for processing.
void fingerAngleHandler(const std_msgs::Float32::ConstPtr& angle) {
char cmd[16]={'\0'};
// Avoid dealing with negative exponents which confuse the conversion to string by checking if the angle is small
if (angle->data < 0.01) {
// 'f' indicates this is a finger command to the arduino
sprintf(cmd, "f,0\n");
} else {
sprintf(cmd, "f,%.4g\n", angle->data);
}
usb.sendData(cmd);
memset(&cmd, '\0', sizeof (cmd));
}
void wristAngleHandler(const std_msgs::Float32::ConstPtr& angle) {
char cmd[16]={'\0'};
// Avoid dealing with negative exponents which confuse the conversion to string by checking if the angle is small
if (angle->data < 0.01) {
// 'w' indicates this is a wrist command to the arduino
sprintf(cmd, "w,0\n");
} else {
sprintf(cmd, "w,%.4g\n", angle->data);
}
usb.sendData(cmd);
memset(&cmd, '\0', sizeof (cmd));
}
void serialActivityTimer(const ros::TimerEvent& e) {
usb.sendData(dataCmd);
parseData(usb.readData());
publishRosTopics();
}
void publishRosTopics() {
fingerAnglePublish.publish(fingerAngle);
wristAnglePublish.publish(wristAngle);
imuPublish.publish(imu);
odomPublish.publish(odom);
sonarLeftPublish.publish(sonarLeft);
sonarCenterPublish.publish(sonarCenter);
sonarRightPublish.publish(sonarRight);
}
void parseData(string str) {
istringstream oss(str);
string word;
while (getline(oss, word, delimiter)) {
dataSet.push_back(word);
}
if (dataSet.size() == 18) {
imu.header.stamp = ros::Time::now();
imu.linear_acceleration.x = atof(dataSet.at(0).c_str());
imu.linear_acceleration.y = atof(dataSet.at(1).c_str());
imu.linear_acceleration.z = atof(dataSet.at(2).c_str());
imu.angular_velocity.x = atof(dataSet.at(3).c_str());
imu.angular_velocity.y = atof(dataSet.at(4).c_str());
imu.angular_velocity.z = atof(dataSet.at(5).c_str());
imu.orientation = tf::createQuaternionMsgFromRollPitchYaw(atof(dataSet.at(6).c_str()), atof(dataSet.at(7).c_str()), atof(dataSet.at(8).c_str()));
odom.header.stamp = ros::Time::now();
odom.pose.pose.position.x += atof(dataSet.at(9).c_str()) / 100.0;
odom.pose.pose.position.y += atof(dataSet.at(10).c_str()) / 100.0;
odom.pose.pose.position.z = 0.0;
odom.pose.pose.orientation = tf::createQuaternionMsgFromYaw(atof(dataSet.at(11).c_str()));
odom.twist.twist.linear.x = atof(dataSet.at(12).c_str()) / 100.0;
odom.twist.twist.linear.y = atof(dataSet.at(13).c_str()) / 100.0;
odom.twist.twist.angular.z = atof(dataSet.at(14).c_str());
sonarLeft.range = atof(dataSet.at(15).c_str()) / 100.0;
sonarCenter.range = atof(dataSet.at(16).c_str()) / 100.0;
sonarRight.range = atof(dataSet.at(17).c_str()) / 100.0;
}
dataSet.clear();
}
<commit_msg>Enhance abridge's parsing function to handle multiple delimited newlines<commit_after>#include <ros/ros.h>
//ROS libraries
#include <tf/transform_datatypes.h>
//ROS messages
#include <std_msgs/Float32.h>
#include <std_msgs/String.h>
#include <geometry_msgs/Quaternion.h>
#include <geometry_msgs/QuaternionStamped.h>
#include <geometry_msgs/Twist.h>
#include <nav_msgs/Odometry.h>
#include <sensor_msgs/Imu.h>
#include <sensor_msgs/Range.h>
//Package include
#include <usbSerial.h>
using namespace std;
//aBridge functions
void cmdHandler(const geometry_msgs::Twist::ConstPtr& message);
void fingerAngleHandler(const std_msgs::Float32::ConstPtr& angle);
void wristAngleHandler(const std_msgs::Float32::ConstPtr& angle);
void serialActivityTimer(const ros::TimerEvent& e);
void publishRosTopics();
void parseData(string data);
//Globals
geometry_msgs::QuaternionStamped fingerAngle;
geometry_msgs::QuaternionStamped wristAngle;
sensor_msgs::Imu imu;
nav_msgs::Odometry odom;
sensor_msgs::Range sonarLeft;
sensor_msgs::Range sonarCenter;
sensor_msgs::Range sonarRight;
USBSerial usb;
const int baud = 115200;
char dataCmd[] = "d\n";
char moveCmd[16];
char host[128];
char delimiter = ',';
vector<string> dataSet;
float linearSpeed = 0.;
float turnSpeed = 0.;
const float deltaTime = 0.1;
//Publishers
ros::Publisher fingerAnglePublish;
ros::Publisher wristAnglePublish;
ros::Publisher imuPublish;
ros::Publisher odomPublish;
ros::Publisher sonarLeftPublish;
ros::Publisher sonarCenterPublish;
ros::Publisher sonarRightPublish;
//Subscribers
ros::Subscriber velocitySubscriber;
ros::Subscriber fingerAngleSubscriber;
ros::Subscriber wristAngleSubscriber;
//Timers
ros::Timer publishTimer;
int main(int argc, char **argv) {
gethostname(host, sizeof (host));
string hostname(host);
string publishedName;
ros::init(argc, argv, (hostname + "_ABRIDGE"));
ros::NodeHandle param("~");
string devicePath;
param.param("device", devicePath, string("/dev/ttyUSB0"));
usb.openUSBPort(devicePath, baud);
sleep(5);
ros::NodeHandle aNH;
if (argc >= 2) {
publishedName = argv[1];
cout << "Welcome to the world of tomorrow " << publishedName << "! ABridge module started." << endl;
} else {
publishedName = hostname;
cout << "No Name Selected. Default is: " << publishedName << endl;
}
fingerAnglePublish = aNH.advertise<geometry_msgs::QuaternionStamped>((publishedName + "/fingerAngle/prev_cmd"), 10);
wristAnglePublish = aNH.advertise<geometry_msgs::QuaternionStamped>((publishedName + "/wristAngle/prev_cmd"), 10);
imuPublish = aNH.advertise<sensor_msgs::Imu>((publishedName + "/imu"), 10);
odomPublish = aNH.advertise<nav_msgs::Odometry>((publishedName + "/odom"), 10);
sonarLeftPublish = aNH.advertise<sensor_msgs::Range>((publishedName + "/sonarLeft"), 10);
sonarCenterPublish = aNH.advertise<sensor_msgs::Range>((publishedName + "/sonarCenter"), 10);
sonarRightPublish = aNH.advertise<sensor_msgs::Range>((publishedName + "/sonarRight"), 10);
velocitySubscriber = aNH.subscribe((publishedName + "/velocity"), 10, cmdHandler);
fingerAngleSubscriber = aNH.subscribe((publishedName + "/fingerAngle/cmd"), 1, fingerAngleHandler);
wristAngleSubscriber = aNH.subscribe((publishedName + "/wristAngle/cmd"), 1, wristAngleHandler);
publishTimer = aNH.createTimer(ros::Duration(deltaTime), serialActivityTimer);
imu.header.frame_id = publishedName+"/base_link";
odom.header.frame_id = publishedName+"/odom";
odom.child_frame_id = publishedName+"/base_link";
ros::spin();
return EXIT_SUCCESS;
}
void cmdHandler(const geometry_msgs::Twist::ConstPtr& message) {
// remove artificial factor that was multiplied for simulation. this scales it back down to -1.0 to +1.0
linearSpeed = (message->linear.x); // / 1.5;
turnSpeed = (message->angular.z); // / 8;
if (linearSpeed != 0.) {
sprintf(moveCmd, "m,%d\n", (int) (linearSpeed * 255));
usb.sendData(moveCmd);
} else if (turnSpeed != 0.) {
sprintf(moveCmd, "t,%d\n", (int) (turnSpeed * 255));
usb.sendData(moveCmd);
} else {
sprintf(moveCmd, "s\n");
usb.sendData(moveCmd);
}
memset(&moveCmd, '\0', sizeof (moveCmd));
}
// The finger and wrist handlers receive gripper angle commands in floating point
// radians, write them to a string and send that to the arduino
// for processing.
void fingerAngleHandler(const std_msgs::Float32::ConstPtr& angle) {
char cmd[16]={'\0'};
// Avoid dealing with negative exponents which confuse the conversion to string by checking if the angle is small
if (angle->data < 0.01) {
// 'f' indicates this is a finger command to the arduino
sprintf(cmd, "f,0\n");
} else {
sprintf(cmd, "f,%.4g\n", angle->data);
}
usb.sendData(cmd);
memset(&cmd, '\0', sizeof (cmd));
}
void wristAngleHandler(const std_msgs::Float32::ConstPtr& angle) {
char cmd[16]={'\0'};
// Avoid dealing with negative exponents which confuse the conversion to string by checking if the angle is small
if (angle->data < 0.01) {
// 'w' indicates this is a wrist command to the arduino
sprintf(cmd, "w,0\n");
} else {
sprintf(cmd, "w,%.4g\n", angle->data);
}
usb.sendData(cmd);
memset(&cmd, '\0', sizeof (cmd));
}
void serialActivityTimer(const ros::TimerEvent& e) {
usb.sendData(dataCmd);
parseData(usb.readData());
publishRosTopics();
}
void publishRosTopics() {
fingerAnglePublish.publish(fingerAngle);
wristAnglePublish.publish(wristAngle);
imuPublish.publish(imu);
odomPublish.publish(odom);
sonarLeftPublish.publish(sonarLeft);
sonarCenterPublish.publish(sonarCenter);
sonarRightPublish.publish(sonarRight);
}
void parseData(string str) {
istringstream oss(str);
string sentence;
while (getline(oss, sentence, '\n')) {
istringstream wss(sentence);
string word;
vector<string> dataSet;
while (getline(wss, word, ',')) {
dataSet.push_back(word);
}
if (dataSet.size() >= 3 && dataSet.at(1) == "1") {
if (dataSet.at(0) == "GRF") {
fingerAngle.header.stamp = ros::Time::now();
fingerAngle.quaternion = tf::createQuaternionMsgFromRollPitchYaw(atof(dataSet.at(2).c_str()), 0.0, 0.0);
}
else if (dataSet.at(0) == "GRW") {
wristAngle.header.stamp = ros::Time::now();
wristAngle.quaternion = tf::createQuaternionMsgFromRollPitchYaw(atof(dataSet.at(2).c_str()), 0.0, 0.0);
}
else if (dataSet.at(0) == "IMU") {
imu.header.stamp = ros::Time::now();
imu.linear_acceleration.x = atof(dataSet.at(2).c_str());
imu.linear_acceleration.y = atof(dataSet.at(3).c_str());
imu.linear_acceleration.z = atof(dataSet.at(4).c_str());
imu.angular_velocity.x = atof(dataSet.at(5).c_str());
imu.angular_velocity.y = atof(dataSet.at(6).c_str());
imu.angular_velocity.z = atof(dataSet.at(7).c_str());
imu.orientation = tf::createQuaternionMsgFromRollPitchYaw(atof(dataSet.at(8).c_str()), atof(dataSet.at(9).c_str()), atof(dataSet.at(10).c_str()));
}
else if (dataSet.at(0) == "ODOM") {
odom.header.stamp = ros::Time::now();
odom.pose.pose.position.x += atof(dataSet.at(2).c_str()) / 100.0;
odom.pose.pose.position.y += atof(dataSet.at(3).c_str()) / 100.0;
odom.pose.pose.position.z = 0.0;
odom.pose.pose.orientation = tf::createQuaternionMsgFromYaw(atof(dataSet.at(4).c_str()));
odom.twist.twist.linear.x = atof(dataSet.at(5).c_str()) / 100.0;
odom.twist.twist.linear.y = atof(dataSet.at(6).c_str()) / 100.0;
odom.twist.twist.angular.z = atof(dataSet.at(7).c_str());
}
else if (dataSet.at(0) == "USL") {
sonarLeft.header.stamp = ros::Time::now();
sonarLeft.range = atof(dataSet.at(2).c_str()) / 100.0;
}
else if (dataSet.at(0) == "USC") {
sonarCenter.header.stamp = ros::Time::now();
sonarCenter.range = atof(dataSet.at(2).c_str()) / 100.0;
}
else if (dataSet.at(0) == "USR") {
sonarRight.header.stamp = ros::Time::now();
sonarRight.range = atof(dataSet.at(2).c_str()) / 100.0;
}
}
}
}
<|endoftext|>
|
<commit_before>class Solution {
public:
vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
std::unordered_map<int, int> m1, m2;
for (const auto &num : nums1) {
auto iter = m1.find(num);
if (iter == m1.end()) {
m1.emplace(num, 1);
} else {
++iter->second;
}
}
for (const auto &num : nums2) {
auto iter = m2.find(num);
if (iter == m2.end()) {
m2.emplace(num, 1);
} else {
++iter->second;
}
}
std::vector<int> ret;
for (auto iter = m1.begin(); iter != m1.end(); ++iter) {
auto iter2 = m2.find(iter->first);
if (iter2 == m2.end())
continue;
int temp = 0;
temp = std::min(iter->second, iter2->second);
while (temp > 0) {
ret.emplace_back(iter->first);
--temp;
}
}
return ret;
}
};
<commit_msg>Intersection of Two Arrays II<commit_after>class Solution {
public:
vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
std::unordered_map<int, int> m1, m2;
for (const auto &num : nums1) {
auto iter = m1.find(num);
if (iter == m1.end()) {
m1.emplace(num, 1);
} else {
++iter->second;
}
}
for (const auto &num : nums2) {
auto iter = m2.find(num);
if (iter == m2.end()) {
m2.emplace(num, 1);
} else {
++iter->second;
}
}
std::vector<int> ret;
for (auto iter = m1.begin(); iter != m1.end(); ++iter) {
auto iter2 = m2.find(iter->first);
if (iter2 == m2.end())
continue;
int temp = 0;
temp = std::min(iter->second, iter2->second);
while (temp > 0) {
ret.emplace_back(iter->first);
--temp;
}
}
return ret;
}
};
class Solution {
public:
vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
std::unordered_map<int, int> m1, m2;
for (const auto& num : nums1) {
m1[num] += 1;
}
for (const auto& num : nums2) {
m2[num] += 1;
}
std::vector<int> ret;
for (const auto& [key, value] : m1) {
if (m2[key] > 0) {
int count = std::min(value, m2[key]);
while (count > 0) {
ret.emplace_back(std::move(key));
--count;
}
}
}
return ret;
}
};
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2019 Anon authors, see AUTHORS file.
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 <epc.h>
#include <netdb.h>
#include "dns_lookup.h"
endpoint_cluster::endpoint_cluster(const char *host, int port,
bool do_tls,
const tls_context *tls_ctx,
int max_conn_per_ep,
int lookup_frequency_in_seconds)
: host_(host),
port_(port),
do_tls_(do_tls),
tls_ctx_(tls_ctx),
max_conn_per_ep_(max_conn_per_ep),
lookup_frequency_in_seconds_(lookup_frequency_in_seconds),
last_lookup_time_((struct timespec){}),
round_robin_index_(0),
looking_up_endpoints_(false),
max_io_block_time_(k_default_io_block_time),
retries_enabled_(true)
{
}
void endpoint_cluster::update_endpoints()
{
auto addrs = dns_lookup::get_addrinfo(host_.c_str(), port_);
fiber_lock l(mtx_);
if (addrs.first != 0 || addrs.second.size() == 0)
{
// if there are no current endpoints that are already known
// for this host name, then this error object will be thrown
// in the fiber has initiated this call to update_endpoints.
// In that case, the fact that it is an instance of fiber_io_error
// will cause the exponential backoff logic to kick in and
// re-attempt the operation - optimistically hoping that whatever
// is causing the error will resolve itself
lookup_err_ = std::unique_ptr<fiber_io_error>(new fiber_io_error(Log::fmt(
[&](std::ostream &msg) { msg << "dns lookup failed for: " << host_ << ", error: " << (addrs.first < 0 ? gai_strerror(addrs.first) : error_string(addrs.first)); })));
}
else
{
// build a map which is the union of all currently
// known endpoints plus the ones that were just
// returned in the call to get_adddrinfo.
auto now = cur_time();
std::map<sockaddr_in6, std::shared_ptr<endpoint>> endpoints;
for (auto &ep : endpoints_)
endpoints.insert(std::make_pair(ep->addr_, ep));
for (auto &addr : addrs.second)
{
auto it = endpoints.find(addr);
if (it == endpoints.end())
endpoints.insert(std::make_pair(addr, std::make_shared<endpoint>(addr)));
else
it->second->last_lookup_time_ = now;
}
// we use a simple policy rule that we are willing to
// keep attempting to use any ip address that was returned
// by getaddrinfo up to 10 times whatever the
// dns lookup_frequency_in_seconds_ is. If any cached
// open sockets become unusable they will be deleted.
// If new connection attempts fail to one of these
// "slighly old" endpoints we will delete that endpoint
// from our list.
auto oldest = now - lookup_frequency_in_seconds_ * 10;
for (auto it = endpoints.begin(); it != endpoints.end();)
{
if (it->second->last_lookup_time_ < oldest)
{
#ifdef ANON_LOG_DNS_LOOKUP
anon_log("aging out endpoint " << it->second->addr_ << ", because it was " << to_seconds(now - it->second->last_lookup_time_) << " seconds old");
#endif
it = endpoints.erase(it);
}
else
++it;
}
endpoints_.resize(endpoints.size());
int indx = 0;
#ifdef ANON_LOG_DNS_LOOKUP
anon_log("host: " << host_);
#endif
for (auto &p : endpoints)
{
#ifdef ANON_LOG_DNS_LOOKUP
auto age = to_seconds(now - p.second->last_lookup_time_);
if (age < 0.0)
age = 0.0;
anon_log(" using " << p.second->addr_ << ", lookup age: " << age << " seconds");
#endif
endpoints_[indx++] = p.second;
}
}
last_lookup_time_ = cur_time();
looking_up_endpoints_ = false;
cond_.notify_all();
}
// This is called either by erase_if_empty ep has only one open
// socket (erase_if_empty is called if there is a problem with
// that socket) - or if we get a connection error trying to
// open a new socket for this endpoint. We delete the endpoint
// from our list to force dns to run again next time we try
// to get a functional pipe
void endpoint_cluster::erase(const std::shared_ptr<endpoint> &ep)
{
fiber_lock l(mtx_);
auto it = endpoints_.begin();
while (it != endpoints_.end())
{
if (*it == ep)
{
#ifdef ANON_LOG_DNS_LOOKUP
anon_log("endpoint_cluster::erase emptying");
#endif
endpoints_.erase(it);
return;
}
it++;
}
}
// This is called when there is some error that has occurred
// on a socket related to this endpoint. If it turns out that
// that socket was the only one in existence for this endpoint
// then remove the matching entry in the endpoints_ vector.
// This causes that endpoint to get deleted (when the other
// shared pointers to it are destructed) and means that the
// endpoint_cluster itself will not attempt to use this endpoint
// again without first going back through dns resolution.
// This cleans up cases where the ip address itself is no
// longer good and dns lookup is correctly no longer reporting
// that ip address. We have a policy of continuing to attempt
// to use that ip address for some period after dns lookup has
// returned it.
void endpoint_cluster::erase_if_empty(const std::shared_ptr<endpoint> &ep)
{
{
fiber_lock l(ep->mtx_);
if (ep->socks_.size() != 0 || ep->outstanding_requests_ != 1)
{
#ifdef ANON_LOG_DNS_LOOKUP
anon_log("endpoint_cluster::erase_if_empty, not emptying, ep->socks_.size(): " << ep->socks_.size() << ", ep->outstanding_requests_: " << ep->outstanding_requests_);
#endif
return;
}
}
erase(ep);
}
void endpoint_cluster::delete_cached_endpoints()
{
fiber_lock l(mtx_);
endpoints_.resize(0);
}
namespace
{
class cleanup
{
public:
cleanup(const std::weak_ptr<endpoint_cluster::endpoint> &wep,
const std::shared_ptr<endpoint_cluster::endpoint::sock> &sock,
const std::weak_ptr<endpoint_cluster>& wcp)
: wep(wep),
sock(sock),
cache(false),
exception_thrown(true)
#ifdef ANON_LOG_DNS_LOOKUP
,addr(wep.lock()->addr_)
#endif
{
}
~cleanup()
{
auto ep = wep.lock();
if (ep)
{
fiber_lock l(ep->mtx_);
--ep->outstanding_requests_;
if (exception_thrown) {
auto cp = wcp.lock();
if (cp)
cp->erase(ep);
}
if (cache)
{
sock->idle_start_time = cur_time();
ep->socks_.push(sock);
}
ep->error_ |= exception_thrown;
ep->cond_.notify_all();
}
else
{
#ifdef ANON_LOG_DNS_LOOKUP
anon_log("epc, appears that endpoint for " << addr << " was deleted prior to callback returning");
#endif
}
}
std::weak_ptr<endpoint_cluster::endpoint> wep;
std::shared_ptr<endpoint_cluster::endpoint::sock> sock;
std::weak_ptr<endpoint_cluster> wcp;
bool cache;
bool exception_thrown;
#ifdef ANON_LOG_DNS_LOOKUP
const struct sockaddr_in6 addr;
#endif
};
class eraser
{
public:
eraser(endpoint_cluster *epc,
const std::shared_ptr<endpoint_cluster::endpoint> &ep)
: epc(epc),
ep(ep),
success(false)
{
}
~eraser()
{
if (!success)
epc->erase(ep);
}
endpoint_cluster *epc;
std::shared_ptr<endpoint_cluster::endpoint> ep;
bool success;
};
} // namespace
void endpoint_cluster::do_with_connected_pipe(const std::function<bool(const pipe_t *pipe)> &f)
{
// if there are currently no available endpoints, or if it has been too long since we have
// last looked up endpoints, then restart the lookup process. If there are no endpoints
// then wait until the lookup is complete, otherwise continue to use the endpoints we
// already know about and let the lookup complete asynchronously. If there was an error
// attempting the lookup throw that error if there are no current endpoints, otherwise
// ignore the error
std::shared_ptr<endpoint> ep;
std::weak_ptr<endpoint> wep;
{
fiber_lock l(mtx_);
if (endpoints_.size() == 0 || to_seconds(cur_time() - last_lookup_time_) > lookup_frequency_in_seconds_)
{
if (!looking_up_endpoints_)
{
looking_up_endpoints_ = true;
lookup_err_.reset();
std::weak_ptr<endpoint_cluster> wp = shared_from_this();
auto stack_size = 16 * 1024;
fiber::run_in_fiber(
[wp] {
auto ths = wp.lock();
if (ths)
{
ths->update_endpoints();
}
},
stack_size, "epc, update_endpoints");
}
while (endpoints_.size() == 0)
{
cond_.wait(l);
if (lookup_err_)
throw *lookup_err_;
}
}
ep = endpoints_[round_robin_index_++ % endpoints_.size()];
wep = ep;
}
std::shared_ptr<endpoint::sock> sock;
{
fiber_lock l(ep->mtx_);
while (ep->outstanding_requests_ >= max_conn_per_ep_)
{
#ifdef ANON_LOG_DNS_LOOKUP
anon_log("waiting to use endpoint because it has " << ep->outstanding_requests_ << " current connections, maximum allowed: " << max_conn_per_ep_);
#endif
ep->cond_.wait(l);
}
if (ep->error_)
{
#ifdef ANON_LOG_DNS_LOOKUP
anon_log("endpoint for " << ep->addr_ << " had previous error (and has been removed from endpoint list) - trying again");
#endif
l.unlock();
ep.reset();
do_with_connected_pipe(f);
return;
}
++ep->outstanding_requests_;
while (!sock && ep->socks_.size() != 0)
{
auto s = ep->socks_.front();
ep->socks_.pop();
if (cur_time() < s->idle_start_time + k_max_idle_time)
sock = s;
#ifdef ANON_LOG_DNS_LOOKUP
else
anon_log("releasing socket (fd=" << s->pipe_->get_fd() << ") because it has been idle for " << cur_time() - s->idle_start_time << " seconds");
#endif
}
if (sock)
{
#ifdef ANON_LOG_DNS_LOOKUP
anon_log("epc reused connection (fd=" << sock->pipe_->get_fd() << ", idle_time=" << cur_time() - sock->idle_start_time << ") to " << ep->addr_);
#endif
}
else
{
l.unlock();
eraser era(this, ep);
auto conn = tcp_client::connect((struct sockaddr *)&ep->addr_, ep->addr_.sin6_family == AF_INET6 ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in));
era.success = true;
if (conn.first != 0)
{
erase(ep);
anon_throw(fiber_io_error, "tcp connect failed for " << ep->addr_ << ", error: " << error_string(conn.first));
}
conn.second->limit_io_block_time(max_io_block_time_);
std::unique_ptr<pipe_t> pipe;
if (do_tls_)
pipe = std::unique_ptr<pipe_t>(new tls_pipe(std::move(conn.second),
true, // client (not server)
true, // verify_peer
true, // doSNI
host_.c_str(),
*tls_ctx_));
else
pipe = std::unique_ptr<pipe_t>(conn.second.release());
sock = std::shared_ptr<endpoint::sock>(new endpoint::sock(std::move(pipe)));
#ifdef ANON_LOG_DNS_LOOKUP
anon_log("epc established new connection (fd=" << sock->pipe_->get_fd() << ") to " << ep->addr_);
#endif
}
}
// we let go of the endpoint itself and only hold
// the weak pointer to it across the call. This
// lets it timeout and get deleted more smoothly.
cleanup cu(wep, sock, shared_from_this());
ep.reset();
cu.cache = f(sock->pipe_.get());
cu.exception_thrown = false;
}
<commit_msg>logging tweak<commit_after>/*
Copyright (c) 2019 Anon authors, see AUTHORS file.
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 <epc.h>
#include <netdb.h>
#include "dns_lookup.h"
endpoint_cluster::endpoint_cluster(const char *host, int port,
bool do_tls,
const tls_context *tls_ctx,
int max_conn_per_ep,
int lookup_frequency_in_seconds)
: host_(host),
port_(port),
do_tls_(do_tls),
tls_ctx_(tls_ctx),
max_conn_per_ep_(max_conn_per_ep),
lookup_frequency_in_seconds_(lookup_frequency_in_seconds),
last_lookup_time_((struct timespec){}),
round_robin_index_(0),
looking_up_endpoints_(false),
max_io_block_time_(k_default_io_block_time),
retries_enabled_(true)
{
}
void endpoint_cluster::update_endpoints()
{
auto addrs = dns_lookup::get_addrinfo(host_.c_str(), port_);
fiber_lock l(mtx_);
if (addrs.first != 0 || addrs.second.size() == 0)
{
// if there are no current endpoints that are already known
// for this host name, then this error object will be thrown
// in the fiber has initiated this call to update_endpoints.
// In that case, the fact that it is an instance of fiber_io_error
// will cause the exponential backoff logic to kick in and
// re-attempt the operation - optimistically hoping that whatever
// is causing the error will resolve itself
lookup_err_ = std::unique_ptr<fiber_io_error>(new fiber_io_error(Log::fmt(
[&](std::ostream &msg) { msg << "dns lookup failed for: " << host_ << ", error: " << (addrs.first < 0 ? gai_strerror(addrs.first) : error_string(addrs.first)); })));
}
else
{
// build a map which is the union of all currently
// known endpoints plus the ones that were just
// returned in the call to get_adddrinfo.
auto now = cur_time();
std::map<sockaddr_in6, std::shared_ptr<endpoint>> endpoints;
for (auto &ep : endpoints_)
endpoints.insert(std::make_pair(ep->addr_, ep));
for (auto &addr : addrs.second)
{
auto it = endpoints.find(addr);
if (it == endpoints.end())
endpoints.insert(std::make_pair(addr, std::make_shared<endpoint>(addr)));
else
it->second->last_lookup_time_ = now;
}
// we use a simple policy rule that we are willing to
// keep attempting to use any ip address that was returned
// by getaddrinfo up to 10 times whatever the
// dns lookup_frequency_in_seconds_ is. If any cached
// open sockets become unusable they will be deleted.
// If new connection attempts fail to one of these
// "slighly old" endpoints we will delete that endpoint
// from our list.
auto oldest = now - lookup_frequency_in_seconds_ * 10;
for (auto it = endpoints.begin(); it != endpoints.end();)
{
if (it->second->last_lookup_time_ < oldest)
{
#ifdef ANON_LOG_DNS_LOOKUP
anon_log("aging out endpoint " << it->second->addr_ << ", because it was " << to_seconds(now - it->second->last_lookup_time_) << " seconds old");
#endif
it = endpoints.erase(it);
}
else
++it;
}
endpoints_.resize(endpoints.size());
int indx = 0;
#ifdef ANON_LOG_DNS_LOOKUP
anon_log("host: " << host_);
#endif
for (auto &p : endpoints)
{
#ifdef ANON_LOG_DNS_LOOKUP
auto age = to_seconds(now - p.second->last_lookup_time_);
if (age < 0.0)
age = 0.0;
anon_log(" using " << p.second->addr_ << ", lookup age: " << age << " seconds");
#endif
endpoints_[indx++] = p.second;
}
}
last_lookup_time_ = cur_time();
looking_up_endpoints_ = false;
cond_.notify_all();
}
// This is called either by erase_if_empty ep has only one open
// socket (erase_if_empty is called if there is a problem with
// that socket) - or if we get a connection error trying to
// open a new socket for this endpoint. We delete the endpoint
// from our list to force dns to run again next time we try
// to get a functional pipe
void endpoint_cluster::erase(const std::shared_ptr<endpoint> &ep)
{
fiber_lock l(mtx_);
auto it = endpoints_.begin();
while (it != endpoints_.end())
{
if (*it == ep)
{
#ifdef ANON_LOG_DNS_LOOKUP
anon_log("endpoint_cluster::erase emptying");
#endif
endpoints_.erase(it);
return;
}
it++;
}
}
// This is called when there is some error that has occurred
// on a socket related to this endpoint. If it turns out that
// that socket was the only one in existence for this endpoint
// then remove the matching entry in the endpoints_ vector.
// This causes that endpoint to get deleted (when the other
// shared pointers to it are destructed) and means that the
// endpoint_cluster itself will not attempt to use this endpoint
// again without first going back through dns resolution.
// This cleans up cases where the ip address itself is no
// longer good and dns lookup is correctly no longer reporting
// that ip address. We have a policy of continuing to attempt
// to use that ip address for some period after dns lookup has
// returned it.
void endpoint_cluster::erase_if_empty(const std::shared_ptr<endpoint> &ep)
{
{
fiber_lock l(ep->mtx_);
if (ep->socks_.size() != 0 || ep->outstanding_requests_ != 1)
{
#ifdef ANON_LOG_DNS_LOOKUP
anon_log("endpoint_cluster::erase_if_empty, not emptying, ep->socks_.size(): " << ep->socks_.size() << ", ep->outstanding_requests_: " << ep->outstanding_requests_);
#endif
return;
}
}
erase(ep);
}
void endpoint_cluster::delete_cached_endpoints()
{
fiber_lock l(mtx_);
endpoints_.resize(0);
}
namespace
{
class cleanup
{
public:
cleanup(const std::weak_ptr<endpoint_cluster::endpoint> &wep,
const std::shared_ptr<endpoint_cluster::endpoint::sock> &sock,
const std::weak_ptr<endpoint_cluster>& wcp)
: wep(wep),
sock(sock),
cache(false),
exception_thrown(true)
#ifdef ANON_LOG_DNS_LOOKUP
,addr(wep.lock()->addr_)
#endif
{
}
~cleanup()
{
auto ep = wep.lock();
if (ep)
{
fiber_lock l(ep->mtx_);
--ep->outstanding_requests_;
if (exception_thrown) {
auto cp = wcp.lock();
if (cp)
cp->erase(ep);
}
if (cache)
{
sock->idle_start_time = cur_time();
ep->socks_.push(sock);
}
ep->error_ |= exception_thrown;
ep->cond_.notify_all();
}
else
{
#ifdef ANON_LOG_DNS_LOOKUP
anon_log("epc, appears that endpoint for " << addr << " was deleted prior to callback returning");
#endif
}
}
std::weak_ptr<endpoint_cluster::endpoint> wep;
std::shared_ptr<endpoint_cluster::endpoint::sock> sock;
std::weak_ptr<endpoint_cluster> wcp;
bool cache;
bool exception_thrown;
#ifdef ANON_LOG_DNS_LOOKUP
const struct sockaddr_in6 addr;
#endif
};
class eraser
{
public:
eraser(endpoint_cluster *epc,
const std::shared_ptr<endpoint_cluster::endpoint> &ep)
: epc(epc),
ep(ep),
success(false)
{
}
~eraser()
{
if (!success)
epc->erase(ep);
}
endpoint_cluster *epc;
std::shared_ptr<endpoint_cluster::endpoint> ep;
bool success;
};
} // namespace
void endpoint_cluster::do_with_connected_pipe(const std::function<bool(const pipe_t *pipe)> &f)
{
// if there are currently no available endpoints, or if it has been too long since we have
// last looked up endpoints, then restart the lookup process. If there are no endpoints
// then wait until the lookup is complete, otherwise continue to use the endpoints we
// already know about and let the lookup complete asynchronously. If there was an error
// attempting the lookup throw that error if there are no current endpoints, otherwise
// ignore the error
std::shared_ptr<endpoint> ep;
std::weak_ptr<endpoint> wep;
{
fiber_lock l(mtx_);
if (endpoints_.size() == 0 || to_seconds(cur_time() - last_lookup_time_) > lookup_frequency_in_seconds_)
{
if (!looking_up_endpoints_)
{
looking_up_endpoints_ = true;
lookup_err_.reset();
std::weak_ptr<endpoint_cluster> wp = shared_from_this();
auto stack_size = 16 * 1024;
fiber::run_in_fiber(
[wp] {
auto ths = wp.lock();
if (ths)
{
ths->update_endpoints();
}
},
stack_size, "epc, update_endpoints");
}
while (endpoints_.size() == 0)
{
cond_.wait(l);
if (lookup_err_)
throw *lookup_err_;
}
}
ep = endpoints_[round_robin_index_++ % endpoints_.size()];
wep = ep;
}
std::shared_ptr<endpoint::sock> sock;
{
fiber_lock l(ep->mtx_);
while (ep->outstanding_requests_ >= max_conn_per_ep_)
{
#ifdef ANON_LOG_DNS_LOOKUP
anon_log("waiting to use endpoint because it has " << ep->outstanding_requests_ << " current connections, maximum allowed: " << max_conn_per_ep_);
#endif
ep->cond_.wait(l);
}
if (ep->error_)
{
#ifdef ANON_LOG_DNS_LOOKUP
anon_log("endpoint for " << ep->addr_ << " had previous error (and has been removed from endpoint list) - trying again");
#endif
l.unlock();
ep.reset();
do_with_connected_pipe(f);
return;
}
++ep->outstanding_requests_;
while (!sock && ep->socks_.size() != 0)
{
auto s = ep->socks_.front();
ep->socks_.pop();
if (cur_time() < s->idle_start_time + k_max_idle_time)
sock = s;
#ifdef ANON_LOG_DNS_LOOKUP
else
anon_log("releasing socket (fd=" << s->pipe_->get_fd() << ", from " << ep->addr_ << ") because it has been idle for " << cur_time() - s->idle_start_time << " seconds");
#endif
}
if (sock)
{
#ifdef ANON_LOG_DNS_LOOKUP
anon_log("epc reused connection (fd=" << sock->pipe_->get_fd() << ", idle_time=" << cur_time() - sock->idle_start_time << ") to " << ep->addr_);
#endif
}
else
{
l.unlock();
eraser era(this, ep);
auto conn = tcp_client::connect((struct sockaddr *)&ep->addr_, ep->addr_.sin6_family == AF_INET6 ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in));
era.success = true;
if (conn.first != 0)
{
erase(ep);
anon_throw(fiber_io_error, "tcp connect failed for " << ep->addr_ << ", error: " << error_string(conn.first));
}
conn.second->limit_io_block_time(max_io_block_time_);
std::unique_ptr<pipe_t> pipe;
if (do_tls_)
pipe = std::unique_ptr<pipe_t>(new tls_pipe(std::move(conn.second),
true, // client (not server)
true, // verify_peer
true, // doSNI
host_.c_str(),
*tls_ctx_));
else
pipe = std::unique_ptr<pipe_t>(conn.second.release());
sock = std::shared_ptr<endpoint::sock>(new endpoint::sock(std::move(pipe)));
#ifdef ANON_LOG_DNS_LOOKUP
anon_log("epc established new connection (fd=" << sock->pipe_->get_fd() << ") to " << ep->addr_);
#endif
}
}
// we let go of the endpoint itself and only hold
// the weak pointer to it across the call. This
// lets it timeout and get deleted more smoothly.
cleanup cu(wep, sock, shared_from_this());
ep.reset();
cu.cache = f(sock->pipe_.get());
cu.exception_thrown = false;
}
<|endoftext|>
|
<commit_before>/**
* @license
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
#include "egl_context_wrapper.h"
#include "utils.h"
#include <EGL/egl.h>
#include <EGL/eglext.h>
#include <GLES2/gl2.h>
#include <iostream>
#include <vector>
namespace nodejsgl {
#if DEBUG
void LogExtensions(const char* extensions_name, const char* extensions) {
std::string s(extensions);
std::string delim = " ";
size_t pos = 0;
std::string token;
std::cout << "---- " << extensions_name << "----" << std::endl;
while ((pos = s.find(delim)) != std::string::npos) {
token = s.substr(0, pos);
std::cout << token << std::endl;
s.erase(0, pos + delim.length());
}
std::cout << s;
std::cout << "-------------------------" << std::endl;
}
#endif
EGLContextWrapper::EGLContextWrapper(napi_env env) {
InitEGL(env);
BindProcAddresses();
BindExtensions();
#if DEBUG
// LogExtensions("GL_EXTENSIONS",
// reinterpret_cast<const char*>(glGetString(GL_EXTENSIONS)));
#endif
}
void EGLContextWrapper::InitEGL(napi_env env) {
// TODO(kreeger): Figure out how to make this work headless
display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
if (display == EGL_NO_DISPLAY) {
NAPI_THROW_ERROR(env, "No display");
return;
}
EGLint major;
EGLint minor;
if (!eglInitialize(display, &major, &minor)) {
NAPI_THROW_ERROR(env, "Could not initialize display");
return;
}
#if DEBUG
// TODO(kreeger): Clean this up.
// std::cerr << "major: " << major << std::endl;
// std::cerr << "minor: " << minor << std::endl;
#endif
extensions_wrapper = new EGLExtensionsWrapper(display);
EGLint attrib_list[] = {EGL_SURFACE_TYPE, EGL_PBUFFER_BIT,
EGL_RED_SIZE, 8,
EGL_GREEN_SIZE, 8,
EGL_BLUE_SIZE, 8,
EGL_ALPHA_SIZE, 8,
EGL_DEPTH_SIZE, 24,
EGL_STENCIL_SIZE, 8,
EGL_NONE};
EGLint num_config;
if (!eglChooseConfig(display, attrib_list, &config, 1, &num_config)) {
NAPI_THROW_ERROR(env, "Failed creating a config");
return;
}
eglBindAPI(EGL_OPENGL_ES_API);
if (eglGetError() != EGL_SUCCESS) {
NAPI_THROW_ERROR(env, "Failed to set OpenGL ES API");
return;
}
#if DEBUG
// LogExtensions("EGL_EXTENSIONS", eglQueryString(display, EGL_EXTENSIONS));
#endif
// Append attributes based on available features
std::vector<EGLint> context_attributes;
context_attributes.push_back(EGL_CONTEXT_WEBGL_COMPATIBILITY_ANGLE);
context_attributes.push_back(EGL_TRUE);
// context_attributes.push_back(EGL_EXTENSIONS_ENABLED_ANGLE);
// context_attributes.push_back(EGL_TRUE);
context_attributes.push_back(EGL_CONTEXT_OPENGL_DEBUG);
#if DEBUG
context_attributes.push_back(EGL_TRUE);
#else
context_attributes.push_back(EGL_FALSE);
#endif
context_attributes.push_back(EGL_NONE);
context =
eglCreateContext(display, config, nullptr, context_attributes.data());
if (context == EGL_NO_CONTEXT) {
NAPI_THROW_ERROR(env, "Could not create context");
return;
}
EGLint surface_attribs[] = {EGL_WIDTH, (EGLint)1, EGL_HEIGHT, (EGLint)1,
EGL_NONE};
surface = eglCreatePbufferSurface(display, config, surface_attribs);
if (surface == EGL_NO_SURFACE) {
NAPI_THROW_ERROR(env, "Could not create surface");
return;
}
if (!eglMakeCurrent(display, surface, surface, context)) {
NAPI_THROW_ERROR(env, "Could not make context current");
return;
}
}
void EGLContextWrapper::BindProcAddresses() {
// Bind runtime function pointers.
glActiveTexture = reinterpret_cast<PFNGLACTIVETEXTUREPROC>(
eglGetProcAddress("glActiveTexture"));
glAttachShader = reinterpret_cast<PFNGLATTACHSHADERPROC>(
eglGetProcAddress("glAttachShader"));
glBindBuffer =
reinterpret_cast<PFNGLBINDBUFFERPROC>(eglGetProcAddress("glBindBuffer"));
glBindFramebuffer = reinterpret_cast<PFNGLBINDFRAMEBUFFERPROC>(
eglGetProcAddress("glBindFramebuffer"));
glBindRenderbuffer = reinterpret_cast<PFNGLBINDRENDERBUFFERPROC>(
eglGetProcAddress("glBindRenderbuffer"));
glBindTexture = reinterpret_cast<PFNGLBINDTEXTUREPROC>(
eglGetProcAddress("glBindTexture"));
glBufferData =
reinterpret_cast<PFNGLBUFFERDATAPROC>(eglGetProcAddress("glBufferData"));
glCheckFramebufferStatus = reinterpret_cast<PFNGLCHECKFRAMEBUFFERSTATUSPROC>(
eglGetProcAddress("glCheckFramebufferStatus"));
glCompileShader = reinterpret_cast<PFNGLCOMPILESHADERPROC>(
eglGetProcAddress("glCompileShader"));
glCreateProgram = reinterpret_cast<PFNGLCREATEPROGRAMPROC>(
eglGetProcAddress("glCreateProgram"));
glCreateShader = reinterpret_cast<PFNGLCREATESHADERPROC>(
eglGetProcAddress("glCreateShader"));
glCullFace =
reinterpret_cast<PFNGLCULLFACEPROC>(eglGetProcAddress("glCullFace"));
glDeleteBuffers = reinterpret_cast<PFNGLDELETEBUFFERSPROC>(
eglGetProcAddress("glDeleteBuffers"));
glDeleteFramebuffers = reinterpret_cast<PFNGLDELETEFRAMEBUFFERSPROC>(
eglGetProcAddress("glDeleteFramebuffers"));
glDeleteProgram = reinterpret_cast<PFNGLDELETEPROGRAMPROC>(
eglGetProcAddress("glDeleteProgram"));
glDeleteShader = reinterpret_cast<PFNGLDELETESHADERPROC>(
eglGetProcAddress("glDeleteShader"));
glDeleteTextures = reinterpret_cast<PFNGLDELETETEXTURESPROC>(
eglGetProcAddress("glDeleteTextures"));
glDrawArrays =
reinterpret_cast<PFNGLDRAWARRAYSPROC>(eglGetProcAddress("glDrawArrays"));
glDrawElements = reinterpret_cast<PFNGLDRAWELEMENTSPROC>(
eglGetProcAddress("glDrawElements"));
glDisable =
reinterpret_cast<PFNGLDISABLEPROC>(eglGetProcAddress("glDisable"));
glDisableVertexAttribArray =
reinterpret_cast<PFNGLDISABLEVERTEXATTRIBARRAYPROC>(
eglGetProcAddress("glDisableVertexAttribArray"));
glEnable = reinterpret_cast<PFNGLENABLEPROC>(eglGetProcAddress("glEnable"));
glEnableVertexAttribArray =
reinterpret_cast<PFNGLENABLEVERTEXATTRIBARRAYPROC>(
eglGetProcAddress("glEnableVertexAttribArray"));
glFinish = reinterpret_cast<PFNGLFINISHPROC>(eglGetProcAddress("glFinish"));
glFlush = reinterpret_cast<PFNGLFLUSHPROC>(eglGetProcAddress("glFlush"));
glFramebufferRenderbuffer =
reinterpret_cast<PFNGLFRAMEBUFFERRENDERBUFFERPROC>(
eglGetProcAddress("glFramebufferRenderbuffer"));
glFramebufferTexture2D = reinterpret_cast<PFNGLFRAMEBUFFERTEXTURE2DPROC>(
eglGetProcAddress("glFramebufferTexture2D"));
glGenBuffers =
reinterpret_cast<PFNGLGENBUFFERSPROC>(eglGetProcAddress("glGenBuffers"));
glGenFramebuffers = reinterpret_cast<PFNGLGENFRAMEBUFFERSPROC>(
eglGetProcAddress("glGenFramebuffers"));
glGenRenderbuffers = reinterpret_cast<PFNGLGENRENDERBUFFERSPROC>(
eglGetProcAddress("glGenRenderbuffers"));
glGetAttribLocation = reinterpret_cast<PFNGLGETATTRIBLOCATIONPROC>(
eglGetProcAddress("glGetAttribLocation"));
glGetError =
reinterpret_cast<PFNGLGETERRORPROC>(eglGetProcAddress("glGetError"));
glGetIntegerv = reinterpret_cast<PFNGLGETINTEGERVPROC>(
eglGetProcAddress("glGetIntegerv"));
glGenTextures = reinterpret_cast<PFNGLGENTEXTURESPROC>(
eglGetProcAddress("glGenTextures"));
glGetProgramiv = reinterpret_cast<PFNGLGETPROGRAMIVPROC>(
eglGetProcAddress("glGetProgramiv"));
glGetProgramInfoLog = reinterpret_cast<PFNGLGETPROGRAMINFOLOGPROC>(
eglGetProcAddress("glGetProgramInfoLog"));
glGetShaderiv = reinterpret_cast<PFNGLGETSHADERIVPROC>(
eglGetProcAddress("glGetShaderiv"));
glGetShaderInfoLog = reinterpret_cast<PFNGLGETSHADERINFOLOGPROC>(
eglGetProcAddress("glGetShaderInfoLog"));
glGetString =
reinterpret_cast<PFNGLGETSTRINGPROC>(eglGetProcAddress("glGetString"));
glGetUniformLocation = reinterpret_cast<PFNGLGETUNIFORMLOCATIONPROC>(
eglGetProcAddress("glGetUniformLocation"));
glLinkProgram = reinterpret_cast<PFNGLLINKPROGRAMPROC>(
eglGetProcAddress("glLinkProgram"));
glReadPixels =
reinterpret_cast<PFNGLREADPIXELSPROC>(eglGetProcAddress("glReadPixels"));
glRenderbufferStorage = reinterpret_cast<PFNGLRENDERBUFFERSTORAGEPROC>(
eglGetProcAddress("glRenderbufferStorage"));
glScissor =
reinterpret_cast<PFNGLSCISSORPROC>(eglGetProcAddress("glScissor"));
glShaderSource = reinterpret_cast<PFNGLSHADERSOURCEPROC>(
eglGetProcAddress("glShaderSource"));
glTexImage2D =
reinterpret_cast<PFNGLTEXIMAGE2DPROC>(eglGetProcAddress("glTexImage2D"));
glTexParameteri = reinterpret_cast<PFNGLTEXPARAMETERIPROC>(
eglGetProcAddress("glTexParameteri"));
glTexSubImage2D = reinterpret_cast<PFNGLTEXSUBIMAGE2DPROC>(
eglGetProcAddress("glTexSubImage2D"));
glUniform1i =
reinterpret_cast<PFNGLUNIFORM1IPROC>(eglGetProcAddress("glUniform1i"));
glUniform1f =
reinterpret_cast<PFNGLUNIFORM1FPROC>(eglGetProcAddress("glUniform1f"));
glUniform1fv =
reinterpret_cast<PFNGLUNIFORM1FVPROC>(eglGetProcAddress("glUniform1fv"));
glUniform2i =
reinterpret_cast<PFNGLUNIFORM2IPROC>(eglGetProcAddress("glUniform2i"));
glUniform4fv =
reinterpret_cast<PFNGLUNIFORM4FVPROC>(eglGetProcAddress("glUniform4fv"));
glUniform4i =
reinterpret_cast<PFNGLUNIFORM4IPROC>(eglGetProcAddress("glUniform4i"));
glUseProgram =
reinterpret_cast<PFNGLUSEPROGRAMPROC>(eglGetProcAddress("glUseProgram"));
glVertexAttribPointer = reinterpret_cast<PFNGLVERTEXATTRIBPOINTERPROC>(
eglGetProcAddress("glVertexAttribPointer"));
glViewport =
reinterpret_cast<PFNGLVIEWPORTPROC>(eglGetProcAddress("glViewport"));
// ANGLE specific
glRequestExtensionANGLE = reinterpret_cast<PFNGLREQUESTEXTENSIONANGLEPROC>(
eglGetProcAddress("glRequestExtensionANGLE"));
}
void EGLContextWrapper::BindExtensions() {
//
// TODO - write me/doc me.
//
// GLint num_extensions = 0;
// this->glGetIntegerv(GL_NUM_REQUESTABLE_EXTENSIONS_ANGLE, &num_extensions);
// fprintf(stderr, "----> requestable extensions: %d\n", num_extensions);
const char* extensions = reinterpret_cast<const char*>(
this->glGetString(GL_REQUESTABLE_EXTENSIONS_ANGLE));
std::string s(extensions);
std::string delim = " ";
size_t pos = 0;
std::string token;
std::cout << "---- GL_REQUESTABLE_EXTENSIONS_ANGLE ----" << std::endl;
while ((pos = s.find(delim)) != std::string::npos) {
token = s.substr(0, pos);
std::cout << "Enabling: " << token << std::endl;
glRequestExtensionANGLE(token.c_str());
s.erase(0, pos + delim.length());
}
std::cout << s;
std::cout << "-------------------------" << std::endl;
}
EGLContextWrapper::~EGLContextWrapper() {
// TODO(kreeger): Close context attributes.
// TODO(kreeger): Cleanup global objects.
if (extensions_wrapper != nullptr) {
delete extensions_wrapper;
}
}
EGLContextWrapper* EGLContextWrapper::Create(napi_env env) {
return new EGLContextWrapper(env);
}
} // namespace nodejsgl
<commit_msg>Cleanup<commit_after>/**
* @license
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
#include "egl_context_wrapper.h"
#include "utils.h"
#include <EGL/egl.h>
#include <EGL/eglext.h>
#include <GLES2/gl2.h>
#include <iostream>
#include <vector>
namespace nodejsgl {
#if DEBUG
void LogExtensions(const char* extensions_name, const char* extensions) {
std::string s(extensions);
std::string delim = " ";
size_t pos = 0;
std::string token;
std::cout << "---- " << extensions_name << "----" << std::endl;
while ((pos = s.find(delim)) != std::string::npos) {
token = s.substr(0, pos);
std::cout << token << std::endl;
s.erase(0, pos + delim.length());
}
std::cout << s;
std::cout << "-------------------------" << std::endl;
}
#endif
EGLContextWrapper::EGLContextWrapper(napi_env env) {
InitEGL(env);
BindProcAddresses();
BindExtensions();
#if DEBUG
// LogExtensions("GL_EXTENSIONS",
// reinterpret_cast<const char*>(glGetString(GL_EXTENSIONS)));
#endif
}
void EGLContextWrapper::InitEGL(napi_env env) {
// TODO(kreeger): Figure out how to make this work headless
display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
if (display == EGL_NO_DISPLAY) {
NAPI_THROW_ERROR(env, "No display");
return;
}
EGLint major;
EGLint minor;
if (!eglInitialize(display, &major, &minor)) {
NAPI_THROW_ERROR(env, "Could not initialize display");
return;
}
#if DEBUG
// TODO(kreeger): Clean this up.
// std::cerr << "major: " << major << std::endl;
// std::cerr << "minor: " << minor << std::endl;
#endif
extensions_wrapper = new EGLExtensionsWrapper(display);
EGLint attrib_list[] = {EGL_SURFACE_TYPE, EGL_PBUFFER_BIT,
EGL_RED_SIZE, 8,
EGL_GREEN_SIZE, 8,
EGL_BLUE_SIZE, 8,
EGL_ALPHA_SIZE, 8,
EGL_DEPTH_SIZE, 24,
EGL_STENCIL_SIZE, 8,
EGL_NONE};
EGLint num_config;
if (!eglChooseConfig(display, attrib_list, &config, 1, &num_config)) {
NAPI_THROW_ERROR(env, "Failed creating a config");
return;
}
eglBindAPI(EGL_OPENGL_ES_API);
if (eglGetError() != EGL_SUCCESS) {
NAPI_THROW_ERROR(env, "Failed to set OpenGL ES API");
return;
}
#if DEBUG
// LogExtensions("EGL_EXTENSIONS", eglQueryString(display, EGL_EXTENSIONS));
#endif
// Append attributes based on available features
std::vector<EGLint> context_attributes;
context_attributes.push_back(EGL_CONTEXT_WEBGL_COMPATIBILITY_ANGLE);
context_attributes.push_back(EGL_TRUE);
context_attributes.push_back(EGL_CONTEXT_OPENGL_DEBUG);
#if DEBUG
context_attributes.push_back(EGL_TRUE);
#else
context_attributes.push_back(EGL_FALSE);
#endif
context_attributes.push_back(EGL_NONE);
context =
eglCreateContext(display, config, nullptr, context_attributes.data());
if (context == EGL_NO_CONTEXT) {
NAPI_THROW_ERROR(env, "Could not create context");
return;
}
EGLint surface_attribs[] = {EGL_WIDTH, (EGLint)1, EGL_HEIGHT, (EGLint)1,
EGL_NONE};
surface = eglCreatePbufferSurface(display, config, surface_attribs);
if (surface == EGL_NO_SURFACE) {
NAPI_THROW_ERROR(env, "Could not create surface");
return;
}
if (!eglMakeCurrent(display, surface, surface, context)) {
NAPI_THROW_ERROR(env, "Could not make context current");
return;
}
}
void EGLContextWrapper::BindProcAddresses() {
// Bind runtime function pointers.
glActiveTexture = reinterpret_cast<PFNGLACTIVETEXTUREPROC>(
eglGetProcAddress("glActiveTexture"));
glAttachShader = reinterpret_cast<PFNGLATTACHSHADERPROC>(
eglGetProcAddress("glAttachShader"));
glBindBuffer =
reinterpret_cast<PFNGLBINDBUFFERPROC>(eglGetProcAddress("glBindBuffer"));
glBindFramebuffer = reinterpret_cast<PFNGLBINDFRAMEBUFFERPROC>(
eglGetProcAddress("glBindFramebuffer"));
glBindRenderbuffer = reinterpret_cast<PFNGLBINDRENDERBUFFERPROC>(
eglGetProcAddress("glBindRenderbuffer"));
glBindTexture = reinterpret_cast<PFNGLBINDTEXTUREPROC>(
eglGetProcAddress("glBindTexture"));
glBufferData =
reinterpret_cast<PFNGLBUFFERDATAPROC>(eglGetProcAddress("glBufferData"));
glCheckFramebufferStatus = reinterpret_cast<PFNGLCHECKFRAMEBUFFERSTATUSPROC>(
eglGetProcAddress("glCheckFramebufferStatus"));
glCompileShader = reinterpret_cast<PFNGLCOMPILESHADERPROC>(
eglGetProcAddress("glCompileShader"));
glCreateProgram = reinterpret_cast<PFNGLCREATEPROGRAMPROC>(
eglGetProcAddress("glCreateProgram"));
glCreateShader = reinterpret_cast<PFNGLCREATESHADERPROC>(
eglGetProcAddress("glCreateShader"));
glCullFace =
reinterpret_cast<PFNGLCULLFACEPROC>(eglGetProcAddress("glCullFace"));
glDeleteBuffers = reinterpret_cast<PFNGLDELETEBUFFERSPROC>(
eglGetProcAddress("glDeleteBuffers"));
glDeleteFramebuffers = reinterpret_cast<PFNGLDELETEFRAMEBUFFERSPROC>(
eglGetProcAddress("glDeleteFramebuffers"));
glDeleteProgram = reinterpret_cast<PFNGLDELETEPROGRAMPROC>(
eglGetProcAddress("glDeleteProgram"));
glDeleteShader = reinterpret_cast<PFNGLDELETESHADERPROC>(
eglGetProcAddress("glDeleteShader"));
glDeleteTextures = reinterpret_cast<PFNGLDELETETEXTURESPROC>(
eglGetProcAddress("glDeleteTextures"));
glDrawArrays =
reinterpret_cast<PFNGLDRAWARRAYSPROC>(eglGetProcAddress("glDrawArrays"));
glDrawElements = reinterpret_cast<PFNGLDRAWELEMENTSPROC>(
eglGetProcAddress("glDrawElements"));
glDisable =
reinterpret_cast<PFNGLDISABLEPROC>(eglGetProcAddress("glDisable"));
glDisableVertexAttribArray =
reinterpret_cast<PFNGLDISABLEVERTEXATTRIBARRAYPROC>(
eglGetProcAddress("glDisableVertexAttribArray"));
glEnable = reinterpret_cast<PFNGLENABLEPROC>(eglGetProcAddress("glEnable"));
glEnableVertexAttribArray =
reinterpret_cast<PFNGLENABLEVERTEXATTRIBARRAYPROC>(
eglGetProcAddress("glEnableVertexAttribArray"));
glFinish = reinterpret_cast<PFNGLFINISHPROC>(eglGetProcAddress("glFinish"));
glFlush = reinterpret_cast<PFNGLFLUSHPROC>(eglGetProcAddress("glFlush"));
glFramebufferRenderbuffer =
reinterpret_cast<PFNGLFRAMEBUFFERRENDERBUFFERPROC>(
eglGetProcAddress("glFramebufferRenderbuffer"));
glFramebufferTexture2D = reinterpret_cast<PFNGLFRAMEBUFFERTEXTURE2DPROC>(
eglGetProcAddress("glFramebufferTexture2D"));
glGenBuffers =
reinterpret_cast<PFNGLGENBUFFERSPROC>(eglGetProcAddress("glGenBuffers"));
glGenFramebuffers = reinterpret_cast<PFNGLGENFRAMEBUFFERSPROC>(
eglGetProcAddress("glGenFramebuffers"));
glGenRenderbuffers = reinterpret_cast<PFNGLGENRENDERBUFFERSPROC>(
eglGetProcAddress("glGenRenderbuffers"));
glGetAttribLocation = reinterpret_cast<PFNGLGETATTRIBLOCATIONPROC>(
eglGetProcAddress("glGetAttribLocation"));
glGetError =
reinterpret_cast<PFNGLGETERRORPROC>(eglGetProcAddress("glGetError"));
glGetIntegerv = reinterpret_cast<PFNGLGETINTEGERVPROC>(
eglGetProcAddress("glGetIntegerv"));
glGenTextures = reinterpret_cast<PFNGLGENTEXTURESPROC>(
eglGetProcAddress("glGenTextures"));
glGetProgramiv = reinterpret_cast<PFNGLGETPROGRAMIVPROC>(
eglGetProcAddress("glGetProgramiv"));
glGetProgramInfoLog = reinterpret_cast<PFNGLGETPROGRAMINFOLOGPROC>(
eglGetProcAddress("glGetProgramInfoLog"));
glGetShaderiv = reinterpret_cast<PFNGLGETSHADERIVPROC>(
eglGetProcAddress("glGetShaderiv"));
glGetShaderInfoLog = reinterpret_cast<PFNGLGETSHADERINFOLOGPROC>(
eglGetProcAddress("glGetShaderInfoLog"));
glGetString =
reinterpret_cast<PFNGLGETSTRINGPROC>(eglGetProcAddress("glGetString"));
glGetUniformLocation = reinterpret_cast<PFNGLGETUNIFORMLOCATIONPROC>(
eglGetProcAddress("glGetUniformLocation"));
glLinkProgram = reinterpret_cast<PFNGLLINKPROGRAMPROC>(
eglGetProcAddress("glLinkProgram"));
glReadPixels =
reinterpret_cast<PFNGLREADPIXELSPROC>(eglGetProcAddress("glReadPixels"));
glRenderbufferStorage = reinterpret_cast<PFNGLRENDERBUFFERSTORAGEPROC>(
eglGetProcAddress("glRenderbufferStorage"));
glScissor =
reinterpret_cast<PFNGLSCISSORPROC>(eglGetProcAddress("glScissor"));
glShaderSource = reinterpret_cast<PFNGLSHADERSOURCEPROC>(
eglGetProcAddress("glShaderSource"));
glTexImage2D =
reinterpret_cast<PFNGLTEXIMAGE2DPROC>(eglGetProcAddress("glTexImage2D"));
glTexParameteri = reinterpret_cast<PFNGLTEXPARAMETERIPROC>(
eglGetProcAddress("glTexParameteri"));
glTexSubImage2D = reinterpret_cast<PFNGLTEXSUBIMAGE2DPROC>(
eglGetProcAddress("glTexSubImage2D"));
glUniform1i =
reinterpret_cast<PFNGLUNIFORM1IPROC>(eglGetProcAddress("glUniform1i"));
glUniform1f =
reinterpret_cast<PFNGLUNIFORM1FPROC>(eglGetProcAddress("glUniform1f"));
glUniform1fv =
reinterpret_cast<PFNGLUNIFORM1FVPROC>(eglGetProcAddress("glUniform1fv"));
glUniform2i =
reinterpret_cast<PFNGLUNIFORM2IPROC>(eglGetProcAddress("glUniform2i"));
glUniform4fv =
reinterpret_cast<PFNGLUNIFORM4FVPROC>(eglGetProcAddress("glUniform4fv"));
glUniform4i =
reinterpret_cast<PFNGLUNIFORM4IPROC>(eglGetProcAddress("glUniform4i"));
glUseProgram =
reinterpret_cast<PFNGLUSEPROGRAMPROC>(eglGetProcAddress("glUseProgram"));
glVertexAttribPointer = reinterpret_cast<PFNGLVERTEXATTRIBPOINTERPROC>(
eglGetProcAddress("glVertexAttribPointer"));
glViewport =
reinterpret_cast<PFNGLVIEWPORTPROC>(eglGetProcAddress("glViewport"));
// ANGLE specific
glRequestExtensionANGLE = reinterpret_cast<PFNGLREQUESTEXTENSIONANGLEPROC>(
eglGetProcAddress("glRequestExtensionANGLE"));
}
void EGLContextWrapper::BindExtensions() {
//
// TODO - write me/doc me.
//
// GLint num_extensions = 0;
// this->glGetIntegerv(GL_NUM_REQUESTABLE_EXTENSIONS_ANGLE, &num_extensions);
// fprintf(stderr, "----> requestable extensions: %d\n", num_extensions);
const char* extensions = reinterpret_cast<const char*>(
this->glGetString(GL_REQUESTABLE_EXTENSIONS_ANGLE));
std::string s(extensions);
std::string delim = " ";
size_t pos = 0;
std::string token;
std::cout << "---- GL_REQUESTABLE_EXTENSIONS_ANGLE ----" << std::endl;
while ((pos = s.find(delim)) != std::string::npos) {
token = s.substr(0, pos);
std::cout << "Enabling: " << token << std::endl;
glRequestExtensionANGLE(token.c_str());
s.erase(0, pos + delim.length());
}
std::cout << s;
std::cout << "-------------------------" << std::endl;
}
EGLContextWrapper::~EGLContextWrapper() {
// TODO(kreeger): Close context attributes.
// TODO(kreeger): Cleanup global objects.
if (extensions_wrapper != nullptr) {
delete extensions_wrapper;
}
}
EGLContextWrapper* EGLContextWrapper::Create(napi_env env) {
return new EGLContextWrapper(env);
}
} // namespace nodejsgl
<|endoftext|>
|
<commit_before>
#include <node.h>
#include <node_buffer.h>
#include "database.h"
namespace bangdown {
static v8::Persistent<v8::FunctionTemplate> database_constructor;
Database::Database (char* name) : name(name) {
db = NULL;
};
Database::~Database () {
if (db != NULL)
db->closedatabase();
delete db;
delete[] name;
};
database* Database::OpenDatabase (
char* location
) {
database* db;
db = new database((char*)location);
printf("%s Created\n", db->getdbname());
return db;
}
void Database::Init () {
v8::Local<v8::FunctionTemplate> tpl = v8::FunctionTemplate::New(Database::New);
NanAssignPersistent(v8::FunctionTemplate, database_constructor, tpl);
tpl->SetClassName(NanSymbol("Database"));
tpl->InstanceTemplate()->SetInternalFieldCount(1);
NODE_SET_PROTOTYPE_METHOD(tpl, "new", Database::New);
NODE_SET_PROTOTYPE_METHOD(tpl, "put", Database::Put);
}
NAN_METHOD(Database::New) {
NanScope();
if (args.Length() == 0)
return NanThrowError("constructor requires at least a location argument");
if (!args[0]->IsString())
return NanThrowError("constructor requires a location string argument");
char* name = NanFromV8String(args[0].As<v8::Object>(), Nan::UTF8, NULL, NULL, 0, v8::String::NO_OPTIONS);
Database* obj = new Database(name);
obj->Wrap(args.This());
printf("NAME: %s \n", name);
// NanReturnUndefined();
NanReturnValue(args.This());
}
NAN_METHOD(Database::Put) {
NanScope();
char* location = NanFromV8String(args[0].As<v8::Object>(), Nan::UTF8, NULL, NULL, 0, v8::String::NO_OPTIONS);
printf("Creating new db\n");
database* db = new database((char*)location);
printf("%s Created\n", db->getdbname());
table *tbl = db->gettable((char*)"mytable2");
connection *conn = tbl->getconnection();
FDT ikey, ival, *out;
// char* key = location;
// char* val = location;
ikey.data = location;
ikey.length = strlen(location);
ival.data = (void*)location;
ival.length = strlen(location);
int ret;
ret=conn->put(&ikey, &ival, INSERT_UPDATE);
printf("PUT Finished with %d\n",ret);
out = conn->get(&ikey);
printf("GET Finished\n");
printf("GET ReturnValue(%s)\n", (char*)out->data);
// key = null;
// val = null;
db->closedatabase();
delete db;
NanReturnUndefined();
}
NAN_METHOD(Bang){
NanScope();
v8::Local<v8::String> name;
if (args.Length() != 0 && args[0]->IsString())
name = args[0].As<v8::String>();
NanReturnValue(Database::NewInstance(name));
}
v8::Handle<v8::Value> Database::NewInstance (v8::Local<v8::String> &name) {
NanScope();
v8::Local<v8::Object> instance;
v8::Local<v8::FunctionTemplate> constructorHandle =
NanPersistentToLocal(database_constructor);
if (name.IsEmpty()) {
instance = constructorHandle->GetFunction()->NewInstance(0, NULL);
} else {
v8::Handle<v8::Value> argv[] = { name };
instance = constructorHandle->GetFunction()->NewInstance(1, argv);
}
return instance;
}
}
<commit_msg>Woot got local reference to Database class unwrapping from args.this finally<commit_after>
#include <node.h>
#include <node_buffer.h>
#include "database.h"
namespace bangdown {
static v8::Persistent<v8::FunctionTemplate> database_constructor;
Database::Database (char* name) : name(name) {
db = NULL;
};
Database::~Database () {
if (db != NULL)
db->closedatabase();
delete db;
delete[] name;
};
database* Database::OpenDatabase (
char* location
) {
//database* db;
db = new database((char*)location);
printf("%s Created\n", db->getdbname());
return db;
}
void Database::Init () {
v8::Local<v8::FunctionTemplate> tpl = v8::FunctionTemplate::New(Database::New);
NanAssignPersistent(v8::FunctionTemplate, database_constructor, tpl);
tpl->SetClassName(NanSymbol("Database"));
tpl->InstanceTemplate()->SetInternalFieldCount(1);
NODE_SET_PROTOTYPE_METHOD(tpl, "new", Database::New);
NODE_SET_PROTOTYPE_METHOD(tpl, "put", Database::Put);
}
NAN_METHOD(Database::New) {
NanScope();
if (args.Length() == 0)
return NanThrowError("constructor requires at least a location argument");
if (!args[0]->IsString())
return NanThrowError("constructor requires a location string argument");
char* name = NanFromV8String(args[0].As<v8::Object>(), Nan::UTF8, NULL, NULL, 0, v8::String::NO_OPTIONS);
Database* obj = new Database(name);
obj->Wrap(args.This());
printf("NAME: %s \n", name);
// NanReturnUndefined();
NanReturnValue(args.This());
}
NAN_METHOD(Database::Put) {
NanScope();
Database* _database = ObjectWrap::Unwrap<Database>(args.This());
char* location = NanFromV8String(args[0].As<v8::Object>(), Nan::UTF8, NULL, NULL, 0, v8::String::NO_OPTIONS);
printf("Creating new db\n");
database* db = new database((char*)location);
printf("%s Created\n", db->getdbname());
table *tbl = db->gettable((char*)"mytable2");
connection *conn = tbl->getconnection();
FDT ikey, ival, *out;
// char* key = location;
// char* val = location;
ikey.data = location;
ikey.length = strlen(location);
ival.data = (void*)location;
ival.length = strlen(location);
int ret;
ret=conn->put(&ikey, &ival, INSERT_UPDATE);
printf("PUT Finished with %d\n",ret);
out = conn->get(&ikey);
printf("GET Finished\n");
printf("GET ReturnValue(%s)\n", (char*)out->data);
// key = null;
// val = null;
db->closedatabase();
delete db;
NanReturnUndefined();
}
NAN_METHOD(Bang){
NanScope();
v8::Local<v8::String> name;
if (args.Length() != 0 && args[0]->IsString())
name = args[0].As<v8::String>();
NanReturnValue(Database::NewInstance(name));
}
v8::Handle<v8::Value> Database::NewInstance (v8::Local<v8::String> &name) {
NanScope();
v8::Local<v8::Object> instance;
v8::Local<v8::FunctionTemplate> constructorHandle =
NanPersistentToLocal(database_constructor);
if (name.IsEmpty()) {
instance = constructorHandle->GetFunction()->NewInstance(0, NULL);
} else {
v8::Handle<v8::Value> argv[] = { name };
instance = constructorHandle->GetFunction()->NewInstance(1, argv);
}
return instance;
}
}
<|endoftext|>
|
<commit_before>// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "deps_log.h"
#include <assert.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include "graph.h"
#include "metrics.h"
#include "state.h"
#include "util.h"
namespace {
const char kFileSignature[] = "# ninja deps v%d\n";
const int kCurrentVersion = 1;
} // anonymous namespace
DepsLog::~DepsLog() {
Close();
}
bool DepsLog::OpenForWrite(const string& path, string* err) {
file_ = fopen(path.c_str(), "ab");
if (!file_) {
*err = strerror(errno);
return false;
}
SetCloseOnExec(fileno(file_));
// Opening a file in append mode doesn't set the file pointer to the file's
// end on Windows. Do that explicitly.
fseek(file_, 0, SEEK_END);
if (ftell(file_) == 0) {
if (fprintf(file_, kFileSignature, kCurrentVersion) < 0) {
*err = strerror(errno);
return false;
}
}
return true;
}
bool DepsLog::RecordDeps(Node* node, TimeStamp mtime,
const vector<Node*>& nodes) {
return RecordDeps(node, mtime, nodes.size(),
nodes.empty() ? NULL : (Node**)&nodes.front());
}
bool DepsLog::RecordDeps(Node* node, TimeStamp mtime,
int node_count, Node** nodes) {
// Track whether there's any new data to be recorded.
bool made_change = false;
// Assign ids to all nodes that are missing one.
if (node->id() < 0) {
RecordId(node);
made_change = true;
}
for (int i = 0; i < node_count; ++i) {
if (nodes[i]->id() < 0) {
RecordId(nodes[i]);
made_change = true;
}
}
// See if the new data is different than the existing data, if any.
if (!made_change) {
Deps* deps = GetDeps(node);
if (!deps ||
deps->mtime != mtime ||
deps->node_count != node_count) {
made_change = true;
} else {
for (int i = 0; i < node_count; ++i) {
if (deps->nodes[i] != nodes[i]) {
made_change = true;
break;
}
}
}
}
// Don't write anything if there's no new info.
if (!made_change)
return true;
uint16_t size = 4 * (1 + 1 + (uint16_t)node_count);
size |= 0x8000; // Deps record: set high bit.
fwrite(&size, 2, 1, file_);
int id = node->id();
fwrite(&id, 4, 1, file_);
int timestamp = mtime;
fwrite(×tamp, 4, 1, file_);
for (int i = 0; i < node_count; ++i) {
id = nodes[i]->id();
fwrite(&id, 4, 1, file_);
}
return true;
}
void DepsLog::Close() {
if (file_)
fclose(file_);
file_ = NULL;
}
bool DepsLog::Load(const string& path, State* state, string* err) {
METRIC_RECORD(".ninja_deps load");
char buf[32 << 10];
FILE* f = fopen(path.c_str(), "rb");
if (!f) {
if (errno == ENOENT)
return true;
*err = strerror(errno);
return false;
}
if (!fgets(buf, sizeof(buf), f)) {
*err = strerror(errno);
return false;
}
int version = 0;
sscanf(buf, kFileSignature, &version);
if (version != kCurrentVersion) {
*err = "bad deps log signature or version; starting over";
fclose(f);
unlink(path.c_str());
// Don't report this as a failure. An empty deps log will cause
// us to rebuild the outputs anyway.
return true;
}
for (;;) {
uint16_t size;
if (fread(&size, 2, 1, f) < 1)
break;
bool is_deps = (size >> 15) != 0;
size = size & 0x7FFF;
if (fread(buf, size, 1, f) < 1)
break;
if (is_deps) {
assert(size % 4 == 0);
int* deps_data = reinterpret_cast<int*>(buf);
int out_id = deps_data[0];
int mtime = deps_data[1];
deps_data += 2;
int deps_count = (size / 4) - 2;
Deps* deps = new Deps;
deps->mtime = mtime;
deps->node_count = deps_count;
deps->nodes = new Node*[deps_count];
for (int i = 0; i < deps_count; ++i) {
assert(deps_data[i] < (int)nodes_.size());
assert(nodes_[deps_data[i]]);
deps->nodes[i] = nodes_[deps_data[i]];
}
if (out_id >= (int)deps_.size())
deps_.resize(out_id + 1);
if (deps_[out_id]) {
++dead_record_count_;
delete deps_[out_id];
}
deps_[out_id] = deps;
} else {
StringPiece path(buf, size);
Node* node = state->GetNode(path);
assert(node->id() < 0);
node->set_id(nodes_.size());
nodes_.push_back(node);
}
}
if (ferror(f)) {
*err = strerror(ferror(f));
return false;
}
fclose(f);
return true;
}
DepsLog::Deps* DepsLog::GetDeps(Node* node) {
if (node->id() < 0)
return NULL;
return deps_[node->id()];
}
bool DepsLog::Recompact(const string& path, string* err) {
METRIC_RECORD(".ninja_deps recompact");
printf("Recompacting deps...\n");
string temp_path = path + ".recompact";
DepsLog new_log;
if (!new_log.OpenForWrite(temp_path, err))
return false;
// Clear all known ids so that new ones can be reassigned.
for (vector<Node*>::iterator i = nodes_.begin();
i != nodes_.end(); ++i) {
(*i)->set_id(-1);
}
// Write out all deps again.
for (int old_id = 0; old_id < (int)deps_.size(); ++old_id) {
Deps* deps = deps_[old_id];
if (!new_log.RecordDeps(nodes_[old_id], deps->mtime,
deps->node_count, deps->nodes)) {
new_log.Close();
return false;
}
}
new_log.Close();
if (unlink(path.c_str()) < 0) {
*err = strerror(errno);
return false;
}
if (rename(temp_path.c_str(), path.c_str()) < 0) {
*err = strerror(errno);
return false;
}
return true;
}
bool DepsLog::RecordId(Node* node) {
uint16_t size = (uint16_t)node->path().size();
fwrite(&size, 2, 1, file_);
fwrite(node->path().data(), node->path().size(), 1, file_);
node->set_id(nodes_.size());
nodes_.push_back(node);
return true;
}
<commit_msg>Write the depslog version in binary instead of text.<commit_after>// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "deps_log.h"
#include <assert.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include "graph.h"
#include "metrics.h"
#include "state.h"
#include "util.h"
// The version is stored as 4 bytes after the signature and also serves as a
// byte order mark. Signature and version combined are 16 bytes long.
const char kFileSignature[] = "# ninjadeps\n";
const int kCurrentVersion = 1;
DepsLog::~DepsLog() {
Close();
}
bool DepsLog::OpenForWrite(const string& path, string* err) {
file_ = fopen(path.c_str(), "ab");
if (!file_) {
*err = strerror(errno);
return false;
}
SetCloseOnExec(fileno(file_));
// Opening a file in append mode doesn't set the file pointer to the file's
// end on Windows. Do that explicitly.
fseek(file_, 0, SEEK_END);
if (ftell(file_) == 0) {
if (fwrite(kFileSignature, sizeof(kFileSignature) - 1, 1, file_) < 1) {
*err = strerror(errno);
return false;
}
if (fwrite(&kCurrentVersion, 4, 1, file_) < 1) {
*err = strerror(errno);
return false;
}
}
return true;
}
bool DepsLog::RecordDeps(Node* node, TimeStamp mtime,
const vector<Node*>& nodes) {
return RecordDeps(node, mtime, nodes.size(),
nodes.empty() ? NULL : (Node**)&nodes.front());
}
bool DepsLog::RecordDeps(Node* node, TimeStamp mtime,
int node_count, Node** nodes) {
// Track whether there's any new data to be recorded.
bool made_change = false;
// Assign ids to all nodes that are missing one.
if (node->id() < 0) {
RecordId(node);
made_change = true;
}
for (int i = 0; i < node_count; ++i) {
if (nodes[i]->id() < 0) {
RecordId(nodes[i]);
made_change = true;
}
}
// See if the new data is different than the existing data, if any.
if (!made_change) {
Deps* deps = GetDeps(node);
if (!deps ||
deps->mtime != mtime ||
deps->node_count != node_count) {
made_change = true;
} else {
for (int i = 0; i < node_count; ++i) {
if (deps->nodes[i] != nodes[i]) {
made_change = true;
break;
}
}
}
}
// Don't write anything if there's no new info.
if (!made_change)
return true;
uint16_t size = 4 * (1 + 1 + (uint16_t)node_count);
size |= 0x8000; // Deps record: set high bit.
fwrite(&size, 2, 1, file_);
int id = node->id();
fwrite(&id, 4, 1, file_);
int timestamp = mtime;
fwrite(×tamp, 4, 1, file_);
for (int i = 0; i < node_count; ++i) {
id = nodes[i]->id();
fwrite(&id, 4, 1, file_);
}
return true;
}
void DepsLog::Close() {
if (file_)
fclose(file_);
file_ = NULL;
}
bool DepsLog::Load(const string& path, State* state, string* err) {
METRIC_RECORD(".ninja_deps load");
char buf[32 << 10];
FILE* f = fopen(path.c_str(), "rb");
if (!f) {
if (errno == ENOENT)
return true;
*err = strerror(errno);
return false;
}
if (!fgets(buf, sizeof(buf), f)) {
*err = strerror(errno);
return false;
}
int version = 0;
if (fread(&version, 4, 1, f) < 1) {
*err = strerror(errno);
return false;
}
if (version != kCurrentVersion) {
*err = "bad deps log signature or version; starting over";
fclose(f);
unlink(path.c_str());
// Don't report this as a failure. An empty deps log will cause
// us to rebuild the outputs anyway.
return true;
}
for (;;) {
uint16_t size;
if (fread(&size, 2, 1, f) < 1)
break;
bool is_deps = (size >> 15) != 0;
size = size & 0x7FFF;
if (fread(buf, size, 1, f) < 1)
break;
if (is_deps) {
assert(size % 4 == 0);
int* deps_data = reinterpret_cast<int*>(buf);
int out_id = deps_data[0];
int mtime = deps_data[1];
deps_data += 2;
int deps_count = (size / 4) - 2;
Deps* deps = new Deps;
deps->mtime = mtime;
deps->node_count = deps_count;
deps->nodes = new Node*[deps_count];
for (int i = 0; i < deps_count; ++i) {
assert(deps_data[i] < (int)nodes_.size());
assert(nodes_[deps_data[i]]);
deps->nodes[i] = nodes_[deps_data[i]];
}
if (out_id >= (int)deps_.size())
deps_.resize(out_id + 1);
if (deps_[out_id]) {
++dead_record_count_;
delete deps_[out_id];
}
deps_[out_id] = deps;
} else {
StringPiece path(buf, size);
Node* node = state->GetNode(path);
assert(node->id() < 0);
node->set_id(nodes_.size());
nodes_.push_back(node);
}
}
if (ferror(f)) {
*err = strerror(ferror(f));
return false;
}
fclose(f);
return true;
}
DepsLog::Deps* DepsLog::GetDeps(Node* node) {
if (node->id() < 0)
return NULL;
return deps_[node->id()];
}
bool DepsLog::Recompact(const string& path, string* err) {
METRIC_RECORD(".ninja_deps recompact");
printf("Recompacting deps...\n");
string temp_path = path + ".recompact";
DepsLog new_log;
if (!new_log.OpenForWrite(temp_path, err))
return false;
// Clear all known ids so that new ones can be reassigned.
for (vector<Node*>::iterator i = nodes_.begin();
i != nodes_.end(); ++i) {
(*i)->set_id(-1);
}
// Write out all deps again.
for (int old_id = 0; old_id < (int)deps_.size(); ++old_id) {
Deps* deps = deps_[old_id];
if (!new_log.RecordDeps(nodes_[old_id], deps->mtime,
deps->node_count, deps->nodes)) {
new_log.Close();
return false;
}
}
new_log.Close();
if (unlink(path.c_str()) < 0) {
*err = strerror(errno);
return false;
}
if (rename(temp_path.c_str(), path.c_str()) < 0) {
*err = strerror(errno);
return false;
}
return true;
}
bool DepsLog::RecordId(Node* node) {
uint16_t size = (uint16_t)node->path().size();
fwrite(&size, 2, 1, file_);
fwrite(node->path().data(), node->path().size(), 1, file_);
node->set_id(nodes_.size());
nodes_.push_back(node);
return true;
}
<|endoftext|>
|
<commit_before>/**
* Copyright (c) Jason White
*
* MIT License
*/
#include <dirent.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <algorithm>
#include <utility>
#include "dircache.h"
#include "glob.h"
#include "path.h"
#include "deps.h"
using path::Path;
bool operator<(const DirEntry& a, const DirEntry& b) {
return std::tie(a.name, a.isDir) < std::tie(b.name, b.isDir);
}
namespace {
/**
* Returns a list of the files in a directory.
*/
DirEntries dirEntries(const std::string& path) {
DirEntries entries;
#ifdef _WIN32
// TODO: Implement on Windows. We'll need to convert between UTF-8 and
// UTF-16 when interacting with the Windows API.
# error Not implemented yet.
#else // _WIN32
DIR* dir = opendir(path.length() > 0 ? path.c_str() : ".");
if (!dir) return entries; // TODO: Throw exception instead
struct dirent* entry;
struct stat statbuf;
while ((entry = readdir(dir))) {
if (strcmp(entry->d_name, "." ) == 0 ||
strcmp(entry->d_name, "..") == 0) continue;
// Directory entry type is unknown. The file system is not required to
// provide this information. Thus, we need to figure it out by using
// stat.
if (entry->d_type == DT_UNKNOWN) {
if (fstatat(dirfd(dir), entry->d_name, &statbuf, 0) == 0) {
switch (statbuf.st_mode & S_IFMT) {
case S_IFIFO: entry->d_type = DT_FIFO; break;
case S_IFCHR: entry->d_type = DT_CHR; break;
case S_IFDIR: entry->d_type = DT_DIR; break;
case S_IFBLK: entry->d_type = DT_BLK; break;
case S_IFREG: entry->d_type = DT_REG; break;
case S_IFLNK: entry->d_type = DT_LNK; break;
case S_IFSOCK: entry->d_type = DT_SOCK; break;
}
}
}
entries.push_back(DirEntry { entry->d_name, entry->d_type == DT_DIR });
}
#endif // !_WIN32
// Sort the entries. The order in which directories are listed is not
// guaranteed to be deterministic.
std::sort(entries.begin(), entries.end());
return entries;
}
/**
* Returns true if the given string contains a glob pattern.
*/
bool isGlobPattern(Path p) {
for (size_t i = 0; i < p.length; ++i) {
switch (p.path[i]) {
case '?':
case '*':
case '[':
return true;
}
}
return false;
}
/**
* Returns true if the given path element is a recursive glob pattern.
*/
bool isRecursiveGlob(Path p) {
return p.length == 2 && p.path[0] == '*' && p.path[1] == '*';
}
struct GlobClosure {
// Directory listing cache.
DirCache* dirCache;
// Root directory we are globbing from.
Path root;
Path pattern;
// Next callback
GlobCallback next;
void* nextData;
};
void globCallback(Path path, bool isDir, void* data) {
if (isDir) {
const GlobClosure* c = (const GlobClosure*)data;
c->dirCache->glob(c->root, path, c->pattern, c->next, c->nextData);
}
}
}
/**
* Helper function for listing a directory with the given pattern. If the
* pattern is empty,
*/
void DirCache::glob(Path root, Path path, Path pattern,
GlobCallback callback, void* data) {
std::string buf(path.path, path.length);
if (pattern.length == 0) {
path::join(buf, pattern);
callback(Path(buf.data(), buf.size()), true, data);
return;
}
for (auto&& entry: dirEntries(root, path)) {
if (globMatch(entry.name, pattern)) {
path::join(buf, entry.name);
callback(Path(buf.data(), buf.size()), entry.isDir, data);
buf.assign(path.path, path.length);
}
}
}
/**
* Helper function to recursively yield directories for the given path.
*/
void DirCache::globRecursive(Path root, std::string& path,
GlobCallback callback, void* data) {
size_t len = path.size();
// "**" matches 0 or more directories and thus includes this one.
callback(Path(path.data(), path.size()), true, data);
for (auto&& entry: dirEntries(root, path)) {
path::join(path, entry.name);
callback(Path(path.data(), path.size()), entry.isDir, data);
if (entry.isDir)
globRecursive(root, path, callback, data);
path.resize(len);
}
}
/**
* Glob a directory.
*/
void DirCache::glob(Path root, Path path, GlobCallback callback, void* data) {
path::Split s = path::split(path);
if (isGlobPattern(s.head)) {
// Directory name contains a glob pattern
GlobClosure c;
c.dirCache = this;
c.root = root;
c.pattern = s.tail;
c.next = callback;
c.nextData = data;
glob(root, s.head, &globCallback, &c);
}
else if (isRecursiveGlob(s.tail)) {
std::string buf(s.head.path, s.head.length);
globRecursive(root, buf, callback, data);
}
else if (isGlobPattern(s.tail)) {
// Only base name contains a glob pattern.
glob(root, s.head, s.tail, callback, data);
}
else {
// No glob pattern in this path.
if (s.tail.length) {
// TODO: Only yield this path if the file exists.
callback(path, false, data);
}
else {
// TODO: Only yield this path if the directory exists.
callback(s.head, true, data);
}
}
}
DirCache::DirCache(ImplicitDeps* deps) : _deps(deps) {}
const DirEntries& DirCache::dirEntries(Path root, Path dir) {
std::string buf(root.path, root.length);
path::join(buf, dir);
return dirEntries(buf);
}
const DirEntries& DirCache::dirEntries(const std::string& path) {
// TODO: Normalize the input path.
// Did we already do the work?
const auto it = cache.find(path);
if (it != cache.end())
return it->second;
// TODO: Report dependency on this directory.
if (_deps) _deps->addInput(path.data(), path.length());
// List the directories, cache it, and return the cached list.
return cache.insert(
std::pair<std::string, DirEntries>(path, ::dirEntries(path))
).first->second;
}
<commit_msg>Clean up comments<commit_after>/**
* Copyright (c) Jason White
*
* MIT License
*/
#include <dirent.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <algorithm>
#include <utility>
#include "dircache.h"
#include "glob.h"
#include "path.h"
#include "deps.h"
using path::Path;
bool operator<(const DirEntry& a, const DirEntry& b) {
return std::tie(a.name, a.isDir) < std::tie(b.name, b.isDir);
}
namespace {
/**
* Returns a list of the files in a directory.
*/
DirEntries dirEntries(const std::string& path) {
DirEntries entries;
#ifdef _WIN32
// TODO: Implement on Windows. We'll need to convert between UTF-8 and
// UTF-16 when interacting with the Windows API.
# error Not implemented yet.
#else // _WIN32
DIR* dir = opendir(path.length() > 0 ? path.c_str() : ".");
if (!dir) return entries; // TODO: Throw exception instead
struct dirent* entry;
struct stat statbuf;
while ((entry = readdir(dir))) {
if (strcmp(entry->d_name, "." ) == 0 ||
strcmp(entry->d_name, "..") == 0) continue;
if (entry->d_type == DT_UNKNOWN) {
// Directory entry type is unknown. The file system is not required
// to provide this information. Thus, we need to figure it out by
// using stat.
if (fstatat(dirfd(dir), entry->d_name, &statbuf, 0) == 0) {
switch (statbuf.st_mode & S_IFMT) {
case S_IFIFO: entry->d_type = DT_FIFO; break;
case S_IFCHR: entry->d_type = DT_CHR; break;
case S_IFDIR: entry->d_type = DT_DIR; break;
case S_IFBLK: entry->d_type = DT_BLK; break;
case S_IFREG: entry->d_type = DT_REG; break;
case S_IFLNK: entry->d_type = DT_LNK; break;
case S_IFSOCK: entry->d_type = DT_SOCK; break;
}
}
}
entries.push_back(DirEntry { entry->d_name, entry->d_type == DT_DIR });
}
#endif // !_WIN32
// Sort the entries. The order in which directories are listed is not
// guaranteed to be deterministic.
std::sort(entries.begin(), entries.end());
return entries;
}
/**
* Returns true if the given string contains a glob pattern.
*/
bool isGlobPattern(Path p) {
for (size_t i = 0; i < p.length; ++i) {
switch (p.path[i]) {
case '?':
case '*':
case '[':
return true;
}
}
return false;
}
/**
* Returns true if the given path element is a recursive glob pattern.
*/
bool isRecursiveGlob(Path p) {
return p.length == 2 && p.path[0] == '*' && p.path[1] == '*';
}
struct GlobClosure {
// Directory listing cache.
DirCache* dirCache;
// Root directory we are globbing from.
Path root;
Path pattern;
// Next callback
GlobCallback next;
void* nextData;
};
void globCallback(Path path, bool isDir, void* data) {
if (isDir) {
const GlobClosure* c = (const GlobClosure*)data;
c->dirCache->glob(c->root, path, c->pattern, c->next, c->nextData);
}
}
}
/**
* Helper function for listing a directory with the given pattern. If the
* pattern is empty,
*/
void DirCache::glob(Path root, Path path, Path pattern,
GlobCallback callback, void* data) {
std::string buf(path.path, path.length);
if (pattern.length == 0) {
path::join(buf, pattern);
callback(Path(buf.data(), buf.size()), true, data);
return;
}
for (auto&& entry: dirEntries(root, path)) {
if (globMatch(entry.name, pattern)) {
path::join(buf, entry.name);
callback(Path(buf.data(), buf.size()), entry.isDir, data);
buf.assign(path.path, path.length);
}
}
}
/**
* Helper function to recursively yield directories for the given path.
*/
void DirCache::globRecursive(Path root, std::string& path,
GlobCallback callback, void* data) {
size_t len = path.size();
// "**" matches 0 or more directories and thus includes this one.
callback(Path(path.data(), path.size()), true, data);
for (auto&& entry: dirEntries(root, path)) {
path::join(path, entry.name);
callback(Path(path.data(), path.size()), entry.isDir, data);
if (entry.isDir)
globRecursive(root, path, callback, data);
path.resize(len);
}
}
/**
* Glob a directory.
*/
void DirCache::glob(Path root, Path path, GlobCallback callback, void* data) {
path::Split s = path::split(path);
if (isGlobPattern(s.head)) {
// Directory name contains a glob pattern
GlobClosure c;
c.dirCache = this;
c.root = root;
c.pattern = s.tail;
c.next = callback;
c.nextData = data;
glob(root, s.head, &globCallback, &c);
}
else if (isRecursiveGlob(s.tail)) {
std::string buf(s.head.path, s.head.length);
globRecursive(root, buf, callback, data);
}
else if (isGlobPattern(s.tail)) {
// Only base name contains a glob pattern.
glob(root, s.head, s.tail, callback, data);
}
else {
// No glob pattern in this path.
if (s.tail.length) {
// TODO: Only yield this path if the file exists.
callback(path, false, data);
}
else {
// TODO: Only yield this path if the directory exists.
callback(s.head, true, data);
}
}
}
DirCache::DirCache(ImplicitDeps* deps) : _deps(deps) {}
const DirEntries& DirCache::dirEntries(Path root, Path dir) {
std::string buf(root.path, root.length);
path::join(buf, dir);
return dirEntries(buf);
}
const DirEntries& DirCache::dirEntries(const std::string& path) {
// TODO: Normalize the input path.
// Did we already do the work?
const auto it = cache.find(path);
if (it != cache.end())
return it->second;
if (_deps) _deps->addInput(path.data(), path.length());
// List the directories, cache it, and return the cached list.
return cache.insert(
std::pair<std::string, DirEntries>(path, ::dirEntries(path))
).first->second;
}
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.