text stringlengths 54 60.6k |
|---|
<commit_before>#include "cvd/internal/io/png.h"
#include "cvd/image_io.h"
#include "cvd/config.h"
#include <png.h>
#include <cstdlib>
using namespace CVD;
using namespace CVD::Exceptions;
using namespace CVD::Exceptions::Image_IO;
using namespace PNG;
using namespace std;
////////////////////////////////////////////////////////////////////////////////
//
// C++ istreams based I/O functions
//
static void error_fn(png_structp png_ptr, png_const_charp error_msg)
{
*(string*)(png_ptr->error_ptr) = error_msg;
}
static void warn_fn(png_structp, png_const_charp )
{
}
static void read_fn(png_structp png_ptr, unsigned char* data, size_t numbytes)
{
istream* i = (istream*)png_get_io_ptr(png_ptr);
i->read((char*) data, numbytes);
//What to do on stream failure?
//There is no return value, and I do not know if longjmp is safe here.
//Anyway, multiple rereads of the data will cause the PNG read
//to fail because it has internal checksums
}
static void write_fn(png_structp png_ptr, unsigned char* data, size_t numbytes)
{
ostream* o = (ostream*)png_get_io_ptr(png_ptr);
o->write((char*) data, numbytes);
}
static void flush_fn(png_structp png_ptr)
{
ostream* o = (ostream*)png_get_io_ptr(png_ptr);
(*o) << flush;
}
////////////////////////////////////////////////////////////////////////////////
//
// PNG reading functions
//
string png_reader::datatype()
{
return type;
}
string png_reader::name()
{
return "PNG";
}
ImageRef png_reader::size()
{
return my_size;
}
//Mechanically generate the pixel reading calls.
#define GEN1(X) void png_reader::get_raw_pixel_line(X*d){read_pixels(d);}
#define GEN3(X) GEN1(X) GEN1(Rgb<X>) GEN1(Rgba<X>)
GEN1(bool)
GEN3(unsigned char)
GEN3(unsigned short)
template<class P> void png_reader::read_pixels(P* data)
{
if(datatype() != PNM::type_name<P>::name())
throw ReadTypeMismatch(datatype(), PNM::type_name<P>::name());
if(row > (unsigned long)my_size.y)
throw InternalLibraryError("CVD", "Read past end of image.");
if(setjmp(png_jmpbuf(png_ptr)))
throw Exceptions::Image_IO::MalformedImage(error_string);
unsigned char* cptr = reinterpret_cast<unsigned char*>(data);
unsigned char** row_ptr = &cptr;
png_read_rows(png_ptr, row_ptr, NULL, 1);
}
png_reader::png_reader(std::istream& in)
:i(in),type(""),row(0),png_ptr(0),info_ptr(0),end_info(0)
{
//Read the header and make sure it really is a PNG...
unsigned char header[8];
in.read((char*)header, 8);
if(png_sig_cmp(header, 0, 8))
throw Exceptions::Image_IO::MalformedImage("Not a PNG image");
png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if(!png_ptr)
throw Exceptions::OutOfMemory();
info_ptr = png_create_info_struct(png_ptr);
if(!info_ptr)
{
png_destroy_read_struct(&png_ptr, NULL, NULL);
throw Exceptions::OutOfMemory();
}
end_info = png_create_info_struct(png_ptr);
if(!info_ptr)
{
png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
throw Exceptions::OutOfMemory();
}
if(setjmp(png_jmpbuf(png_ptr)))
{
png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
throw Exceptions::Image_IO::MalformedImage(error_string);
}
png_set_error_fn(png_ptr, &error_string, error_fn, warn_fn);
//png_init_io(png_ptr, stdin);
png_set_read_fn(png_ptr, &i, read_fn);
png_set_sig_bytes(png_ptr, 8);
png_read_info(png_ptr, info_ptr);
png_uint_32 w, h;
int colour, interlace, dummy, depth;
png_get_IHDR(png_ptr, info_ptr, &w, &h, &depth, &colour, &interlace, &dummy, &dummy);
my_size.x = w;
my_size.y = h;
//Figure out the type name, and what processing to to.
if(depth == 1)
{
//Unpack bools to bytes to ease loading.
png_set_packing(png_ptr);
type = PNM::type_name<bool>::name();
}
else if(depth <= 8)
{
//Expand nonbool colour depths up to 8bpp
if(depth < 8)
png_set_gray_1_2_4_to_8(png_ptr);
type = PNM::type_name<unsigned char>::name();
}
else
type = PNM::type_name<unsigned short>::name();
if(colour & PNG_COLOR_MASK_COLOR)
if(colour & PNG_COLOR_MASK_ALPHA)
type = "CVD::Rgba<" + type + ">";
else
type = "CVD::Rgb<" + type + ">";
else
if(colour & PNG_COLOR_MASK_ALPHA)
type = "CVD::GreyAlpha<" + type + ">";
else
type = type;
//Get rid of palette, by transforming it to RGB
if(colour == PNG_COLOR_TYPE_PALETTE)
png_set_palette_to_rgb(png_ptr);
if(interlace != PNG_INTERLACE_NONE)
throw Exceptions::Image_IO::UnsupportedImageSubType("PNG", "Interlace not yet supported");
#ifdef CVD_ARCH_LITTLE_ENDIAN
if(depth == 16)
png_set_swap(png_ptr);
#endif
}
png_reader::~png_reader()
{
//Clear the stream of any remaining PNG bits.
//It doesn't matter if there's an error here
if(!setjmp(png_jmpbuf(png_ptr)))
png_read_end(png_ptr, end_info);
//Destroy all PNG structs
png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
}
////////////////////////////////////////////////////////////////////////////////
//
// PNG writing functions.
//
png_writer::png_writer(ostream& out, ImageRef sz, const string& type_)
:row(0),o(out),size(sz),type(type_)
{
//Create required structs
png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, &error_string, error_fn, warn_fn);
if(!png_ptr)
throw Exceptions::OutOfMemory();
info_ptr = png_create_info_struct(png_ptr);
if (!info_ptr)
{
png_destroy_write_struct(&png_ptr,NULL);
throw Exceptions::OutOfMemory();
}
//Set up error handling
if(setjmp(png_jmpbuf(png_ptr)))
{
png_destroy_write_struct(&png_ptr, &info_ptr);
throw Exceptions::Image_IO::MalformedImage(error_string);
}
//Set up stream IO
png_set_write_fn(png_ptr, &o, write_fn, flush_fn);
int c_type=0;
int depth=0;
if(type == "bool")
{
c_type = PNG_COLOR_TYPE_GRAY;
depth=1;
}
else if(type == "unsigned char")
{
c_type = PNG_COLOR_TYPE_GRAY;
depth=8;
}
else if(type == "unsigned short")
{
c_type = PNG_COLOR_TYPE_GRAY;
depth=16;
}
else if(type == "CVD::Rgb<unsigned char>")
{
c_type = PNG_COLOR_TYPE_RGB;
depth=8;
}
else if(type == "CVD::Rgb8")
{
c_type = PNG_COLOR_TYPE_RGB;
depth=8;
//Note the existence of meaningless filler.
png_set_filler(png_ptr, 0, PNG_FILLER_AFTER);
}
else if(type == "CVD::Rgb<unsigned short>")
{
c_type = PNG_COLOR_TYPE_RGB;
depth=16;
}
else if(type == "CVD::Rgba<unsigned char>")
{
c_type = PNG_COLOR_TYPE_RGB_ALPHA;
depth = 8;
}
else if(type == "CVD::Rgba<unsigned short>")
{
c_type = PNG_COLOR_TYPE_RGB_ALPHA;
depth = 16;
}
else
throw UnsupportedImageSubType("TIFF", type);
//Set up the image type
png_set_IHDR(png_ptr, info_ptr, size.x, size.y, depth, c_type, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
//Write the header
png_write_info(png_ptr, info_ptr);
//Write the transformations
#ifdef CVD_ARCH_LITTLE_ENDIAN
if (depth == 16)
png_set_swap(png_ptr);
#endif
//Pack from C++ bools to packed PNG bools
//This has to be done _after_ writing the info struct.
if(type == "bool")
png_set_packing(png_ptr);
}
//Mechanically generate the pixel writing calls.
#undef GEN1
#undef GEN3
#define GEN1(X) void png_writer::write_raw_pixel_line(const X*d){write_line(d);}
#define GEN3(X) GEN1(X) GEN1(Rgb<X>) GEN1(Rgba<X>)
GEN1(bool)
GEN1(Rgb8)
GEN3(unsigned char)
GEN3(unsigned short)
template<class P> void png_writer::write_line(const P* data)
{
unsigned char* chardata = const_cast<unsigned char*>(reinterpret_cast<const unsigned char*>(data));
//Do some type checking
if(type != PNM::type_name<P>::name())
throw WriteTypeMismatch(type, PNM::type_name<P>::name());
//Set up error handling
if(setjmp(png_jmpbuf(png_ptr)))
throw Exceptions::Image_IO::MalformedImage(error_string);
//Do some sanity checking
if(row > size.y)
throw InternalLibraryError("CVD", "Write past end of image.");
unsigned char** row_ptr = & chardata;
png_write_rows(png_ptr, row_ptr, 1);
row++;
}
png_writer::~png_writer()
{
png_write_end(png_ptr, info_ptr);
png_destroy_write_struct(&png_ptr, &info_ptr);
}
<commit_msg>Throw write error, rather than read error exceptions if writing fails.<commit_after>#include "cvd/internal/io/png.h"
#include "cvd/image_io.h"
#include "cvd/config.h"
#include <png.h>
#include <cstdlib>
using namespace CVD;
using namespace CVD::Exceptions;
using namespace CVD::Exceptions::Image_IO;
using namespace PNG;
using namespace std;
////////////////////////////////////////////////////////////////////////////////
//
// C++ istreams based I/O functions
//
static void error_fn(png_structp png_ptr, png_const_charp error_msg)
{
*(string*)(png_ptr->error_ptr) = error_msg;
}
static void warn_fn(png_structp, png_const_charp )
{
}
static void read_fn(png_structp png_ptr, unsigned char* data, size_t numbytes)
{
istream* i = (istream*)png_get_io_ptr(png_ptr);
i->read((char*) data, numbytes);
//What to do on stream failure?
//There is no return value, and I do not know if longjmp is safe here.
//Anyway, multiple rereads of the data will cause the PNG read
//to fail because it has internal checksums
}
static void write_fn(png_structp png_ptr, unsigned char* data, size_t numbytes)
{
ostream* o = (ostream*)png_get_io_ptr(png_ptr);
o->write((char*) data, numbytes);
}
static void flush_fn(png_structp png_ptr)
{
ostream* o = (ostream*)png_get_io_ptr(png_ptr);
(*o) << flush;
}
////////////////////////////////////////////////////////////////////////////////
//
// PNG reading functions
//
string png_reader::datatype()
{
return type;
}
string png_reader::name()
{
return "PNG";
}
ImageRef png_reader::size()
{
return my_size;
}
//Mechanically generate the pixel reading calls.
#define GEN1(X) void png_reader::get_raw_pixel_line(X*d){read_pixels(d);}
#define GEN3(X) GEN1(X) GEN1(Rgb<X>) GEN1(Rgba<X>)
GEN1(bool)
GEN3(unsigned char)
GEN3(unsigned short)
template<class P> void png_reader::read_pixels(P* data)
{
if(datatype() != PNM::type_name<P>::name())
throw ReadTypeMismatch(datatype(), PNM::type_name<P>::name());
if(row > (unsigned long)my_size.y)
throw InternalLibraryError("CVD", "Read past end of image.");
if(setjmp(png_jmpbuf(png_ptr)))
throw Exceptions::Image_IO::MalformedImage(error_string);
unsigned char* cptr = reinterpret_cast<unsigned char*>(data);
unsigned char** row_ptr = &cptr;
png_read_rows(png_ptr, row_ptr, NULL, 1);
}
png_reader::png_reader(std::istream& in)
:i(in),type(""),row(0),png_ptr(0),info_ptr(0),end_info(0)
{
//Read the header and make sure it really is a PNG...
unsigned char header[8];
in.read((char*)header, 8);
if(png_sig_cmp(header, 0, 8))
throw Exceptions::Image_IO::MalformedImage("Not a PNG image");
png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if(!png_ptr)
throw Exceptions::OutOfMemory();
info_ptr = png_create_info_struct(png_ptr);
if(!info_ptr)
{
png_destroy_read_struct(&png_ptr, NULL, NULL);
throw Exceptions::OutOfMemory();
}
end_info = png_create_info_struct(png_ptr);
if(!info_ptr)
{
png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
throw Exceptions::OutOfMemory();
}
if(setjmp(png_jmpbuf(png_ptr)))
{
png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
throw Exceptions::Image_IO::MalformedImage(error_string);
}
png_set_error_fn(png_ptr, &error_string, error_fn, warn_fn);
//png_init_io(png_ptr, stdin);
png_set_read_fn(png_ptr, &i, read_fn);
png_set_sig_bytes(png_ptr, 8);
png_read_info(png_ptr, info_ptr);
png_uint_32 w, h;
int colour, interlace, dummy, depth;
png_get_IHDR(png_ptr, info_ptr, &w, &h, &depth, &colour, &interlace, &dummy, &dummy);
my_size.x = w;
my_size.y = h;
//Figure out the type name, and what processing to to.
if(depth == 1)
{
//Unpack bools to bytes to ease loading.
png_set_packing(png_ptr);
type = PNM::type_name<bool>::name();
}
else if(depth <= 8)
{
//Expand nonbool colour depths up to 8bpp
if(depth < 8)
png_set_gray_1_2_4_to_8(png_ptr);
type = PNM::type_name<unsigned char>::name();
}
else
type = PNM::type_name<unsigned short>::name();
if(colour & PNG_COLOR_MASK_COLOR)
if(colour & PNG_COLOR_MASK_ALPHA)
type = "CVD::Rgba<" + type + ">";
else
type = "CVD::Rgb<" + type + ">";
else
if(colour & PNG_COLOR_MASK_ALPHA)
type = "CVD::GreyAlpha<" + type + ">";
else
type = type;
//Get rid of palette, by transforming it to RGB
if(colour == PNG_COLOR_TYPE_PALETTE)
png_set_palette_to_rgb(png_ptr);
if(interlace != PNG_INTERLACE_NONE)
throw Exceptions::Image_IO::UnsupportedImageSubType("PNG", "Interlace not yet supported");
#ifdef CVD_ARCH_LITTLE_ENDIAN
if(depth == 16)
png_set_swap(png_ptr);
#endif
}
png_reader::~png_reader()
{
//Clear the stream of any remaining PNG bits.
//It doesn't matter if there's an error here
if(!setjmp(png_jmpbuf(png_ptr)))
png_read_end(png_ptr, end_info);
//Destroy all PNG structs
png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
}
////////////////////////////////////////////////////////////////////////////////
//
// PNG writing functions.
//
png_writer::png_writer(ostream& out, ImageRef sz, const string& type_)
:row(0),o(out),size(sz),type(type_)
{
//Create required structs
png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, &error_string, error_fn, warn_fn);
if(!png_ptr)
throw Exceptions::OutOfMemory();
info_ptr = png_create_info_struct(png_ptr);
if (!info_ptr)
{
png_destroy_write_struct(&png_ptr,NULL);
throw Exceptions::OutOfMemory();
}
//Set up error handling
if(setjmp(png_jmpbuf(png_ptr)))
{
png_destroy_write_struct(&png_ptr, &info_ptr);
throw Exceptions::Image_IO::WriteError(error_string);
}
//Set up stream IO
png_set_write_fn(png_ptr, &o, write_fn, flush_fn);
int c_type=0;
int depth=0;
if(type == "bool")
{
c_type = PNG_COLOR_TYPE_GRAY;
depth=1;
}
else if(type == "unsigned char")
{
c_type = PNG_COLOR_TYPE_GRAY;
depth=8;
}
else if(type == "unsigned short")
{
c_type = PNG_COLOR_TYPE_GRAY;
depth=16;
}
else if(type == "CVD::Rgb<unsigned char>")
{
c_type = PNG_COLOR_TYPE_RGB;
depth=8;
}
else if(type == "CVD::Rgb8")
{
c_type = PNG_COLOR_TYPE_RGB;
depth=8;
//Note the existence of meaningless filler.
png_set_filler(png_ptr, 0, PNG_FILLER_AFTER);
}
else if(type == "CVD::Rgb<unsigned short>")
{
c_type = PNG_COLOR_TYPE_RGB;
depth=16;
}
else if(type == "CVD::Rgba<unsigned char>")
{
c_type = PNG_COLOR_TYPE_RGB_ALPHA;
depth = 8;
}
else if(type == "CVD::Rgba<unsigned short>")
{
c_type = PNG_COLOR_TYPE_RGB_ALPHA;
depth = 16;
}
else
throw UnsupportedImageSubType("TIFF", type);
//Set up the image type
png_set_IHDR(png_ptr, info_ptr, size.x, size.y, depth, c_type, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
//Write the header
png_write_info(png_ptr, info_ptr);
//Write the transformations
#ifdef CVD_ARCH_LITTLE_ENDIAN
if (depth == 16)
png_set_swap(png_ptr);
#endif
//Pack from C++ bools to packed PNG bools
//This has to be done _after_ writing the info struct.
if(type == "bool")
png_set_packing(png_ptr);
}
//Mechanically generate the pixel writing calls.
#undef GEN1
#undef GEN3
#define GEN1(X) void png_writer::write_raw_pixel_line(const X*d){write_line(d);}
#define GEN3(X) GEN1(X) GEN1(Rgb<X>) GEN1(Rgba<X>)
GEN1(bool)
GEN1(Rgb8)
GEN3(unsigned char)
GEN3(unsigned short)
template<class P> void png_writer::write_line(const P* data)
{
unsigned char* chardata = const_cast<unsigned char*>(reinterpret_cast<const unsigned char*>(data));
//Do some type checking
if(type != PNM::type_name<P>::name())
throw WriteTypeMismatch(type, PNM::type_name<P>::name());
//Set up error handling
if(setjmp(png_jmpbuf(png_ptr)))
throw Exceptions::Image_IO::WriteError(error_string);
//Do some sanity checking
if(row > size.y)
throw InternalLibraryError("CVD", "Write past end of image.");
unsigned char** row_ptr = & chardata;
png_write_rows(png_ptr, row_ptr, 1);
row++;
}
png_writer::~png_writer()
{
png_write_end(png_ptr, info_ptr);
png_destroy_write_struct(&png_ptr, &info_ptr);
}
<|endoftext|> |
<commit_before>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2012 Scientific Computing and Imaging Institute,
University of Utah.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
/**
\brief A Lua class proxy for IO's TransferFunction2D class.
*/
#include <vector>
#include "Controller/Controller.h"
#include "3rdParty/LUA/lua.hpp"
#include "../LuaScripting.h"
#include "../LuaClassRegistration.h"
#include "LuaTuvokTypes.h"
#include "LuaTransferFun2DProxy.h"
using namespace tuvok;
//------------------------------------------------------------------------------
LuaTransferFun2DProxy::LuaTransferFun2DProxy()
: mReg(NULL),
m2DTrans(NULL)
{
}
//------------------------------------------------------------------------------
LuaTransferFun2DProxy::~LuaTransferFun2DProxy()
{
if (mReg != NULL)
delete mReg;
}
//------------------------------------------------------------------------------
void LuaTransferFun2DProxy::bind(TransferFunction2D* tf)
{
if (mReg == NULL)
throw LuaError("Unable to bind transfer function 2D , no class registration"
" available.");
mReg->clearProxyFunctions();
m2DTrans = tf;
if (tf != NULL)
{
// Register TransferFunction2D functions using tf.
std::string id;
/// @todo Determine which of the following functions should have provenance
/// enabled.
id = mReg->functionProxy(tf, &TransferFunction2D::SwatchArrayGetSize,
"swatchGetCount", "", false);
id = mReg->functionProxy(tf, &TransferFunction2D::SwatchPushBack,
"swatchPushBack", "", false);
id = mReg->functionProxy(tf, &TransferFunction2D::SwatchErase,
"swatchErase", "", false);
id = mReg->functionProxy(tf, &TransferFunction2D::SwatchInsert,
"swatchInsert", "", false);
id = mReg->functionProxy(tf, &TransferFunction2D::SwatchUpdate,
"swatchUpdate", "", false);
id = mReg->functionProxy(tf, &TransferFunction2D::SwatchIsRadial,
"swatchIsRadial", "", false);
id = mReg->functionProxy(tf, &TransferFunction2D::SwatchGetNumPoints,
"swatchGetNumPoints", "", false);
id = mReg->functionProxy(tf, &TransferFunction2D::SwatchGetGradientCount,
"swatchGetGradientCount", "", false);
id = mReg->functionProxy(tf, &TransferFunction2D::SwatchGetGradient,
"swatchGetGradient", "", false);
}
}
//------------------------------------------------------------------------------
void LuaTransferFun2DProxy::defineLuaInterface(
LuaClassRegistration<LuaTransferFun2DProxy>& reg,
LuaTransferFun2DProxy* me,
LuaScripting*)
{
me->mReg = new LuaClassRegistration<LuaTransferFun2DProxy>(reg);
/// @todo Determine if the following function should be provenance enabled.
//reg.function(&LuaTransferFun2DProxy::proxyLoadWithFilenameAndSize,
// "loadFromFileWithSize", "Loads 'file' into the 2D "
// " transfer function with 'size'.", false);
}
<commit_msg>Exposed 3 more 2D transfer function methods.<commit_after>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2012 Scientific Computing and Imaging Institute,
University of Utah.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
/**
\brief A Lua class proxy for IO's TransferFunction2D class.
*/
#include <vector>
#include "Controller/Controller.h"
#include "3rdParty/LUA/lua.hpp"
#include "../LuaScripting.h"
#include "../LuaClassRegistration.h"
#include "LuaTuvokTypes.h"
#include "LuaTransferFun2DProxy.h"
using namespace tuvok;
//------------------------------------------------------------------------------
LuaTransferFun2DProxy::LuaTransferFun2DProxy()
: mReg(NULL),
m2DTrans(NULL)
{
}
//------------------------------------------------------------------------------
LuaTransferFun2DProxy::~LuaTransferFun2DProxy()
{
if (mReg != NULL)
delete mReg;
}
//------------------------------------------------------------------------------
void LuaTransferFun2DProxy::bind(TransferFunction2D* tf)
{
if (mReg == NULL)
throw LuaError("Unable to bind transfer function 2D , no class registration"
" available.");
mReg->clearProxyFunctions();
m2DTrans = tf;
if (tf != NULL)
{
// Register TransferFunction2D functions using tf.
std::string id;
/// @todo Determine which of the following functions should have provenance
/// enabled.
id = mReg->functionProxy(tf, &TransferFunction2D::SwatchArrayGetSize,
"swatchGetCount", "", false);
id = mReg->functionProxy(tf, &TransferFunction2D::SwatchPushBack,
"swatchPushBack", "", false);
id = mReg->functionProxy(tf, &TransferFunction2D::SwatchErase,
"swatchErase", "", false);
id = mReg->functionProxy(tf, &TransferFunction2D::SwatchInsert,
"swatchInsert", "", false);
id = mReg->functionProxy(tf, &TransferFunction2D::SwatchUpdate,
"swatchUpdate", "", false);
id = mReg->functionProxy(tf, &TransferFunction2D::SwatchIsRadial,
"swatchIsRadial", "", false);
id = mReg->functionProxy(tf, &TransferFunction2D::SwatchGetNumPoints,
"swatchGetNumPoints", "", false);
id = mReg->functionProxy(tf, &TransferFunction2D::SwatchErasePoint,
"swatchErasePoint", "", false);
id = mReg->functionProxy(tf, &TransferFunction2D::SwatchInsertPoint,
"swatchInsertPoint", "", false);
id = mReg->functionProxy(tf, &TransferFunction2D::SwatchGetGradientCount,
"swatchGetGradientCount", "", false);
id = mReg->functionProxy(tf, &TransferFunction2D::SwatchGetGradient,
"swatchGetGradient", "", false);
id = mReg->functionProxy(tf, &TransferFunction2D::SwatchGet,
"swatchGet", "", false);
}
}
//------------------------------------------------------------------------------
void LuaTransferFun2DProxy::defineLuaInterface(
LuaClassRegistration<LuaTransferFun2DProxy>& reg,
LuaTransferFun2DProxy* me,
LuaScripting*)
{
me->mReg = new LuaClassRegistration<LuaTransferFun2DProxy>(reg);
/// @todo Determine if the following function should be provenance enabled.
//reg.function(&LuaTransferFun2DProxy::proxyLoadWithFilenameAndSize,
// "loadFromFileWithSize", "Loads 'file' into the 2D "
// " transfer function with 'size'.", false);
}
<|endoftext|> |
<commit_before>// The libMesh Finite Element Library.
// Copyright (C) 2002-2016 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// 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
// Local includes
#include "libmesh/elem.h"
#include "libmesh/fe.h"
#include "libmesh/fe_interface.h"
#include "libmesh/string_to_enum.h"
namespace libMesh
{
// ------------------------------------------------------------
// Hierarchic-specific implementations
// Anonymous namespace for local helper functions
namespace {
void hierarchic_nodal_soln(const Elem * elem,
const Order order,
const std::vector<Number> & elem_soln,
std::vector<Number> & nodal_soln,
unsigned Dim)
{
const unsigned int n_nodes = elem->n_nodes();
const ElemType elem_type = elem->type();
nodal_soln.resize(n_nodes);
const Order totalorder = static_cast<Order>(order + elem->p_level());
// FEType object to be passed to various FEInterface functions below.
FEType fe_type(totalorder, HIERARCHIC);
switch (totalorder)
{
// Constant shape functions
case CONSTANT:
{
libmesh_assert_equal_to (elem_soln.size(), 1);
const Number val = elem_soln[0];
for (unsigned int n=0; n<n_nodes; n++)
nodal_soln[n] = val;
return;
}
// For other orders do interpolation at the nodes
// explicitly.
default:
{
const unsigned int n_sf =
// FE<Dim,T>::n_shape_functions(elem_type, totalorder);
FEInterface::n_shape_functions(Dim, fe_type, elem_type);
std::vector<Point> refspace_nodes;
FEBase::get_refspace_nodes(elem_type,refspace_nodes);
libmesh_assert_equal_to (refspace_nodes.size(), n_nodes);
for (unsigned int n=0; n<n_nodes; n++)
{
libmesh_assert_equal_to (elem_soln.size(), n_sf);
// Zero before summation
nodal_soln[n] = 0;
// u_i = Sum (alpha_i phi_i)
for (unsigned int i=0; i<n_sf; i++)
nodal_soln[n] += elem_soln[i] *
// FE<Dim,T>::shape(elem, order, i, mapped_point);
FEInterface::shape(Dim, fe_type, elem, i, refspace_nodes[n]);
}
return;
}
}
} // hierarchic_nodal_soln()
unsigned int hierarchic_n_dofs(const ElemType t, const Order o)
{
libmesh_assert_greater (o, 0);
switch (t)
{
case NODEELEM:
return 1;
case EDGE2:
case EDGE3:
return (o+1);
case QUAD4:
case QUADSHELL4:
libmesh_assert_less (o, 2);
case QUAD8:
case QUAD9:
return ((o+1)*(o+1));
case HEX8:
libmesh_assert_less (o, 2);
case HEX20:
libmesh_assert_less (o, 2);
case HEX27:
return ((o+1)*(o+1)*(o+1));
case TRI6:
return ((o+1)*(o+2)/2);
case INVALID_ELEM:
return 0;
default:
libmesh_error_msg("ERROR: Invalid ElemType " << Utility::enum_to_string(t) << " selected for HIERARCHIC FE family!");
}
libmesh_error_msg("We'll never get here!");
return 0;
} // hierarchic_n_dofs()
unsigned int hierarchic_n_dofs_at_node(const ElemType t,
const Order o,
const unsigned int n)
{
libmesh_assert_greater (o, 0);
switch (t)
{
case NODEELEM:
return 1;
case EDGE2:
case EDGE3:
switch (n)
{
case 0:
case 1:
return 1;
// Internal DoFs are associated with the elem, not its nodes
case 2:
return 0;
default:
libmesh_error_msg("ERROR: Invalid node ID " << n << " selected for EDGE2/3!");
}
case TRI6:
switch (n)
{
case 0:
case 1:
case 2:
return 1;
case 3:
case 4:
case 5:
return (o-1);
// Internal DoFs are associated with the elem, not its nodes
default:
libmesh_error_msg("ERROR: Invalid node ID " << n << " selected for TRI6!");
}
case QUAD4:
case QUADSHELL4:
libmesh_assert_less (n, 4);
libmesh_assert_less (o, 2);
case QUAD8:
case QUAD9:
switch (n)
{
case 0:
case 1:
case 2:
case 3:
return 1;
case 4:
case 5:
case 6:
case 7:
return (o-1);
// Internal DoFs are associated with the elem, not its nodes
case 8:
return 0;
default:
libmesh_error_msg("ERROR: Invalid node ID " << n << " selected for QUAD4/8/9!");
}
case HEX8:
libmesh_assert_less (n, 8);
libmesh_assert_less (o, 2);
case HEX20:
libmesh_assert_less (n, 20);
libmesh_assert_less (o, 2);
case HEX27:
switch (n)
{
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
return 1;
case 8:
case 9:
case 10:
case 11:
case 12:
case 13:
case 14:
case 15:
case 16:
case 17:
case 18:
case 19:
return (o-1);
case 20:
case 21:
case 22:
case 23:
case 24:
case 25:
return ((o-1)*(o-1));
// Internal DoFs are associated with the elem, not its nodes
case 26:
return 0;
default:
libmesh_error_msg("ERROR: Invalid node ID " << n << " selected for HEX8/20/27!");
}
case INVALID_ELEM:
return 0;
default:
libmesh_error_msg("ERROR: Bad ElemType = " << Utility::enum_to_string(t) << " for " << Utility::enum_to_string(o) << " order approximation!");
}
libmesh_error_msg("We'll never get here!");
return 0;
} // hierarchic_n_dofs_at_node()
unsigned int hierarchic_n_dofs_per_elem(const ElemType t,
const Order o)
{
libmesh_assert_greater (o, 0);
switch (t)
{
case NODEELEM:
return 0;
case EDGE2:
case EDGE3:
return (o-1);
case TRI3:
case TRISHELL3:
case QUAD4:
case QUADSHELL4:
return 0;
case TRI6:
return ((o-1)*(o-2)/2);
case QUAD8:
case QUAD9:
return ((o-1)*(o-1));
case HEX8:
case HEX20:
libmesh_assert_less (o, 2);
return 0;
case HEX27:
return ((o-1)*(o-1)*(o-1));
case INVALID_ELEM:
return 0;
default:
libmesh_error_msg("ERROR: Bad ElemType = " << Utility::enum_to_string(t) << " for " << Utility::enum_to_string(o) << " order approximation!");
}
libmesh_error_msg("We'll never get here!");
return 0;
} // hierarchic_n_dofs_per_elem()
} // anonymous namespace
// Do full-specialization of nodal_soln() function for every
// dimension, instead of explicit instantiation at the end of this
// file.
// This could be macro-ified so that it fits on one line...
template <>
void FE<0,HIERARCHIC>::nodal_soln(const Elem * elem,
const Order order,
const std::vector<Number> & elem_soln,
std::vector<Number> & nodal_soln)
{ hierarchic_nodal_soln(elem, order, elem_soln, nodal_soln, /*Dim=*/0); }
template <>
void FE<1,HIERARCHIC>::nodal_soln(const Elem * elem,
const Order order,
const std::vector<Number> & elem_soln,
std::vector<Number> & nodal_soln)
{ hierarchic_nodal_soln(elem, order, elem_soln, nodal_soln, /*Dim=*/1); }
template <>
void FE<2,HIERARCHIC>::nodal_soln(const Elem * elem,
const Order order,
const std::vector<Number> & elem_soln,
std::vector<Number> & nodal_soln)
{ hierarchic_nodal_soln(elem, order, elem_soln, nodal_soln, /*Dim=*/2); }
template <>
void FE<3,HIERARCHIC>::nodal_soln(const Elem * elem,
const Order order,
const std::vector<Number> & elem_soln,
std::vector<Number> & nodal_soln)
{ hierarchic_nodal_soln(elem, order, elem_soln, nodal_soln, /*Dim=*/3); }
// Full specialization of n_dofs() function for every dimension
template <> unsigned int FE<0,HIERARCHIC>::n_dofs(const ElemType t, const Order o) { return hierarchic_n_dofs(t, o); }
template <> unsigned int FE<1,HIERARCHIC>::n_dofs(const ElemType t, const Order o) { return hierarchic_n_dofs(t, o); }
template <> unsigned int FE<2,HIERARCHIC>::n_dofs(const ElemType t, const Order o) { return hierarchic_n_dofs(t, o); }
template <> unsigned int FE<3,HIERARCHIC>::n_dofs(const ElemType t, const Order o) { return hierarchic_n_dofs(t, o); }
// Full specialization of n_dofs_at_node() function for every dimension.
template <> unsigned int FE<0,HIERARCHIC>::n_dofs_at_node(const ElemType t, const Order o, const unsigned int n) { return hierarchic_n_dofs_at_node(t, o, n); }
template <> unsigned int FE<1,HIERARCHIC>::n_dofs_at_node(const ElemType t, const Order o, const unsigned int n) { return hierarchic_n_dofs_at_node(t, o, n); }
template <> unsigned int FE<2,HIERARCHIC>::n_dofs_at_node(const ElemType t, const Order o, const unsigned int n) { return hierarchic_n_dofs_at_node(t, o, n); }
template <> unsigned int FE<3,HIERARCHIC>::n_dofs_at_node(const ElemType t, const Order o, const unsigned int n) { return hierarchic_n_dofs_at_node(t, o, n); }
// Full specialization of n_dofs_per_elem() function for every dimension.
template <> unsigned int FE<0,HIERARCHIC>::n_dofs_per_elem(const ElemType t, const Order o) { return hierarchic_n_dofs_per_elem(t, o); }
template <> unsigned int FE<1,HIERARCHIC>::n_dofs_per_elem(const ElemType t, const Order o) { return hierarchic_n_dofs_per_elem(t, o); }
template <> unsigned int FE<2,HIERARCHIC>::n_dofs_per_elem(const ElemType t, const Order o) { return hierarchic_n_dofs_per_elem(t, o); }
template <> unsigned int FE<3,HIERARCHIC>::n_dofs_per_elem(const ElemType t, const Order o) { return hierarchic_n_dofs_per_elem(t, o); }
// Hierarchic FEMs are C^0 continuous
template <> FEContinuity FE<0,HIERARCHIC>::get_continuity() const { return C_ZERO; }
template <> FEContinuity FE<1,HIERARCHIC>::get_continuity() const { return C_ZERO; }
template <> FEContinuity FE<2,HIERARCHIC>::get_continuity() const { return C_ZERO; }
template <> FEContinuity FE<3,HIERARCHIC>::get_continuity() const { return C_ZERO; }
// Hierarchic FEMs are hierarchic (duh!)
template <> bool FE<0,HIERARCHIC>::is_hierarchic() const { return true; }
template <> bool FE<1,HIERARCHIC>::is_hierarchic() const { return true; }
template <> bool FE<2,HIERARCHIC>::is_hierarchic() const { return true; }
template <> bool FE<3,HIERARCHIC>::is_hierarchic() const { return true; }
#ifdef LIBMESH_ENABLE_AMR
// compute_constraints() specializations are only needed for 2 and 3D
template <>
void FE<2,HIERARCHIC>::compute_constraints (DofConstraints & constraints,
DofMap & dof_map,
const unsigned int variable_number,
const Elem * elem)
{ compute_proj_constraints(constraints, dof_map, variable_number, elem); }
template <>
void FE<3,HIERARCHIC>::compute_constraints (DofConstraints & constraints,
DofMap & dof_map,
const unsigned int variable_number,
const Elem * elem)
{ compute_proj_constraints(constraints, dof_map, variable_number, elem); }
#endif // #ifdef LIBMESH_ENABLE_AMR
// Hierarchic FEM shapes need reinit
template <> bool FE<0,HIERARCHIC>::shapes_need_reinit() const { return true; }
template <> bool FE<1,HIERARCHIC>::shapes_need_reinit() const { return true; }
template <> bool FE<2,HIERARCHIC>::shapes_need_reinit() const { return true; }
template <> bool FE<3,HIERARCHIC>::shapes_need_reinit() const { return true; }
} // namespace libMesh
<commit_msg>Support FIRST order HIERARCHIC on TRI3<commit_after>// The libMesh Finite Element Library.
// Copyright (C) 2002-2016 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// 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
// Local includes
#include "libmesh/elem.h"
#include "libmesh/fe.h"
#include "libmesh/fe_interface.h"
#include "libmesh/string_to_enum.h"
namespace libMesh
{
// ------------------------------------------------------------
// Hierarchic-specific implementations
// Anonymous namespace for local helper functions
namespace {
void hierarchic_nodal_soln(const Elem * elem,
const Order order,
const std::vector<Number> & elem_soln,
std::vector<Number> & nodal_soln,
unsigned Dim)
{
const unsigned int n_nodes = elem->n_nodes();
const ElemType elem_type = elem->type();
nodal_soln.resize(n_nodes);
const Order totalorder = static_cast<Order>(order + elem->p_level());
// FEType object to be passed to various FEInterface functions below.
FEType fe_type(totalorder, HIERARCHIC);
switch (totalorder)
{
// Constant shape functions
case CONSTANT:
{
libmesh_assert_equal_to (elem_soln.size(), 1);
const Number val = elem_soln[0];
for (unsigned int n=0; n<n_nodes; n++)
nodal_soln[n] = val;
return;
}
// For other orders do interpolation at the nodes
// explicitly.
default:
{
const unsigned int n_sf =
// FE<Dim,T>::n_shape_functions(elem_type, totalorder);
FEInterface::n_shape_functions(Dim, fe_type, elem_type);
std::vector<Point> refspace_nodes;
FEBase::get_refspace_nodes(elem_type,refspace_nodes);
libmesh_assert_equal_to (refspace_nodes.size(), n_nodes);
for (unsigned int n=0; n<n_nodes; n++)
{
libmesh_assert_equal_to (elem_soln.size(), n_sf);
// Zero before summation
nodal_soln[n] = 0;
// u_i = Sum (alpha_i phi_i)
for (unsigned int i=0; i<n_sf; i++)
nodal_soln[n] += elem_soln[i] *
// FE<Dim,T>::shape(elem, order, i, mapped_point);
FEInterface::shape(Dim, fe_type, elem, i, refspace_nodes[n]);
}
return;
}
}
} // hierarchic_nodal_soln()
unsigned int hierarchic_n_dofs(const ElemType t, const Order o)
{
libmesh_assert_greater (o, 0);
switch (t)
{
case NODEELEM:
return 1;
case EDGE2:
case EDGE3:
return (o+1);
case QUAD4:
case QUADSHELL4:
libmesh_assert_less (o, 2);
case QUAD8:
case QUAD9:
return ((o+1)*(o+1));
case HEX8:
libmesh_assert_less (o, 2);
case HEX20:
libmesh_assert_less (o, 2);
case HEX27:
return ((o+1)*(o+1)*(o+1));
case TRI3:
libmesh_assert_less (o, 2);
case TRI6:
return ((o+1)*(o+2)/2);
case INVALID_ELEM:
return 0;
default:
libmesh_error_msg("ERROR: Invalid ElemType " << Utility::enum_to_string(t) << " selected for HIERARCHIC FE family!");
}
libmesh_error_msg("We'll never get here!");
return 0;
} // hierarchic_n_dofs()
unsigned int hierarchic_n_dofs_at_node(const ElemType t,
const Order o,
const unsigned int n)
{
libmesh_assert_greater (o, 0);
switch (t)
{
case NODEELEM:
return 1;
case EDGE2:
case EDGE3:
switch (n)
{
case 0:
case 1:
return 1;
// Internal DoFs are associated with the elem, not its nodes
case 2:
return 0;
default:
libmesh_error_msg("ERROR: Invalid node ID " << n << " selected for EDGE2/3!");
}
case TRI3:
libmesh_assert_less (n, 3);
libmesh_assert_less (o, 2);
case TRI6:
switch (n)
{
case 0:
case 1:
case 2:
return 1;
case 3:
case 4:
case 5:
return (o-1);
// Internal DoFs are associated with the elem, not its nodes
default:
libmesh_error_msg("ERROR: Invalid node ID " << n << " selected for TRI6!");
}
case QUAD4:
case QUADSHELL4:
libmesh_assert_less (n, 4);
libmesh_assert_less (o, 2);
case QUAD8:
case QUAD9:
switch (n)
{
case 0:
case 1:
case 2:
case 3:
return 1;
case 4:
case 5:
case 6:
case 7:
return (o-1);
// Internal DoFs are associated with the elem, not its nodes
case 8:
return 0;
default:
libmesh_error_msg("ERROR: Invalid node ID " << n << " selected for QUAD4/8/9!");
}
case HEX8:
libmesh_assert_less (n, 8);
libmesh_assert_less (o, 2);
case HEX20:
libmesh_assert_less (n, 20);
libmesh_assert_less (o, 2);
case HEX27:
switch (n)
{
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
return 1;
case 8:
case 9:
case 10:
case 11:
case 12:
case 13:
case 14:
case 15:
case 16:
case 17:
case 18:
case 19:
return (o-1);
case 20:
case 21:
case 22:
case 23:
case 24:
case 25:
return ((o-1)*(o-1));
// Internal DoFs are associated with the elem, not its nodes
case 26:
return 0;
default:
libmesh_error_msg("ERROR: Invalid node ID " << n << " selected for HEX8/20/27!");
}
case INVALID_ELEM:
return 0;
default:
libmesh_error_msg("ERROR: Bad ElemType = " << Utility::enum_to_string(t) << " for " << Utility::enum_to_string(o) << " order approximation!");
}
libmesh_error_msg("We'll never get here!");
return 0;
} // hierarchic_n_dofs_at_node()
unsigned int hierarchic_n_dofs_per_elem(const ElemType t,
const Order o)
{
libmesh_assert_greater (o, 0);
switch (t)
{
case NODEELEM:
return 0;
case EDGE2:
case EDGE3:
return (o-1);
case TRI3:
case TRISHELL3:
case QUAD4:
case QUADSHELL4:
return 0;
case TRI6:
return ((o-1)*(o-2)/2);
case QUAD8:
case QUAD9:
return ((o-1)*(o-1));
case HEX8:
case HEX20:
libmesh_assert_less (o, 2);
return 0;
case HEX27:
return ((o-1)*(o-1)*(o-1));
case INVALID_ELEM:
return 0;
default:
libmesh_error_msg("ERROR: Bad ElemType = " << Utility::enum_to_string(t) << " for " << Utility::enum_to_string(o) << " order approximation!");
}
libmesh_error_msg("We'll never get here!");
return 0;
} // hierarchic_n_dofs_per_elem()
} // anonymous namespace
// Do full-specialization of nodal_soln() function for every
// dimension, instead of explicit instantiation at the end of this
// file.
// This could be macro-ified so that it fits on one line...
template <>
void FE<0,HIERARCHIC>::nodal_soln(const Elem * elem,
const Order order,
const std::vector<Number> & elem_soln,
std::vector<Number> & nodal_soln)
{ hierarchic_nodal_soln(elem, order, elem_soln, nodal_soln, /*Dim=*/0); }
template <>
void FE<1,HIERARCHIC>::nodal_soln(const Elem * elem,
const Order order,
const std::vector<Number> & elem_soln,
std::vector<Number> & nodal_soln)
{ hierarchic_nodal_soln(elem, order, elem_soln, nodal_soln, /*Dim=*/1); }
template <>
void FE<2,HIERARCHIC>::nodal_soln(const Elem * elem,
const Order order,
const std::vector<Number> & elem_soln,
std::vector<Number> & nodal_soln)
{ hierarchic_nodal_soln(elem, order, elem_soln, nodal_soln, /*Dim=*/2); }
template <>
void FE<3,HIERARCHIC>::nodal_soln(const Elem * elem,
const Order order,
const std::vector<Number> & elem_soln,
std::vector<Number> & nodal_soln)
{ hierarchic_nodal_soln(elem, order, elem_soln, nodal_soln, /*Dim=*/3); }
// Full specialization of n_dofs() function for every dimension
template <> unsigned int FE<0,HIERARCHIC>::n_dofs(const ElemType t, const Order o) { return hierarchic_n_dofs(t, o); }
template <> unsigned int FE<1,HIERARCHIC>::n_dofs(const ElemType t, const Order o) { return hierarchic_n_dofs(t, o); }
template <> unsigned int FE<2,HIERARCHIC>::n_dofs(const ElemType t, const Order o) { return hierarchic_n_dofs(t, o); }
template <> unsigned int FE<3,HIERARCHIC>::n_dofs(const ElemType t, const Order o) { return hierarchic_n_dofs(t, o); }
// Full specialization of n_dofs_at_node() function for every dimension.
template <> unsigned int FE<0,HIERARCHIC>::n_dofs_at_node(const ElemType t, const Order o, const unsigned int n) { return hierarchic_n_dofs_at_node(t, o, n); }
template <> unsigned int FE<1,HIERARCHIC>::n_dofs_at_node(const ElemType t, const Order o, const unsigned int n) { return hierarchic_n_dofs_at_node(t, o, n); }
template <> unsigned int FE<2,HIERARCHIC>::n_dofs_at_node(const ElemType t, const Order o, const unsigned int n) { return hierarchic_n_dofs_at_node(t, o, n); }
template <> unsigned int FE<3,HIERARCHIC>::n_dofs_at_node(const ElemType t, const Order o, const unsigned int n) { return hierarchic_n_dofs_at_node(t, o, n); }
// Full specialization of n_dofs_per_elem() function for every dimension.
template <> unsigned int FE<0,HIERARCHIC>::n_dofs_per_elem(const ElemType t, const Order o) { return hierarchic_n_dofs_per_elem(t, o); }
template <> unsigned int FE<1,HIERARCHIC>::n_dofs_per_elem(const ElemType t, const Order o) { return hierarchic_n_dofs_per_elem(t, o); }
template <> unsigned int FE<2,HIERARCHIC>::n_dofs_per_elem(const ElemType t, const Order o) { return hierarchic_n_dofs_per_elem(t, o); }
template <> unsigned int FE<3,HIERARCHIC>::n_dofs_per_elem(const ElemType t, const Order o) { return hierarchic_n_dofs_per_elem(t, o); }
// Hierarchic FEMs are C^0 continuous
template <> FEContinuity FE<0,HIERARCHIC>::get_continuity() const { return C_ZERO; }
template <> FEContinuity FE<1,HIERARCHIC>::get_continuity() const { return C_ZERO; }
template <> FEContinuity FE<2,HIERARCHIC>::get_continuity() const { return C_ZERO; }
template <> FEContinuity FE<3,HIERARCHIC>::get_continuity() const { return C_ZERO; }
// Hierarchic FEMs are hierarchic (duh!)
template <> bool FE<0,HIERARCHIC>::is_hierarchic() const { return true; }
template <> bool FE<1,HIERARCHIC>::is_hierarchic() const { return true; }
template <> bool FE<2,HIERARCHIC>::is_hierarchic() const { return true; }
template <> bool FE<3,HIERARCHIC>::is_hierarchic() const { return true; }
#ifdef LIBMESH_ENABLE_AMR
// compute_constraints() specializations are only needed for 2 and 3D
template <>
void FE<2,HIERARCHIC>::compute_constraints (DofConstraints & constraints,
DofMap & dof_map,
const unsigned int variable_number,
const Elem * elem)
{ compute_proj_constraints(constraints, dof_map, variable_number, elem); }
template <>
void FE<3,HIERARCHIC>::compute_constraints (DofConstraints & constraints,
DofMap & dof_map,
const unsigned int variable_number,
const Elem * elem)
{ compute_proj_constraints(constraints, dof_map, variable_number, elem); }
#endif // #ifdef LIBMESH_ENABLE_AMR
// Hierarchic FEM shapes need reinit
template <> bool FE<0,HIERARCHIC>::shapes_need_reinit() const { return true; }
template <> bool FE<1,HIERARCHIC>::shapes_need_reinit() const { return true; }
template <> bool FE<2,HIERARCHIC>::shapes_need_reinit() const { return true; }
template <> bool FE<3,HIERARCHIC>::shapes_need_reinit() const { return true; }
} // namespace libMesh
<|endoftext|> |
<commit_before>#include "MainPanel.h"
#include "Settings.h"
#include <QMessageBox>
#include <QGridLayout>
#include <QPushButton>
#include <QScrollArea>
#include <QLabel>
/** MainPanel constructor
* Sets base size policy and object name.
* \param parent Pointer to parent widget.
*/
MainPanel::MainPanel(QWidget* parent)
: QWidget(parent)
{
setObjectName("mainPanel");
init();
setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
show();
}
/** Main initializer for the UI.
* QObjects are initialized by depth - back to front.
* Note that the navbar is initialized as a derived class.
*/
void MainPanel::init()
{
p = new QSettings(QSettings::IniFormat, QSettings::UserScope, "HorizonLauncher", "palette");
// Main panel layout
QGridLayout* mainGridLayout = new QGridLayout;
mainGridLayout->setSpacing(0);
mainGridLayout->setMargin(0);
setLayout(mainGridLayout);
// Core widget
QWidget* coreWidget = new QWidget();
coreWidget->setObjectName("coreWidget");
coreWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
coreWidget->setStyleSheet("background-color: " + p->value("Body/Background").toString() + ";");
mainGridLayout->addWidget(coreWidget);
// Vertical layout #1
QVBoxLayout* verticalLayout1 = new QVBoxLayout;
verticalLayout1->setSpacing(0);
verticalLayout1->setMargin(0);
verticalLayout1->setAlignment(Qt::AlignHCenter);
coreWidget->setLayout(verticalLayout1);
// Title bar widget
QWidget* borderWidget = new QWidget;
borderWidget->setStyleSheet("background-color: " + p->value("TitleBar/Color").toString() + ";"
"background-image: url(:SystemMenu/Images/TitleBarPattern.png);"
"background-repeat: repeat-x;");
verticalLayout1->addWidget(borderWidget);
// Window Control Horizontal Layout
QHBoxLayout* windowControlLayout = new QHBoxLayout;
windowControlLayout->setSpacing(0);
windowControlLayout->setMargin(8);
borderWidget->setLayout(windowControlLayout);
windowControlLayout->addStretch();
// Window controls
// Minimize
QPushButton* pushButtonMinimize = new QPushButton("", coreWidget);
pushButtonMinimize->setObjectName("pushButtonMinimize");
windowControlLayout->addWidget(pushButtonMinimize);
QObject::connect(pushButtonMinimize, &QPushButton::clicked, this, &MainPanel::pushButtonMinimize);
// Maximize
QPushButton* pushButtonMaximize = new QPushButton("", coreWidget);
pushButtonMaximize->setObjectName("pushButtonMaximize");
windowControlLayout->addWidget(pushButtonMaximize);
QObject::connect(pushButtonMaximize, &QPushButton::clicked, this, &MainPanel::pushButtonMaximize);
// Close
QPushButton* pushButtonClose = new QPushButton("", coreWidget);
pushButtonClose->setObjectName("pushButtonClose");
windowControlLayout->addWidget(pushButtonClose);
QObject::connect(pushButtonClose, &QPushButton::clicked, this, &MainPanel::pushButtonClose);
// Navbar
navbar = new Navbar(p, coreWidget);
verticalLayout1->addWidget(navbar);
// Main Horizontal Layout
QHBoxLayout* horizontalLayout = new QHBoxLayout;
horizontalLayout->setSpacing(0);
horizontalLayout->setMargin(0);
horizontalLayout->setAlignment(Qt::AlignVCenter);
verticalLayout1->addLayout(horizontalLayout);
// Backdrop widget
QWidget* mainPanelBackdrop = new QWidget(coreWidget);
mainPanelBackdrop->setObjectName("mainPanelBackdrop");
horizontalLayout->addWidget(mainPanelBackdrop);
// Vertical layout #2
QVBoxLayout* verticalLayout2 = new QVBoxLayout;
verticalLayout2->setSpacing(0);
verticalLayout2->setMargin(0);
verticalLayout2->setAlignment(Qt::AlignHCenter);
mainPanelBackdrop->setLayout(verticalLayout2);
// Main panel scroll area
QScrollArea* scrollArea = new QScrollArea(coreWidget);
scrollArea->setWidgetResizable(true);
scrollArea->setObjectName("mainPanelScrollArea");
scrollArea->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
verticalLayout2->addWidget(scrollArea);
// Stacked content panel
stack = new QStackedWidget(scrollArea);
stack->setObjectName("stack");
stack->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
scrollArea->setWidget(stack);
// Stack widgets
home = new Homepage(p, stack);
home->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
library = new Library(p, stack);
library->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
community = new Community(p, stack);
community->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
settings = new Settings(p, stack);
settings->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
stack->addWidget(home);
stack->addWidget(library);
stack->addWidget(community);
stack->addWidget(settings);
stack->setCurrentWidget(library);
connect(stack, &QStackedWidget::currentChanged, this, &MainPanel::onStackedChanged);
// Set active tab
activeTab = navbar->gamesTab;
activeTab->toggleActive();
// Connect signals
connect(navbar->homeTab, &TabWidget::clicked, this, &MainPanel::setHome);
// connect(navbar->storeTab, &TabWidget::clicked, this, &MainPanel::setStore);
connect(navbar->gamesTab, &TabWidget::clicked, this, &MainPanel::setGames);
connect(navbar->communityTab, &TabWidget::clicked, this, &MainPanel::setCommunity);
// connect(navbar->newsTab, &TabWidget::clicked, this, &MainPanel::setNews);
// connect(navbar->modsTab, &TabWidget::clicked, this, &MainPanel::setMods);
connect(navbar->settingsTab, &TabWidget::clicked, this, &MainPanel::setSettings);
// Show
show();
}
void MainPanel::onStackedChanged(int index)
{
QWidget* curWidget = stack->widget(index);
curWidget->adjustSize();
}
<commit_msg>Fix bugs where stacked widgets would be smaller than the window<commit_after>#include "MainPanel.h"
#include "Settings.h"
#include <QMessageBox>
#include <QGridLayout>
#include <QPushButton>
#include <QScrollArea>
#include <QLabel>
/** MainPanel constructor
* Sets base size policy and object name.
* \param parent Pointer to parent widget.
*/
MainPanel::MainPanel(QWidget* parent)
: QWidget(parent)
{
setObjectName("mainPanel");
init();
setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
show();
}
/** Main initializer for the UI.
* QObjects are initialized by depth - back to front.
* Note that the navbar is initialized as a derived class.
*/
void MainPanel::init()
{
p = new QSettings(QSettings::IniFormat, QSettings::UserScope, "HorizonLauncher", "palette");
// Main panel layout
QGridLayout* mainGridLayout = new QGridLayout;
mainGridLayout->setSpacing(0);
mainGridLayout->setMargin(0);
setLayout(mainGridLayout);
// Core widget
QWidget* coreWidget = new QWidget();
coreWidget->setObjectName("coreWidget");
coreWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
coreWidget->setStyleSheet("background-color: " + p->value("Body/Background").toString() + ";");
mainGridLayout->addWidget(coreWidget);
// Vertical layout #1
QVBoxLayout* verticalLayout1 = new QVBoxLayout;
verticalLayout1->setSpacing(0);
verticalLayout1->setMargin(0);
verticalLayout1->setAlignment(Qt::AlignHCenter);
coreWidget->setLayout(verticalLayout1);
// Title bar widget
QWidget* borderWidget = new QWidget;
borderWidget->setStyleSheet("background-color: " + p->value("TitleBar/Color").toString() + ";"
"background-image: url(:SystemMenu/Images/TitleBarPattern.png);"
"background-repeat: repeat-x;");
verticalLayout1->addWidget(borderWidget);
// Window Control Horizontal Layout
QHBoxLayout* windowControlLayout = new QHBoxLayout;
windowControlLayout->setSpacing(0);
windowControlLayout->setMargin(8);
borderWidget->setLayout(windowControlLayout);
windowControlLayout->addStretch();
// Window controls
// Minimize
QPushButton* pushButtonMinimize = new QPushButton("", coreWidget);
pushButtonMinimize->setObjectName("pushButtonMinimize");
windowControlLayout->addWidget(pushButtonMinimize);
QObject::connect(pushButtonMinimize, &QPushButton::clicked, this, &MainPanel::pushButtonMinimize);
// Maximize
QPushButton* pushButtonMaximize = new QPushButton("", coreWidget);
pushButtonMaximize->setObjectName("pushButtonMaximize");
windowControlLayout->addWidget(pushButtonMaximize);
QObject::connect(pushButtonMaximize, &QPushButton::clicked, this, &MainPanel::pushButtonMaximize);
// Close
QPushButton* pushButtonClose = new QPushButton("", coreWidget);
pushButtonClose->setObjectName("pushButtonClose");
windowControlLayout->addWidget(pushButtonClose);
QObject::connect(pushButtonClose, &QPushButton::clicked, this, &MainPanel::pushButtonClose);
// Navbar
navbar = new Navbar(p, coreWidget);
verticalLayout1->addWidget(navbar);
// Main Horizontal Layout
QHBoxLayout* horizontalLayout = new QHBoxLayout;
horizontalLayout->setSpacing(0);
horizontalLayout->setMargin(0);
horizontalLayout->setAlignment(Qt::AlignVCenter);
verticalLayout1->addLayout(horizontalLayout);
// Backdrop widget
QWidget* mainPanelBackdrop = new QWidget(coreWidget);
mainPanelBackdrop->setObjectName("mainPanelBackdrop");
horizontalLayout->addWidget(mainPanelBackdrop);
// Vertical layout #2
QVBoxLayout* verticalLayout2 = new QVBoxLayout;
verticalLayout2->setSpacing(0);
verticalLayout2->setMargin(0);
verticalLayout2->setAlignment(Qt::AlignHCenter);
mainPanelBackdrop->setLayout(verticalLayout2);
// Main panel scroll area
QScrollArea* scrollArea = new QScrollArea(coreWidget);
scrollArea->setWidgetResizable(true);
scrollArea->setObjectName("mainPanelScrollArea");
scrollArea->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
verticalLayout2->addWidget(scrollArea);
// Stacked content panel
stack = new QStackedWidget(scrollArea);
stack->setObjectName("stack");
stack->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
scrollArea->setWidget(stack);
// Stack widgets
home = new Homepage(p, stack);
home->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
library = new Library(p, stack);
library->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
community = new Community(p, stack);
community->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
settings = new Settings(p, stack);
settings->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
stack->addWidget(home);
stack->addWidget(library);
stack->addWidget(community);
stack->addWidget(settings);
stack->setCurrentWidget(library);
connect(stack, &QStackedWidget::currentChanged, this, &MainPanel::onStackedChanged);
// Set active tab
activeTab = navbar->gamesTab;
activeTab->toggleActive();
// Connect signals
connect(navbar->homeTab, &TabWidget::clicked, this, &MainPanel::setHome);
// connect(navbar->storeTab, &TabWidget::clicked, this, &MainPanel::setStore);
connect(navbar->gamesTab, &TabWidget::clicked, this, &MainPanel::setGames);
connect(navbar->communityTab, &TabWidget::clicked, this, &MainPanel::setCommunity);
// connect(navbar->newsTab, &TabWidget::clicked, this, &MainPanel::setNews);
// connect(navbar->modsTab, &TabWidget::clicked, this, &MainPanel::setMods);
connect(navbar->settingsTab, &TabWidget::clicked, this, &MainPanel::setSettings);
// Show
show();
}
void MainPanel::onStackedChanged(int index)
{
QWidget* curWidget = stack->widget(index);
curWidget->setMinimumSize(this->size());
curWidget->adjustSize();
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
#include <quic/logging/QLoggerTypes.h>
namespace quic {
folly::dynamic PaddingFrameLog::toDynamic() const {
folly::dynamic d = folly::dynamic::object();
d["frame_type"] = toString(FrameType::PADDING);
return d;
}
folly::dynamic RstStreamFrameLog::toDynamic() const {
folly::dynamic d = folly::dynamic::object();
d["frame_type"] = toString(FrameType::RST_STREAM);
d["stream_id"] = streamId;
d["error_code"] = errorCode;
d["offset"] = offset;
return d;
}
folly::dynamic ConnectionCloseFrameLog::toDynamic() const {
folly::dynamic d = folly::dynamic::object();
d["frame_type"] = toString(FrameType::CONNECTION_CLOSE);
d["error_code"] = toString(errorCode);
d["reason_phrase"] = reasonPhrase;
d["closing_frame_type"] = toString(closingFrameType);
return d;
}
folly::dynamic ApplicationCloseFrameLog::toDynamic() const {
folly::dynamic d = folly::dynamic::object();
d["frame_type"] = toString(FrameType::APPLICATION_CLOSE);
d["error_code"] = errorCode;
d["reason_phrase"] = reasonPhrase;
return d;
}
folly::dynamic MaxDataFrameLog::toDynamic() const {
folly::dynamic d = folly::dynamic::object();
d["frame_type"] = toString(FrameType::MAX_DATA);
d["maximum_data"] = maximumData;
return d;
}
folly::dynamic MaxStreamDataFrameLog::toDynamic() const {
folly::dynamic d = folly::dynamic::object();
d["frame_type"] = toString(FrameType::MAX_STREAM_DATA);
d["stream_id"] = streamId;
d["maximum_data"] = maximumData;
return d;
}
folly::dynamic MaxStreamsFrameLog::toDynamic() const {
folly::dynamic d = folly::dynamic::object();
FrameType type;
if (isForBidirectional) {
type = FrameType::MAX_STREAMS_BIDI;
} else {
type = FrameType::MAX_STREAMS_UNI;
}
d["frame_type"] = toString(type);
d["max_streams"] = maxStreams;
return d;
}
folly::dynamic StreamsBlockedFrameLog::toDynamic() const {
folly::dynamic d = folly::dynamic::object();
FrameType type;
if (isForBidirectional) {
type = FrameType::STREAMS_BLOCKED_BIDI;
} else {
type = FrameType::STREAMS_BLOCKED_UNI;
}
d["frame_type"] = toString(type);
d["stream_limit"] = streamLimit;
return d;
}
folly::dynamic PingFrameLog::toDynamic() const {
folly::dynamic d = folly::dynamic::object();
d["frame_type"] = toString(FrameType::PING);
return d;
}
folly::dynamic DataBlockedFrameLog::toDynamic() const {
folly::dynamic d = folly::dynamic::object();
d["frame_type"] = toString(FrameType::DATA_BLOCKED);
d["data_limit"] = dataLimit;
return d;
}
folly::dynamic StreamDataBlockedFrameLog::toDynamic() const {
folly::dynamic d = folly::dynamic::object();
d["frame_type"] = toString(FrameType::STREAM_DATA_BLOCKED);
d["stream_id"] = streamId;
d["data_limit"] = dataLimit;
return d;
}
folly::dynamic StreamFrameLog::toDynamic() const {
folly::dynamic d = folly::dynamic::object();
d["offset"] = offset;
d["length"] = len;
d["fin"] = fin;
d["id"] = streamId;
d["frame_type"] = toString(FrameType::STREAM);
return d;
}
folly::dynamic CryptoFrameLog::toDynamic() const {
folly::dynamic d = folly::dynamic::object();
d["frame_type"] = toString(FrameType::CRYPTO_FRAME);
d["offset"] = offset;
d["len"] = len;
return d;
}
folly::dynamic StopSendingFrameLog::toDynamic() const {
folly::dynamic d = folly::dynamic::object();
d["frame_type"] = toString(FrameType::STOP_SENDING);
d["stream_id"] = streamId;
d["error_code"] = errorCode;
return d;
}
folly::dynamic MinStreamDataFrameLog::toDynamic() const {
folly::dynamic d = folly::dynamic::object();
d["frame_type"] = toString(FrameType::MIN_STREAM_DATA);
d["stream_id"] = streamId;
d["maximum_data"] = maximumData;
d["minimum_stream_offset"] = minimumStreamOffset;
return d;
}
folly::dynamic ExpiredStreamDataFrameLog::toDynamic() const {
folly::dynamic d = folly::dynamic::object();
d["frame_type"] = toString(FrameType::EXPIRED_STREAM_DATA);
d["stream_id"] = streamId;
d["minimum_stream_offset"] = minimumStreamOffset;
return d;
}
folly::dynamic PathChallengeFrameLog::toDynamic() const {
folly::dynamic d = folly::dynamic::object();
d["frame_type"] = toString(FrameType::PATH_CHALLENGE);
d["path_data"] = pathData;
return d;
}
folly::dynamic PathResponseFrameLog::toDynamic() const {
folly::dynamic d = folly::dynamic::object();
d["frame_type"] = toString(FrameType::PATH_RESPONSE);
d["path_data"] = pathData;
return d;
}
folly::dynamic NewConnectionIdFrameLog::toDynamic() const {
folly::dynamic d = folly::dynamic::object();
d["frame_type"] = toString(FrameType::NEW_CONNECTION_ID);
d["sequence"] = sequence;
folly::dynamic dToken = folly::dynamic::array();
for (const auto& a : token) {
dToken.push_back(a);
}
d["token"] = dToken;
return d;
}
folly::dynamic ReadAckFrameLog::toDynamic() const {
folly::dynamic d = folly::dynamic::object();
folly::dynamic ackRangeDynamic = folly::dynamic::array();
for (const auto& b : ackBlocks) {
folly::dynamic subArray = folly::dynamic::array(b.startPacket, b.endPacket);
ackRangeDynamic.push_back(subArray);
}
d["acked_ranges"] = ackRangeDynamic;
d["frame_type"] = toString(FrameType::ACK);
d["ack_delay"] = ackDelay.count();
return d;
}
folly::dynamic WriteAckFrameLog::toDynamic() const {
folly::dynamic d = folly::dynamic::object();
folly::dynamic ackRangeDynamic = folly::dynamic::array();
for (auto it = ackBlocks.cbegin(); it != ackBlocks.cend(); ++it) {
folly::dynamic subArray = folly::dynamic::array(it->start, it->end);
ackRangeDynamic.push_back(subArray);
}
d["acked_ranges"] = ackRangeDynamic;
d["frame_type"] = toString(FrameType::ACK);
d["ack_delay"] = ackDelay.count();
return d;
}
folly::dynamic ReadNewTokenFrameLog::toDynamic() const {
folly::dynamic d = folly::dynamic::object();
d["frame_type"] = toString(FrameType::NEW_TOKEN);
return d;
}
folly::dynamic VersionNegotiationLog::toDynamic() const {
folly::dynamic d = folly::dynamic::object();
d = folly::dynamic::array();
for (const auto& v : versions) {
d.push_back(toString(v));
}
return d;
}
folly::dynamic QLogPacketEvent::toDynamic() const {
folly::dynamic d =
folly::dynamic::array("TRANSPORT", toString(eventType), "DEFAULT");
folly::dynamic data = folly::dynamic::object();
data["frames"] = folly::dynamic::array();
for (const auto& frame : frames) {
data["frames"].push_back(frame->toDynamic());
}
data["header"] = folly::dynamic::object("packet_size", packetSize)(
"packet_number", packetNum);
data["packet_type"] = packetType;
d.push_back(data);
return d;
}
folly::dynamic QLogVersionNegotiationEvent::toDynamic() const {
folly::dynamic d =
folly::dynamic::array("TRANSPORT", toString(eventType), "DEFAULT");
folly::dynamic data = folly::dynamic::object();
data["versions"] = versionLog->toDynamic();
data["header"] = folly::dynamic::object("packet_size", packetSize);
data["packet_type"] = packetType;
d.push_back(data);
return d;
}
std::string toString(EventType type) {
switch (type) {
case EventType::PacketSent:
return "PACKET_SENT";
case EventType::PacketReceived:
return "PACKET_RECEIVED";
}
LOG(WARNING) << "toString has unhandled QLog event type";
return "UNKNOWN";
}
} // namespace quic
<commit_msg>Save a couple copy of dynamics in QLog<commit_after>/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
#include <quic/logging/QLoggerTypes.h>
namespace quic {
folly::dynamic PaddingFrameLog::toDynamic() const {
folly::dynamic d = folly::dynamic::object();
d["frame_type"] = toString(FrameType::PADDING);
return d;
}
folly::dynamic RstStreamFrameLog::toDynamic() const {
folly::dynamic d = folly::dynamic::object();
d["frame_type"] = toString(FrameType::RST_STREAM);
d["stream_id"] = streamId;
d["error_code"] = errorCode;
d["offset"] = offset;
return d;
}
folly::dynamic ConnectionCloseFrameLog::toDynamic() const {
folly::dynamic d = folly::dynamic::object();
d["frame_type"] = toString(FrameType::CONNECTION_CLOSE);
d["error_code"] = toString(errorCode);
d["reason_phrase"] = reasonPhrase;
d["closing_frame_type"] = toString(closingFrameType);
return d;
}
folly::dynamic ApplicationCloseFrameLog::toDynamic() const {
folly::dynamic d = folly::dynamic::object();
d["frame_type"] = toString(FrameType::APPLICATION_CLOSE);
d["error_code"] = errorCode;
d["reason_phrase"] = reasonPhrase;
return d;
}
folly::dynamic MaxDataFrameLog::toDynamic() const {
folly::dynamic d = folly::dynamic::object();
d["frame_type"] = toString(FrameType::MAX_DATA);
d["maximum_data"] = maximumData;
return d;
}
folly::dynamic MaxStreamDataFrameLog::toDynamic() const {
folly::dynamic d = folly::dynamic::object();
d["frame_type"] = toString(FrameType::MAX_STREAM_DATA);
d["stream_id"] = streamId;
d["maximum_data"] = maximumData;
return d;
}
folly::dynamic MaxStreamsFrameLog::toDynamic() const {
folly::dynamic d = folly::dynamic::object();
FrameType type;
if (isForBidirectional) {
type = FrameType::MAX_STREAMS_BIDI;
} else {
type = FrameType::MAX_STREAMS_UNI;
}
d["frame_type"] = toString(type);
d["max_streams"] = maxStreams;
return d;
}
folly::dynamic StreamsBlockedFrameLog::toDynamic() const {
folly::dynamic d = folly::dynamic::object();
FrameType type;
if (isForBidirectional) {
type = FrameType::STREAMS_BLOCKED_BIDI;
} else {
type = FrameType::STREAMS_BLOCKED_UNI;
}
d["frame_type"] = toString(type);
d["stream_limit"] = streamLimit;
return d;
}
folly::dynamic PingFrameLog::toDynamic() const {
folly::dynamic d = folly::dynamic::object();
d["frame_type"] = toString(FrameType::PING);
return d;
}
folly::dynamic DataBlockedFrameLog::toDynamic() const {
folly::dynamic d = folly::dynamic::object();
d["frame_type"] = toString(FrameType::DATA_BLOCKED);
d["data_limit"] = dataLimit;
return d;
}
folly::dynamic StreamDataBlockedFrameLog::toDynamic() const {
folly::dynamic d = folly::dynamic::object();
d["frame_type"] = toString(FrameType::STREAM_DATA_BLOCKED);
d["stream_id"] = streamId;
d["data_limit"] = dataLimit;
return d;
}
folly::dynamic StreamFrameLog::toDynamic() const {
folly::dynamic d = folly::dynamic::object();
d["offset"] = offset;
d["length"] = len;
d["fin"] = fin;
d["id"] = streamId;
d["frame_type"] = toString(FrameType::STREAM);
return d;
}
folly::dynamic CryptoFrameLog::toDynamic() const {
folly::dynamic d = folly::dynamic::object();
d["frame_type"] = toString(FrameType::CRYPTO_FRAME);
d["offset"] = offset;
d["len"] = len;
return d;
}
folly::dynamic StopSendingFrameLog::toDynamic() const {
folly::dynamic d = folly::dynamic::object();
d["frame_type"] = toString(FrameType::STOP_SENDING);
d["stream_id"] = streamId;
d["error_code"] = errorCode;
return d;
}
folly::dynamic MinStreamDataFrameLog::toDynamic() const {
folly::dynamic d = folly::dynamic::object();
d["frame_type"] = toString(FrameType::MIN_STREAM_DATA);
d["stream_id"] = streamId;
d["maximum_data"] = maximumData;
d["minimum_stream_offset"] = minimumStreamOffset;
return d;
}
folly::dynamic ExpiredStreamDataFrameLog::toDynamic() const {
folly::dynamic d = folly::dynamic::object();
d["frame_type"] = toString(FrameType::EXPIRED_STREAM_DATA);
d["stream_id"] = streamId;
d["minimum_stream_offset"] = minimumStreamOffset;
return d;
}
folly::dynamic PathChallengeFrameLog::toDynamic() const {
folly::dynamic d = folly::dynamic::object();
d["frame_type"] = toString(FrameType::PATH_CHALLENGE);
d["path_data"] = pathData;
return d;
}
folly::dynamic PathResponseFrameLog::toDynamic() const {
folly::dynamic d = folly::dynamic::object();
d["frame_type"] = toString(FrameType::PATH_RESPONSE);
d["path_data"] = pathData;
return d;
}
folly::dynamic NewConnectionIdFrameLog::toDynamic() const {
folly::dynamic d = folly::dynamic::object();
d["frame_type"] = toString(FrameType::NEW_CONNECTION_ID);
d["sequence"] = sequence;
folly::dynamic dToken = folly::dynamic::array();
for (const auto& a : token) {
dToken.push_back(a);
}
d["token"] = dToken;
return d;
}
folly::dynamic ReadAckFrameLog::toDynamic() const {
folly::dynamic d = folly::dynamic::object();
folly::dynamic ackRangeDynamic = folly::dynamic::array();
for (const auto& b : ackBlocks) {
ackRangeDynamic.push_back(
folly::dynamic::array(b.startPacket, b.endPacket));
}
d["acked_ranges"] = ackRangeDynamic;
d["frame_type"] = toString(FrameType::ACK);
d["ack_delay"] = ackDelay.count();
return d;
}
folly::dynamic WriteAckFrameLog::toDynamic() const {
folly::dynamic d = folly::dynamic::object();
folly::dynamic ackRangeDynamic = folly::dynamic::array();
for (auto it = ackBlocks.cbegin(); it != ackBlocks.cend(); ++it) {
ackRangeDynamic.push_back(folly::dynamic::array(it->start, it->end));
}
d["acked_ranges"] = ackRangeDynamic;
d["frame_type"] = toString(FrameType::ACK);
d["ack_delay"] = ackDelay.count();
return d;
}
folly::dynamic ReadNewTokenFrameLog::toDynamic() const {
folly::dynamic d = folly::dynamic::object();
d["frame_type"] = toString(FrameType::NEW_TOKEN);
return d;
}
folly::dynamic VersionNegotiationLog::toDynamic() const {
folly::dynamic d = folly::dynamic::object();
d = folly::dynamic::array();
for (const auto& v : versions) {
d.push_back(toString(v));
}
return d;
}
folly::dynamic QLogPacketEvent::toDynamic() const {
folly::dynamic d =
folly::dynamic::array("TRANSPORT", toString(eventType), "DEFAULT");
folly::dynamic data = folly::dynamic::object();
data["frames"] = folly::dynamic::array();
for (const auto& frame : frames) {
data["frames"].push_back(frame->toDynamic());
}
data["header"] = folly::dynamic::object("packet_size", packetSize)(
"packet_number", packetNum);
data["packet_type"] = packetType;
d.push_back(std::move(data));
return d;
}
folly::dynamic QLogVersionNegotiationEvent::toDynamic() const {
folly::dynamic d =
folly::dynamic::array("TRANSPORT", toString(eventType), "DEFAULT");
folly::dynamic data = folly::dynamic::object();
data["versions"] = versionLog->toDynamic();
data["header"] = folly::dynamic::object("packet_size", packetSize);
data["packet_type"] = packetType;
d.push_back(std::move(data));
return d;
}
std::string toString(EventType type) {
switch (type) {
case EventType::PacketSent:
return "PACKET_SENT";
case EventType::PacketReceived:
return "PACKET_RECEIVED";
}
LOG(WARNING) << "toString has unhandled QLog event type";
return "UNKNOWN";
}
} // namespace quic
<|endoftext|> |
<commit_before>#include "ex14_26_StrVec.h"
#include <algorithm> // for_each, equal
void StrVec::push_back(const std::string& s)
{
chk_n_alloc();
alloc.construct(first_free++, s);
}
std::pair<std::string*, std::string*> StrVec::alloc_n_copy(const std::string* b,
const std::string* e)
{
auto data = alloc.allocate(e - b);
return {data, std::uninitialized_copy(b, e, data)};
}
void StrVec::free()
{
if (elements) {
for_each(elements, first_free,
[this](std::string& rhs) { alloc.destroy(&rhs); });
alloc.deallocate(elements, cap - elements);
}
}
void StrVec::range_initialize(const std::string* first, const std::string* last)
{
auto newdata = alloc_n_copy(first, last);
elements = newdata.first;
first_free = cap = newdata.second;
}
StrVec::StrVec(const StrVec& rhs)
{
range_initialize(rhs.begin(), rhs.end());
}
StrVec::StrVec(std::initializer_list<std::string> il)
{
range_initialize(il.begin(), il.end());
}
StrVec::~StrVec()
{
free();
}
StrVec& StrVec::operator=(const StrVec& rhs)
{
auto data = alloc_n_copy(rhs.begin(), rhs.end());
free();
elements = data.first;
first_free = cap = data.second;
return *this;
}
void StrVec::alloc_n_move(size_t new_cap)
{
auto newdata = alloc.allocate(new_cap);
auto dest = newdata;
auto elem = elements;
for (size_t i = 0; i != size(); ++i)
alloc.construct(dest++, std::move(*elem++));
free();
elements = newdata;
first_free = dest;
cap = elements + new_cap;
}
void StrVec::reallocate()
{
auto newcapacity = size() ? 2 * size() : 1;
alloc_n_move(newcapacity);
}
void StrVec::reserve(size_t new_cap)
{
if (new_cap <= capacity()) return;
alloc_n_move(new_cap);
}
void StrVec::resize(size_t count)
{
resize(count, std::string());
}
void StrVec::resize(size_t count, const std::string& s)
{
if (count > size()) {
if (count > capacity()) reserve(count * 2);
for (size_t i = size(); i != count; ++i)
alloc.construct(first_free++, s);
}
else if (count < size()) {
while (first_free != elements + count) alloc.destroy(--first_free);
}
}
StrVec::StrVec(StrVec&& s) NOEXCEPT : elements(s.elements),
first_free(s.first_free),
cap(s.cap)
{
// leave s in a state in which it is safe to run the destructor.
s.elements = s.first_free = s.cap = nullptr;
}
StrVec& StrVec::operator=(StrVec&& rhs) NOEXCEPT
{
if (this != &rhs) {
free();
elements = rhs.elements;
first_free = rhs.first_free;
cap = rhs.cap;
rhs.elements = rhs.first_free = rhs.cap = nullptr;
}
return *this;
}
bool operator==(const StrVec& lhs, const StrVec& rhs)
{
return (lhs.size() == rhs.size() &&
std::equal(lhs.begin(), lhs.end(), rhs.begin()));
}
bool operator!=(const StrVec& lhs, const StrVec& rhs)
{
return !(lhs == rhs);
}
bool operator<(const StrVec& lhs, const StrVec& rhs)
{
return std::lexicographical_compare(lhs.begin(), lhs.end(), rhs.begin(),
rhs.end());
}
bool operator>(const StrVec& lhs, const StrVec& rhs)
{
return rhs < lhs;
}
bool operator<=(const StrVec& lhs, const StrVec& rhs)
{
return !(rhs < lhs);
}
bool operator>=(const StrVec& lhs, const StrVec& rhs)
{
return !(lhs < rhs);
}
<commit_msg>Update ex14_26_StrVec.cpp<commit_after>#include <string>
#include <memory>
#include <utility>
#include <cstddef>
#include <algorithm>
#include <initializer_list>
#include "ex14_26_StrVec.h"
using namespace std;
bool operator==(const StrVec& lhs, const StrVec& rhs)
{
return ((lhs.size()==rhs.size())&&equal(lhs.begin(), lhs.end(), rhs.begin()));
}
bool operator!=(const StrVec& lhs, const StrVec& rhs)
{
return !(lhs==rhs);
}
bool operator<(const StrVec& lhs, const StrVec& rhs)
{
return lexicographical_compare(lhs.begin(), lhs.end(), rhs.begin(), rhs.end());
}
bool operator>(const StrVec& lhs, const StrVec& rhs)
{
return rhs<lhs;
}
bool operator<=(const StrVec& lhs, const StrVec& rhs)
{
return !(rhs<lhs);
}
bool operator>=(const StrVec& lhs, const StrVec& rhs)
{
return !(lhs<rhs);
}
StrVec::StrVec(initializer_list<string> il)
{
range_initialize(il.begin(), il.end());
}
StrVec::StrVec(const StrVec& s)
{
range_initialize(s.begin(), s.end());
}
StrVec& StrVec::operator=(const StrVec& rhs)
{
auto data=alloc_n_copy(rhs.begin(), rhs.end());
free();
elements=data.first;
first_free=cap=data.second;
return *this;
}
StrVec::StrVec(StrVec&& s) noexcept : elements(s.elements), first_free(s.first_free), cap(s.cap)
{
s.elements=s.first_free=s.cap=nullptr;
}
StrVec& StrVec::operator=(StrVec&& rhs) noexcept
{
if(this!=&rhs)
{
free();
elements=rhs.elements;
first_free=rhs.first_free;
cap=rhs.cap;
rhs.elements=rhs.first_free=rhs.cap=nullptr;
}
return *this;
}
StrVec::~StrVec()
{
free();
}
void StrVec::push_back(const string& s)
{
chk_n_alloc();
alloc.construct(first_free++, s);
}
void StrVec::reserve(size_t new_cap)
{
if(new_cap<=capacity())
return;
alloc_n_move(new_cap);
}
void StrVec::resize(size_t count)
{
resize(count, string());
}
void StrVec::resize(size_t count, const string& s)
{
if(count>size())
{
if(count>capacity())
reserve(2*count);
for(size_t i=size(); i!=count; ++i)
alloc.construct(first_free++, s);
}
else if(count<size())
{
while(first_free!=elements+count)
alloc.destroy(--first_free);
}
}
pair<string*, string*> StrVec::alloc_n_copy(const string* b, const string* e)
{
auto data=alloc.allocate(e-b);
return {data, uninitialized_copy(b, e, data)};
}
void StrVec::range_initialize(const string* first, const string* last)
{
auto newdata=alloc_n_copy(first, last);
elements=newdata.first;
first_free=cap=newdata.second;
}
void StrVec::free()
{
if(elements)
{
for_each(elements, first_free, [this](string& s) {alloc.destroy(&s);});
alloc.deallocate(elements, cap-elements);
}
}
void StrVec::reallocate()
{
auto newcapacity=size() ? 2*size() : 1;
alloc_n_move(newcapacity);
}
void StrVec::alloc_n_move(size_t new_cap)
{
auto newdata=alloc.allocate(new_cap);
auto dest=newdata;
auto elem=elements;
for(size_t i=0; i!=size(); ++i)
alloc.construct(dest++, std::move(*elem++));
free();
elements=newdata;
first_free=dest;
cap=elements+new_cap;
}
<|endoftext|> |
<commit_before>// ======================================================================== //
// Copyright 2009-2019 Intel Corporation //
// //
// Licensed under the Apache License, Version 2.0 (the "License"); //
// you may not use this file except in compliance with the License. //
// You may obtain a copy of the License at //
// //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and //
// limitations under the License. //
// ======================================================================== //
#include "DistributedWorld.h"
#include <algorithm>
#include <iterator>
#include "DistributedWorld.h"
#include "DistributedWorld_ispc.h"
#include "MPICommon.h"
#include "Messaging.h"
#include "api/ISPCDevice.h"
#include "common/Data.h"
namespace ospray {
namespace mpi {
using namespace ospcommon;
void RegionScreenBounds::extend(const vec3f &p)
{
if (p.z < 0) {
bounds = box2f(vec2f(0), vec2f(1));
} else {
bounds.extend(vec2f(p.x * sign(p.z), p.y * sign(p.z)));
bounds.lower.x = clamp(bounds.lower.x);
bounds.upper.x = clamp(bounds.upper.x);
bounds.lower.y = clamp(bounds.lower.y);
bounds.upper.y = clamp(bounds.upper.y);
}
}
Region::Region(const box3f &bounds, int id) : bounds(bounds), id(id) {}
RegionScreenBounds Region::project(const Camera *camera) const
{
RegionScreenBounds screen;
for (int k = 0; k < 2; ++k) {
vec3f pt;
pt.z = k == 0 ? bounds.lower.z : bounds.upper.z;
for (int j = 0; j < 2; ++j) {
pt.y = j == 0 ? bounds.lower.y : bounds.upper.y;
for (int i = 0; i < 2; ++i) {
pt.x = i == 0 ? bounds.lower.x : bounds.upper.x;
ProjectedPoint proj = camera->projectPoint(pt);
screen.extend(proj.screenPos);
vec3f v = pt - camera->pos;
screen.depth = std::max(dot(v, camera->dir), screen.depth);
}
}
}
return screen;
}
bool Region::operator==(const Region &b) const
{
// TODO: Do we want users to specify the ID explitly? Or should we just
// assume that two objects with the same bounds have the same id?
return id == b.id;
}
bool Region::operator<(const Region &b) const
{
return id < b.id;
}
DistributedWorld::DistributedWorld() : mpiGroup(mpicommon::worker.dup())
{
managedObjectType = OSP_WORLD;
this->ispcEquivalent = ispc::DistributedWorld_create(this);
}
box3f DistributedWorld::getBounds() const
{
box3f bounds;
for (const auto &r : allRegions) {
bounds.extend(r.bounds);
}
return bounds;
}
std::string DistributedWorld::toString() const
{
return "ospray::mpi::DistributedWorld";
}
void DistributedWorld::commit()
{
World::commit();
myRegions.clear();
localRegions = getParamDataT<box3f>("regions");
if (localRegions) {
std::copy(localRegions->begin(),
localRegions->end(),
std::back_inserter(myRegions));
} else {
// Assume we're going to treat everything on this node as a one region,
// either for data-parallel rendering or to switch to replicated
// rendering
box3f localBounds;
if (embreeSceneHandleGeometries) {
box4f b;
rtcGetSceneBounds(embreeSceneHandleGeometries, (RTCBounds *)&b);
localBounds.extend(box3f(vec3f(b.lower.x, b.lower.y, b.lower.z),
vec3f(b.upper.x, b.upper.y, b.upper.z)));
}
if (embreeSceneHandleVolumes) {
box4f b;
rtcGetSceneBounds(embreeSceneHandleVolumes, (RTCBounds *)&b);
localBounds.extend(box3f(vec3f(b.lower.x, b.lower.y, b.lower.z),
vec3f(b.upper.x, b.upper.y, b.upper.z)));
}
myRegions.push_back(localBounds);
}
// Figure out the unique regions on this node which we can send
// to the others to build the distributed world
auto last = std::unique(myRegions.begin(), myRegions.end());
myRegions.erase(last, myRegions.end());
exchangeRegions();
ispc::DistributedWorld_set(getIE(), allRegions.data(), allRegions.size());
}
void DistributedWorld::exchangeRegions()
{
allRegions.clear();
// Exchange regions between the ranks in world to find which other
// ranks may be sharing a region with this one, and the other regions
// to expect to be rendered for each tile
for (int i = 0; i < mpiGroup.size; ++i) {
if (i == mpiGroup.rank) {
int nRegions = myRegions.size();
auto sizeBcast =
mpicommon::bcast(&nRegions, 1, MPI_INT, i, mpiGroup.comm);
int nBytes = nRegions * sizeof(box3f);
auto regionBcast = mpicommon::bcast(
myRegions.data(), nBytes, MPI_BYTE, i, mpiGroup.comm);
for (const auto &b : myRegions) {
auto fnd = std::find_if(allRegions.begin(),
allRegions.end(),
[&](const Region &r) { return r.bounds == b; });
int id = -1;
if (fnd == allRegions.end()) {
id = allRegions.size();
allRegions.push_back(Region(b, id));
} else {
id = std::distance(allRegions.begin(), fnd);
}
regionOwners[id].insert(i);
myRegionIds.push_back(id);
}
// As we recv/send regions see if they're unique or not
sizeBcast.wait();
regionBcast.wait();
} else {
int nRegions = 0;
mpicommon::bcast(&nRegions, 1, MPI_INT, i, mpiGroup.comm).wait();
std::vector<box3f> recv;
recv.resize(nRegions);
int nBytes = nRegions * sizeof(box3f);
mpicommon::bcast(recv.data(), nBytes, MPI_BYTE, i, mpiGroup.comm).wait();
for (const auto &b : recv) {
auto fnd = std::find_if(allRegions.begin(),
allRegions.end(),
[&](const Region &r) { return r.bounds == b; });
int id = -1;
if (fnd == allRegions.end()) {
id = allRegions.size();
allRegions.push_back(Region(b, id));
} else {
id = std::distance(allRegions.begin(), fnd);
}
regionOwners[id].insert(i);
}
}
}
#ifndef __APPLE__
// TODO WILL: Remove this eventually? It may be useful for users to debug
// their code when setting regions. Maybe fix build on Apple? Why did
// it fail to compile?
if (logLevel() >= 3) {
for (int i = 0; i < mpiGroup.size; ++i) {
if (i == mpiGroup.rank) {
postStatusMsg(1) << "Rank " << mpiGroup.rank
<< ": All regions in world {";
for (const auto &b : allRegions) {
postStatusMsg(1) << "\t" << b << ",";
}
postStatusMsg(1) << "}\n";
postStatusMsg(1) << "Ownership Information: {";
for (const auto &r : regionOwners) {
postStatusMsg(1) << "(" << r.first << ": [";
for (const auto &i : r.second) {
postStatusMsg(1) << i << ", ";
}
postStatusMsg(1) << "])";
}
postStatusMsg(1) << "\n" << std::flush;
}
mpicommon::barrier(mpiGroup.comm).wait();
}
}
#endif
}
} // namespace mpi
} // namespace ospray
using namespace ospray::mpi;
std::ostream &operator<<(std::ostream &os, const Region &r)
{
os << "Region { id = " << r.id << ", bounds = " << r.bounds << " }";
return os;
}
<commit_msg>fix depth of regions computed when projecting<commit_after>// ======================================================================== //
// Copyright 2009-2019 Intel Corporation //
// //
// Licensed under the Apache License, Version 2.0 (the "License"); //
// you may not use this file except in compliance with the License. //
// You may obtain a copy of the License at //
// //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and //
// limitations under the License. //
// ======================================================================== //
#include "DistributedWorld.h"
#include <algorithm>
#include <iterator>
#include "DistributedWorld.h"
#include "DistributedWorld_ispc.h"
#include "MPICommon.h"
#include "Messaging.h"
#include "api/ISPCDevice.h"
#include "common/Data.h"
namespace ospray {
namespace mpi {
using namespace ospcommon;
void RegionScreenBounds::extend(const vec3f &p)
{
if (p.z < 0) {
bounds = box2f(vec2f(0), vec2f(1));
} else {
bounds.extend(vec2f(p.x * sign(p.z), p.y * sign(p.z)));
bounds.lower.x = clamp(bounds.lower.x);
bounds.upper.x = clamp(bounds.upper.x);
bounds.lower.y = clamp(bounds.lower.y);
bounds.upper.y = clamp(bounds.upper.y);
}
}
Region::Region(const box3f &bounds, int id) : bounds(bounds), id(id) {}
RegionScreenBounds Region::project(const Camera *camera) const
{
RegionScreenBounds screen;
for (int k = 0; k < 2; ++k) {
vec3f pt;
pt.z = k == 0 ? bounds.lower.z : bounds.upper.z;
for (int j = 0; j < 2; ++j) {
pt.y = j == 0 ? bounds.lower.y : bounds.upper.y;
for (int i = 0; i < 2; ++i) {
pt.x = i == 0 ? bounds.lower.x : bounds.upper.x;
ProjectedPoint proj = camera->projectPoint(pt);
screen.extend(proj.screenPos);
screen.depth = std::max(length(pt - camera->pos), screen.depth);
}
}
}
return screen;
}
bool Region::operator==(const Region &b) const
{
// TODO: Do we want users to specify the ID explitly? Or should we just
// assume that two objects with the same bounds have the same id?
return id == b.id;
}
bool Region::operator<(const Region &b) const
{
return id < b.id;
}
DistributedWorld::DistributedWorld() : mpiGroup(mpicommon::worker.dup())
{
managedObjectType = OSP_WORLD;
this->ispcEquivalent = ispc::DistributedWorld_create(this);
}
box3f DistributedWorld::getBounds() const
{
box3f bounds;
for (const auto &r : allRegions) {
bounds.extend(r.bounds);
}
return bounds;
}
std::string DistributedWorld::toString() const
{
return "ospray::mpi::DistributedWorld";
}
void DistributedWorld::commit()
{
World::commit();
myRegions.clear();
localRegions = getParamDataT<box3f>("regions");
if (localRegions) {
std::copy(localRegions->begin(),
localRegions->end(),
std::back_inserter(myRegions));
} else {
// Assume we're going to treat everything on this node as a one region,
// either for data-parallel rendering or to switch to replicated
// rendering
box3f localBounds;
if (embreeSceneHandleGeometries) {
box4f b;
rtcGetSceneBounds(embreeSceneHandleGeometries, (RTCBounds *)&b);
localBounds.extend(box3f(vec3f(b.lower.x, b.lower.y, b.lower.z),
vec3f(b.upper.x, b.upper.y, b.upper.z)));
}
if (embreeSceneHandleVolumes) {
box4f b;
rtcGetSceneBounds(embreeSceneHandleVolumes, (RTCBounds *)&b);
localBounds.extend(box3f(vec3f(b.lower.x, b.lower.y, b.lower.z),
vec3f(b.upper.x, b.upper.y, b.upper.z)));
}
myRegions.push_back(localBounds);
}
// Figure out the unique regions on this node which we can send
// to the others to build the distributed world
auto last = std::unique(myRegions.begin(), myRegions.end());
myRegions.erase(last, myRegions.end());
exchangeRegions();
ispc::DistributedWorld_set(getIE(), allRegions.data(), allRegions.size());
}
void DistributedWorld::exchangeRegions()
{
allRegions.clear();
// Exchange regions between the ranks in world to find which other
// ranks may be sharing a region with this one, and the other regions
// to expect to be rendered for each tile
for (int i = 0; i < mpiGroup.size; ++i) {
if (i == mpiGroup.rank) {
int nRegions = myRegions.size();
auto sizeBcast =
mpicommon::bcast(&nRegions, 1, MPI_INT, i, mpiGroup.comm);
int nBytes = nRegions * sizeof(box3f);
auto regionBcast = mpicommon::bcast(
myRegions.data(), nBytes, MPI_BYTE, i, mpiGroup.comm);
for (const auto &b : myRegions) {
auto fnd = std::find_if(allRegions.begin(),
allRegions.end(),
[&](const Region &r) { return r.bounds == b; });
int id = -1;
if (fnd == allRegions.end()) {
id = allRegions.size();
allRegions.push_back(Region(b, id));
} else {
id = std::distance(allRegions.begin(), fnd);
}
regionOwners[id].insert(i);
myRegionIds.push_back(id);
}
// As we recv/send regions see if they're unique or not
sizeBcast.wait();
regionBcast.wait();
} else {
int nRegions = 0;
mpicommon::bcast(&nRegions, 1, MPI_INT, i, mpiGroup.comm).wait();
std::vector<box3f> recv;
recv.resize(nRegions);
int nBytes = nRegions * sizeof(box3f);
mpicommon::bcast(recv.data(), nBytes, MPI_BYTE, i, mpiGroup.comm).wait();
for (const auto &b : recv) {
auto fnd = std::find_if(allRegions.begin(),
allRegions.end(),
[&](const Region &r) { return r.bounds == b; });
int id = -1;
if (fnd == allRegions.end()) {
id = allRegions.size();
allRegions.push_back(Region(b, id));
} else {
id = std::distance(allRegions.begin(), fnd);
}
regionOwners[id].insert(i);
}
}
}
#ifndef __APPLE__
// TODO WILL: Remove this eventually? It may be useful for users to debug
// their code when setting regions. Maybe fix build on Apple? Why did
// it fail to compile?
if (logLevel() >= 3) {
for (int i = 0; i < mpiGroup.size; ++i) {
if (i == mpiGroup.rank) {
postStatusMsg(1) << "Rank " << mpiGroup.rank
<< ": All regions in world {";
for (const auto &b : allRegions) {
postStatusMsg(1) << "\t" << b << ",";
}
postStatusMsg(1) << "}\n";
postStatusMsg(1) << "Ownership Information: {";
for (const auto &r : regionOwners) {
postStatusMsg(1) << "(" << r.first << ": [";
for (const auto &i : r.second) {
postStatusMsg(1) << i << ", ";
}
postStatusMsg(1) << "])";
}
postStatusMsg(1) << "\n" << std::flush;
}
mpicommon::barrier(mpiGroup.comm).wait();
}
}
#endif
}
} // namespace mpi
} // namespace ospray
using namespace ospray::mpi;
std::ostream &operator<<(std::ostream &os, const Region &r)
{
os << "Region { id = " << r.id << ", bounds = " << r.bounds << " }";
return os;
}
<|endoftext|> |
<commit_before>/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include <queue>
#include <memory>
#include <utility>
#include <limits>
#include <algorithm>
#include "modules/prediction/common/junction_analyzer.h"
namespace apollo {
namespace prediction {
using apollo::hdmap::LaneInfo;
using ConstLaneInfoPtr = std::shared_ptr<const LaneInfo>;
using apollo::hdmap::JunctionInfo;
using apollo::hdmap::OverlapInfo;
std::shared_ptr<const apollo::hdmap::JunctionInfo>
JunctionAnalyzer::junction_info_ptr_;
std::unordered_map<std::string, JunctionExit>
JunctionAnalyzer::junction_exits_;
std::unordered_map<std::string, JunctionFeature>
JunctionAnalyzer::junction_features_;
void JunctionAnalyzer::Init(const std::string& junction_id) {
if (junction_info_ptr_ != nullptr &&
junction_info_ptr_->id().id() == junction_id) {
return;
}
Clear();
junction_info_ptr_ = PredictionMap::JunctionById(junction_id);
SetAllJunctionExits();
}
void JunctionAnalyzer::Clear() {
// Clear all data
junction_info_ptr_ = nullptr;
junction_exits_.clear();
junction_features_.clear();
}
void JunctionAnalyzer::SetAllJunctionExits() {
CHECK_NOTNULL(junction_info_ptr_);
for (const auto &overlap_id : junction_info_ptr_->junction().overlap_id()) {
auto overlap_info_ptr = PredictionMap::OverlapById(overlap_id.id());
if (overlap_info_ptr == nullptr) {
continue;
}
// TODO(all) consider to delete
if (overlap_info_ptr->overlap().object_size() != 2) {
continue;
}
for (const auto &object : overlap_info_ptr->overlap().object()) {
if (object.has_lane_overlap_info()) {
const std::string& lane_id = object.id().id();
auto lane_info_ptr = PredictionMap::LaneById(lane_id);
// TODO(all) move 0.1 to gflags
if (object.lane_overlap_info().end_s() + 0.1 <
lane_info_ptr->total_length()) {
JunctionExit junction_exit;
double s = object.lane_overlap_info().end_s();
apollo::common::PointENU position = lane_info_ptr->GetSmoothPoint(s);
junction_exit.set_exit_lane_id(lane_id);
junction_exit.mutable_exit_position()->set_x(position.x());
junction_exit.mutable_exit_position()->set_y(position.y());
junction_exit.set_exit_heading(lane_info_ptr->Heading(s));
junction_exit.set_exit_width(lane_info_ptr->GetWidth(s));
// add junction_exit to hashtable
junction_exits_[lane_id] = junction_exit;
}
}
}
}
}
std::vector<JunctionExit> JunctionAnalyzer::GetJunctionExits(
const std::string& start_lane_id) {
int max_search_level = 3;
std::vector<JunctionExit> junction_exits;
std::queue<std::pair<ConstLaneInfoPtr, int>> lane_info_queue;
lane_info_queue.emplace(PredictionMap::LaneById(start_lane_id), 0);
while (!lane_info_queue.empty()) {
ConstLaneInfoPtr curr_lane = lane_info_queue.front().first;
int level = lane_info_queue.front().second;
lane_info_queue.pop();
const std::string& curr_lane_id = curr_lane->id().id();
if (IsExitLane(curr_lane_id)) {
// TODO(kechxu) deal with duplicates
junction_exits.push_back(junction_exits_[curr_lane_id]);
continue;
}
if (level >= max_search_level) {
continue;
}
for (const auto& succ_lane_id : curr_lane->lane().successor_id()) {
ConstLaneInfoPtr succ_lane_ptr =
PredictionMap::LaneById(succ_lane_id.id());
lane_info_queue.emplace(succ_lane_ptr, level + 1);
}
}
return junction_exits;
}
const JunctionFeature& JunctionAnalyzer::GetJunctionFeature(
const std::string& start_lane_id) {
if (junction_features_.find(start_lane_id) != junction_features_.end()) {
return junction_features_[start_lane_id];
}
JunctionFeature junction_feature;
junction_feature.set_junction_id(GetJunctionId());
junction_feature.set_junction_range(ComputeJunctionRange());
std::vector<JunctionExit> junction_exits = GetJunctionExits(start_lane_id);
for (const auto& junction_exit : junction_exits) {
junction_feature.add_junction_exit()->CopyFrom(junction_exit);
}
junction_feature.mutable_enter_lane()->set_lane_id(start_lane_id);
junction_features_[start_lane_id] = junction_feature;
return junction_features_[start_lane_id];
}
bool JunctionAnalyzer::IsExitLane(const std::string& lane_id) {
return junction_exits_.find(lane_id) != junction_exits_.end();
}
const std::string& JunctionAnalyzer::GetJunctionId() {
CHECK_NOTNULL(junction_info_ptr_);
return junction_info_ptr_->id().id();
}
double JunctionAnalyzer::ComputeJunctionRange() {
CHECK_NOTNULL(junction_info_ptr_);
if (!junction_info_ptr_->junction().has_polygon() ||
junction_info_ptr_->junction().polygon().point_size() < 3) {
AERROR << "Junction [" << GetJunctionId()
<< "] has not enough polygon points to compute range";
// TODO(kechxu) move the default range value to gflags
return 10.0;
}
double x_min = std::numeric_limits<double>::infinity();
double x_max = -std::numeric_limits<double>::infinity();
double y_min = std::numeric_limits<double>::infinity();
double y_max = -std::numeric_limits<double>::infinity();
for (const auto& point : junction_info_ptr_->junction().polygon().point()) {
x_min = std::min(x_min, point.x());
x_max = std::max(x_max, point.x());
y_min = std::min(y_min, point.y());
y_max = std::max(y_max, point.y());
}
double dx = std::abs(x_max - x_min);
double dy = std::abs(y_max - y_min);
double range = std::sqrt(dx * dx + dy * dy);
return range;
}
} // namespace prediction
} // namespace apollo
<commit_msg>Prediction: solved duplicate junction exits<commit_after>/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include <queue>
#include <memory>
#include <utility>
#include <limits>
#include <algorithm>
#include <unordered_set>
#include "modules/prediction/common/junction_analyzer.h"
namespace apollo {
namespace prediction {
using apollo::hdmap::LaneInfo;
using ConstLaneInfoPtr = std::shared_ptr<const LaneInfo>;
using apollo::hdmap::JunctionInfo;
using apollo::hdmap::OverlapInfo;
std::shared_ptr<const apollo::hdmap::JunctionInfo>
JunctionAnalyzer::junction_info_ptr_;
std::unordered_map<std::string, JunctionExit>
JunctionAnalyzer::junction_exits_;
std::unordered_map<std::string, JunctionFeature>
JunctionAnalyzer::junction_features_;
void JunctionAnalyzer::Init(const std::string& junction_id) {
if (junction_info_ptr_ != nullptr &&
junction_info_ptr_->id().id() == junction_id) {
return;
}
Clear();
junction_info_ptr_ = PredictionMap::JunctionById(junction_id);
SetAllJunctionExits();
}
void JunctionAnalyzer::Clear() {
// Clear all data
junction_info_ptr_ = nullptr;
junction_exits_.clear();
junction_features_.clear();
}
void JunctionAnalyzer::SetAllJunctionExits() {
CHECK_NOTNULL(junction_info_ptr_);
for (const auto &overlap_id : junction_info_ptr_->junction().overlap_id()) {
auto overlap_info_ptr = PredictionMap::OverlapById(overlap_id.id());
if (overlap_info_ptr == nullptr) {
continue;
}
// TODO(all) consider to delete
if (overlap_info_ptr->overlap().object_size() != 2) {
continue;
}
for (const auto &object : overlap_info_ptr->overlap().object()) {
if (object.has_lane_overlap_info()) {
const std::string& lane_id = object.id().id();
auto lane_info_ptr = PredictionMap::LaneById(lane_id);
// TODO(all) move 0.1 to gflags
if (object.lane_overlap_info().end_s() + 0.1 <
lane_info_ptr->total_length()) {
JunctionExit junction_exit;
double s = object.lane_overlap_info().end_s();
apollo::common::PointENU position = lane_info_ptr->GetSmoothPoint(s);
junction_exit.set_exit_lane_id(lane_id);
junction_exit.mutable_exit_position()->set_x(position.x());
junction_exit.mutable_exit_position()->set_y(position.y());
junction_exit.set_exit_heading(lane_info_ptr->Heading(s));
junction_exit.set_exit_width(lane_info_ptr->GetWidth(s));
// add junction_exit to hashtable
junction_exits_[lane_id] = junction_exit;
}
}
}
}
}
std::vector<JunctionExit> JunctionAnalyzer::GetJunctionExits(
const std::string& start_lane_id) {
int max_search_level = 3;
std::vector<JunctionExit> junction_exits;
std::queue<std::pair<ConstLaneInfoPtr, int>> lane_info_queue;
lane_info_queue.emplace(PredictionMap::LaneById(start_lane_id), 0);
while (!lane_info_queue.empty()) {
ConstLaneInfoPtr curr_lane = lane_info_queue.front().first;
int level = lane_info_queue.front().second;
lane_info_queue.pop();
const std::string& curr_lane_id = curr_lane->id().id();
std::unordered_set<std::string> visited_exit_lanes;
if (IsExitLane(curr_lane_id) &&
visited_exit_lanes.find(curr_lane_id) == visited_exit_lanes.end()) {
junction_exits.push_back(junction_exits_[curr_lane_id]);
visited_exit_lanes.insert(curr_lane_id);
continue;
}
if (level >= max_search_level) {
continue;
}
for (const auto& succ_lane_id : curr_lane->lane().successor_id()) {
ConstLaneInfoPtr succ_lane_ptr =
PredictionMap::LaneById(succ_lane_id.id());
lane_info_queue.emplace(succ_lane_ptr, level + 1);
}
}
return junction_exits;
}
const JunctionFeature& JunctionAnalyzer::GetJunctionFeature(
const std::string& start_lane_id) {
if (junction_features_.find(start_lane_id) != junction_features_.end()) {
return junction_features_[start_lane_id];
}
JunctionFeature junction_feature;
junction_feature.set_junction_id(GetJunctionId());
junction_feature.set_junction_range(ComputeJunctionRange());
std::vector<JunctionExit> junction_exits = GetJunctionExits(start_lane_id);
for (const auto& junction_exit : junction_exits) {
junction_feature.add_junction_exit()->CopyFrom(junction_exit);
}
junction_feature.mutable_enter_lane()->set_lane_id(start_lane_id);
junction_features_[start_lane_id] = junction_feature;
return junction_features_[start_lane_id];
}
bool JunctionAnalyzer::IsExitLane(const std::string& lane_id) {
return junction_exits_.find(lane_id) != junction_exits_.end();
}
const std::string& JunctionAnalyzer::GetJunctionId() {
CHECK_NOTNULL(junction_info_ptr_);
return junction_info_ptr_->id().id();
}
double JunctionAnalyzer::ComputeJunctionRange() {
CHECK_NOTNULL(junction_info_ptr_);
if (!junction_info_ptr_->junction().has_polygon() ||
junction_info_ptr_->junction().polygon().point_size() < 3) {
AERROR << "Junction [" << GetJunctionId()
<< "] has not enough polygon points to compute range";
// TODO(kechxu) move the default range value to gflags
return 10.0;
}
double x_min = std::numeric_limits<double>::infinity();
double x_max = -std::numeric_limits<double>::infinity();
double y_min = std::numeric_limits<double>::infinity();
double y_max = -std::numeric_limits<double>::infinity();
for (const auto& point : junction_info_ptr_->junction().polygon().point()) {
x_min = std::min(x_min, point.x());
x_max = std::max(x_max, point.x());
y_min = std::min(y_min, point.y());
y_max = std::max(y_max, point.y());
}
double dx = std::abs(x_max - x_min);
double dy = std::abs(y_max - y_min);
double range = std::sqrt(dx * dx + dy * dy);
return range;
}
} // namespace prediction
} // namespace apollo
<|endoftext|> |
<commit_before>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "idstring.h"
#include "idstringexception.h"
#include <vespa/document/bucket/bucketid.h>
#include <vespa/vespalib/util/md5.h>
#include <vespa/vespalib/util/stringfmt.h>
#include <vespa/vespalib/util/optimized.h>
#include <cerrno>
#include <cstring>
using vespalib::string;
using vespalib::stringref;
using vespalib::make_string;
namespace document {
VESPA_IMPLEMENT_EXCEPTION(IdParseException, vespalib::Exception);
namespace {
void reportError(const char* part) __attribute__((noinline));
void reportTooShortDocId(const char * id, size_t sz) __attribute__((noinline));
void reportNoSchemeSeparator(const char * id) __attribute__((noinline));
void reportNoId(const char * id) __attribute__((noinline));
void
reportError(const char* part) {
throw IdParseException(make_string("Unparseable id: No %s separator ':' found", part), VESPA_STRLOC);
}
void
reportNoSchemeSeparator(const char * id) {
throw IdParseException(make_string("Unparseable id '%s': No scheme separator ':' found", id), VESPA_STRLOC);
}
void
reportNoId(const char * id){
throw IdParseException(make_string("Unparseable id '%s': No 'id:' found", id), VESPA_STRLOC);
}
void
reportTooShortDocId(const char * id, size_t sz) {
throw IdParseException( make_string( "Unparseable id '%s': It is too short(%li) " "to make any sense", id, sz), VESPA_STRLOC);
}
union TwoByte {
char asChar[2];
uint16_t as16;
};
union FourByte {
char asChar[4];
uint32_t as32;
};
const FourByte _G_null = {{'n', 'u', 'l', 'l'}};
const TwoByte _G_id = {{'i', 'd'}};
#ifdef __x86_64__
typedef char v16qi __attribute__ ((__vector_size__(16)));
v16qi _G_zero = { ':', ':', ':', ':', ':', ':', ':', ':', ':', ':', ':', ':', ':', ':', ':', ':' };
#endif
inline const char *
fmemchr(const char * s, const char * e)
{
#ifdef __x86_64__
while (s+15 < e) {
#ifdef __clang__
v16qi tmpCurrent = __builtin_ia32_lddqu(s);
v16qi tmp0 = tmpCurrent == _G_zero;
#else
v16qi tmpCurrent = __builtin_ia32_loaddqu(s);
v16qi tmp0 = __builtin_ia32_pcmpeqb128(tmpCurrent, _G_zero);
#endif
uint32_t charMap = __builtin_ia32_pmovmskb128(tmp0); // 1 in charMap equals to '\0' in input buffer
if (__builtin_expect(charMap, 1)) {
return s + vespalib::Optimized::lsbIdx(charMap);
}
s+=16;
}
const char c(':');
while (s+3 < e) {
if (s[0] == c) {
return s;
}
if (s[1] == c) {
return s+1;
}
if (s[2] == c) {
return s+2;
}
if (s[3] == c) {
return s+3;
}
s+=4;
}
while (s < e) {
if (s[0] == c) {
return s;
}
s++;
}
return nullptr;
#else
return static_cast<const char *>(memchr(s, ':', e - s));
#endif
}
void
verifyIdString(const char * id, size_t sz_)
{
if (sz_ > 4) {
if (_G_id.as16 == *reinterpret_cast<const uint16_t *>(id) && id[2] == ':') {
return;
} else if ((sz_ == 6) && (_G_null.as32 == *reinterpret_cast<const uint32_t *>(id)) && (id[4] == ':') && (id[5] == ':')) {
reportNoId(id);
} else if (sz_ > 8) {
reportNoSchemeSeparator(id);
} else {
reportTooShortDocId(id, 8);
}
} else {
reportTooShortDocId(id, 5);
}
}
void
validate(uint16_t numComponents)
{
if (numComponents < 2) {
reportError("namespace");
}
if (numComponents < 3) {
reportError("document type");
}
if (numComponents < 4) {
reportError("key/value-pairs");
}
}
constexpr uint32_t NAMESPACE_OFFSET = 3;
const vespalib::stringref DEFAULT_ID("id::::");
union LocationUnion {
uint8_t _key[16];
IdString::LocationType _location[2];
};
uint64_t parseNumber(stringref number) {
char* errPos = nullptr;
errno = 0;
uint64_t n = strtoul(number.data(), &errPos, 10);
if (*errPos) {
throw IdParseException("'n'-value must be a 64-bit number. It was " + number, VESPA_STRLOC);
}
if (errno == ERANGE) {
throw IdParseException("'n'-value out of range (" + number + ")", VESPA_STRLOC);
}
return n;
}
void setLocation(IdString::LocationType &loc, IdString::LocationType val,
bool &has_set_location, stringref key_values) {
if (has_set_location) {
throw IdParseException("Illegal key combination in " + key_values);
}
loc = val;
has_set_location = true;
}
} // namespace
const IdString::Offsets IdString::Offsets::DefaultID(DEFAULT_ID);
IdString::Offsets::Offsets(stringref id)
: _offsets()
{
compute(id);
}
uint16_t
IdString::Offsets::compute(stringref id)
{
_offsets[0] = NAMESPACE_OFFSET;
size_t index(1);
const char * s(id.data() + NAMESPACE_OFFSET);
const char * e(id.data() + id.size());
for(s=fmemchr(s, e);
(s != nullptr) && (index < MAX_COMPONENTS);
s = fmemchr(s+1, e))
{
_offsets[index++] = s - id.data() + 1;
}
uint16_t numComponents = index;
for (;index < VESPA_NELEMS(_offsets); index++) {
_offsets[index] = id.size() + 1; // 1 is added due to the implicitt accounting for ':'
}
return numComponents;
}
IdString::LocationType
IdString::makeLocation(stringref s) {
LocationUnion location;
fastc_md5sum(reinterpret_cast<const unsigned char*>(s.data()), s.size(), location._key);
return location._location[0];
}
IdString::IdString()
: _rawId(DEFAULT_ID),
_location(0),
_offsets(Offsets::DefaultID),
_groupOffset(0),
_has_number(false)
{
}
IdString::IdString(stringref id)
: _rawId(id),
_location(0),
_offsets(),
_groupOffset(0),
_has_number(false)
{
// TODO(magnarn): Require that keys are lexicographically ordered.
verifyIdString(id.data(), id.size());
validate(_offsets.compute(id));
stringref key_values(getComponent(2));
char key(0);
string::size_type pos = 0;
bool has_set_location = false;
bool hasFoundKey(false);
for (string::size_type i = 0; i < key_values.size(); ++i) {
if (!hasFoundKey && (key_values[i] == '=')) {
key = key_values[i-1];
pos = i + 1;
hasFoundKey = true;
} else if (key_values[i] == ',' || i == key_values.size() - 1) {
stringref value(key_values.substr(pos, i - pos + (i == key_values.size() - 1)));
if (key == 'n') {
char tmp=value[value.size()];
const_cast<char &>(value[value.size()]) = 0;
setLocation(_location, parseNumber(value), has_set_location, key_values);
_has_number = true;
const_cast<char &>(value[value.size()]) = tmp;
} else if (key == 'g') {
setLocation(_location, makeLocation(value), has_set_location, key_values);
_groupOffset = offset(2) + pos;
} else {
throw IdParseException(make_string("Illegal key '%c'", key));
}
pos = i + 1;
hasFoundKey = false;
}
}
if (!has_set_location) {
_location = makeLocation(getNamespaceSpecific());
}
}
} // document
<commit_msg>Handle unaligned IdString reads in a well-defined manner<commit_after>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "idstring.h"
#include "idstringexception.h"
#include <vespa/document/bucket/bucketid.h>
#include <vespa/vespalib/util/md5.h>
#include <vespa/vespalib/util/stringfmt.h>
#include <vespa/vespalib/util/optimized.h>
#include <cerrno>
#include <cstring>
using vespalib::string;
using vespalib::stringref;
using vespalib::make_string;
namespace document {
VESPA_IMPLEMENT_EXCEPTION(IdParseException, vespalib::Exception);
namespace {
void reportError(const char* part) __attribute__((noinline));
void reportTooShortDocId(const char * id, size_t sz) __attribute__((noinline));
void reportNoSchemeSeparator(const char * id) __attribute__((noinline));
void reportNoId(const char * id) __attribute__((noinline));
void
reportError(const char* part) {
throw IdParseException(make_string("Unparseable id: No %s separator ':' found", part), VESPA_STRLOC);
}
void
reportNoSchemeSeparator(const char * id) {
throw IdParseException(make_string("Unparseable id '%s': No scheme separator ':' found", id), VESPA_STRLOC);
}
void
reportNoId(const char * id){
throw IdParseException(make_string("Unparseable id '%s': No 'id:' found", id), VESPA_STRLOC);
}
void
reportTooShortDocId(const char * id, size_t sz) {
throw IdParseException( make_string( "Unparseable id '%s': It is too short(%li) " "to make any sense", id, sz), VESPA_STRLOC);
}
union TwoByte {
char asChar[2];
uint16_t as16;
};
union FourByte {
char asChar[4];
uint32_t as32;
};
const FourByte _G_null = {{'n', 'u', 'l', 'l'}};
const TwoByte _G_id = {{'i', 'd'}};
#ifdef __x86_64__
typedef char v16qi __attribute__ ((__vector_size__(16)));
v16qi _G_zero = { ':', ':', ':', ':', ':', ':', ':', ':', ':', ':', ':', ':', ':', ':', ':', ':' };
#endif
inline const char *
fmemchr(const char * s, const char * e)
{
#ifdef __x86_64__
while (s+15 < e) {
#ifdef __clang__
v16qi tmpCurrent = __builtin_ia32_lddqu(s);
v16qi tmp0 = tmpCurrent == _G_zero;
#else
v16qi tmpCurrent = __builtin_ia32_loaddqu(s);
v16qi tmp0 = __builtin_ia32_pcmpeqb128(tmpCurrent, _G_zero);
#endif
uint32_t charMap = __builtin_ia32_pmovmskb128(tmp0); // 1 in charMap equals to '\0' in input buffer
if (__builtin_expect(charMap, 1)) {
return s + vespalib::Optimized::lsbIdx(charMap);
}
s+=16;
}
const char c(':');
while (s+3 < e) {
if (s[0] == c) {
return s;
}
if (s[1] == c) {
return s+1;
}
if (s[2] == c) {
return s+2;
}
if (s[3] == c) {
return s+3;
}
s+=4;
}
while (s < e) {
if (s[0] == c) {
return s;
}
s++;
}
return nullptr;
#else
return static_cast<const char *>(memchr(s, ':', e - s));
#endif
}
namespace {
// Avoid issues with primitive alignment when reading from buffer.
// Requires caller to ensure buffer is big enough to read from.
template <typename T>
inline T read_unaligned(const char* buf) noexcept
{
T tmp;
memcpy(&tmp, buf, sizeof(T));
return tmp;
}
}
void
verifyIdString(const char * id, size_t sz_)
{
if (sz_ > 4) {
if ((_G_id.as16 == read_unaligned<uint16_t>(id)) && (id[2] == ':')) {
return;
} else if ((sz_ == 6) && (_G_null.as32 == read_unaligned<uint32_t>(id)) && (id[4] == ':') && (id[5] == ':')) {
reportNoId(id);
} else if (sz_ > 8) {
reportNoSchemeSeparator(id);
} else {
reportTooShortDocId(id, 8);
}
} else {
reportTooShortDocId(id, 5);
}
}
void
validate(uint16_t numComponents)
{
if (numComponents < 2) {
reportError("namespace");
}
if (numComponents < 3) {
reportError("document type");
}
if (numComponents < 4) {
reportError("key/value-pairs");
}
}
constexpr uint32_t NAMESPACE_OFFSET = 3;
const vespalib::stringref DEFAULT_ID("id::::");
union LocationUnion {
uint8_t _key[16];
IdString::LocationType _location[2];
};
uint64_t parseNumber(stringref number) {
char* errPos = nullptr;
errno = 0;
uint64_t n = strtoul(number.data(), &errPos, 10);
if (*errPos) {
throw IdParseException("'n'-value must be a 64-bit number. It was " + number, VESPA_STRLOC);
}
if (errno == ERANGE) {
throw IdParseException("'n'-value out of range (" + number + ")", VESPA_STRLOC);
}
return n;
}
void setLocation(IdString::LocationType &loc, IdString::LocationType val,
bool &has_set_location, stringref key_values) {
if (has_set_location) {
throw IdParseException("Illegal key combination in " + key_values);
}
loc = val;
has_set_location = true;
}
} // namespace
const IdString::Offsets IdString::Offsets::DefaultID(DEFAULT_ID);
IdString::Offsets::Offsets(stringref id)
: _offsets()
{
compute(id);
}
uint16_t
IdString::Offsets::compute(stringref id)
{
_offsets[0] = NAMESPACE_OFFSET;
size_t index(1);
const char * s(id.data() + NAMESPACE_OFFSET);
const char * e(id.data() + id.size());
for(s=fmemchr(s, e);
(s != nullptr) && (index < MAX_COMPONENTS);
s = fmemchr(s+1, e))
{
_offsets[index++] = s - id.data() + 1;
}
uint16_t numComponents = index;
for (;index < VESPA_NELEMS(_offsets); index++) {
_offsets[index] = id.size() + 1; // 1 is added due to the implicitt accounting for ':'
}
return numComponents;
}
IdString::LocationType
IdString::makeLocation(stringref s) {
LocationUnion location;
fastc_md5sum(reinterpret_cast<const unsigned char*>(s.data()), s.size(), location._key);
return location._location[0];
}
IdString::IdString()
: _rawId(DEFAULT_ID),
_location(0),
_offsets(Offsets::DefaultID),
_groupOffset(0),
_has_number(false)
{
}
IdString::IdString(stringref id)
: _rawId(id),
_location(0),
_offsets(),
_groupOffset(0),
_has_number(false)
{
// TODO(magnarn): Require that keys are lexicographically ordered.
verifyIdString(id.data(), id.size());
validate(_offsets.compute(id));
stringref key_values(getComponent(2));
char key(0);
string::size_type pos = 0;
bool has_set_location = false;
bool hasFoundKey(false);
for (string::size_type i = 0; i < key_values.size(); ++i) {
if (!hasFoundKey && (key_values[i] == '=')) {
key = key_values[i-1];
pos = i + 1;
hasFoundKey = true;
} else if (key_values[i] == ',' || i == key_values.size() - 1) {
stringref value(key_values.substr(pos, i - pos + (i == key_values.size() - 1)));
if (key == 'n') {
char tmp=value[value.size()];
const_cast<char &>(value[value.size()]) = 0;
setLocation(_location, parseNumber(value), has_set_location, key_values);
_has_number = true;
const_cast<char &>(value[value.size()]) = tmp;
} else if (key == 'g') {
setLocation(_location, makeLocation(value), has_set_location, key_values);
_groupOffset = offset(2) + pos;
} else {
throw IdParseException(make_string("Illegal key '%c'", key));
}
pos = i + 1;
hasFoundKey = false;
}
}
if (!has_set_location) {
_location = makeLocation(getNamespaceSpecific());
}
}
} // document
<|endoftext|> |
<commit_before>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2011, Alexandru-Eugen Ichim
* 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 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.
*
*/
/*///@todo PCL_INSTANTIATE does not work; error: expected constructor, destructor, or type conversion before PCL_INSTANTIATE_PPFRegistration
#include "pcl/point_types.h"
#include "pcl/impl/instantiate.hpp"
#include "pcl/registration/ppf_registration.h"
#include "pcl/registration/impl/ppf_registration.hpp"
PCL_INSTANTIATE_PRODUCT(PPFRegistration, (PCL_XYZ_POINT_TYPES)(PCL_NORMAL_POINT_TYPES));
*/
<commit_msg>more fixes<commit_after>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2011, Alexandru-Eugen Ichim
* 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 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.
*
*/
/** Re-enable these once all of registration is separated into H/HPP correctly. */
//#include "pcl/point_types.h"
//#include "pcl/impl/instantiate.hpp"
//#include "pcl/registration/ppf_registration.h"
//#include "pcl/registration/impl/ppf_registration.hpp"
//
//PCL_INSTANTIATE_PRODUCT(PPFRegistration, (PCL_XYZ_POINT_TYPES)(PCL_NORMAL_POINT_TYPES));
//
<|endoftext|> |
<commit_before>// Time: O(n)
// Space: O(1)
class Solution {
public:
bool isPalindrome(string s) {
int i = 0, j = s.length() - 1;
while (i < j) {
if (!isalnum(s[i])) {
++i;
} else if (!isalnum(s[j])) {
--j;
} else if (tolower(s[i]) != tolower(s[j])) {
return false;
} else {
++i, --j;
}
}
return true;
}
};
// Time: O(n)
// Space: O(1)
// Iterator solution.
class Solution2 {
public:
bool isPalindrome(string s) {
auto left = s.begin();
auto right = prev(s.end());
for(; left < right;) {
if(!isalnum(*left)) {
++left;
} else if(!isalnum(*right)) {
--right;
} else if(tolower(*left) != tolower(*right)) {
return false;
} else {
++left, --right;
}
}
return true;
}
};
<commit_msg>Update valid-palindrome.cpp<commit_after>// Time: O(n)
// Space: O(1)
class Solution {
public:
bool isPalindrome(string s) {
int i = 0, j = s.length() - 1;
while (i < j) {
if (!isalnum(s[i])) {
++i;
} else if (!isalnum(s[j])) {
--j;
} else if (tolower(s[i]) != tolower(s[j])) {
return false;
} else {
++i, --j;
}
}
return true;
}
};
// Time: O(n)
// Space: O(1)
// Iterator solution.
class Solution2 {
public:
bool isPalindrome(string s) {
auto left = s.begin();
auto right = prev(s.end());
while (left < right) {
if (!isalnum(*left)) {
++left;
} else if (!isalnum(*right)) {
--right;
} else if (tolower(*left) != tolower(*right)) {
return false;
} else {
++left, --right;
}
}
return true;
}
};
<|endoftext|> |
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/file_path.h"
#include "base/gfx/native_widget_types.h"
#include "base/string_util.h"
#include "base/sys_info.h"
#include "base/values.h"
#include "chrome/app/chrome_dll_resource.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/platform_util.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/window_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"
#include "net/url_request/url_request_unittest.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
namespace {
class BrowserTest : public UITest {
protected:
#if defined(OS_WIN)
HWND GetMainWindow() {
scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
scoped_refptr<WindowProxy> window(browser->GetWindow());
HWND window_handle;
EXPECT_TRUE(window->GetHWND(&window_handle));
return window_handle;
}
#endif
};
class VisibleBrowserTest : public UITest {
protected:
VisibleBrowserTest() : UITest() {
show_window_ = true;
}
};
#if defined(OS_WIN)
// The browser should quit quickly if it receives a WM_ENDSESSION message.
TEST_F(BrowserTest, WindowsSessionEnd) {
FilePath test_file(test_data_directory_);
test_file = test_file.AppendASCII("title1.html");
NavigateToURL(net::FilePathToFileURL(test_file));
PlatformThread::Sleep(action_timeout_ms());
// Simulate an end of session. Normally this happens when the user
// shuts down the pc or logs off.
HWND window_handle = GetMainWindow();
ASSERT_TRUE(::PostMessageW(window_handle, WM_ENDSESSION, 0, 0));
PlatformThread::Sleep(action_timeout_ms());
ASSERT_FALSE(IsBrowserRunning());
// Make sure the UMA metrics say we didn't crash.
scoped_ptr<DictionaryValue> local_prefs(GetLocalState());
bool exited_cleanly;
ASSERT_TRUE(local_prefs.get());
ASSERT_TRUE(local_prefs->GetBoolean(prefs::kStabilityExitedCleanly,
&exited_cleanly));
ASSERT_TRUE(exited_cleanly);
// And that session end was successful.
bool session_end_completed;
ASSERT_TRUE(local_prefs->GetBoolean(prefs::kStabilitySessionEndCompleted,
&session_end_completed));
ASSERT_TRUE(session_end_completed);
// Make sure session restore says we didn't crash.
scoped_ptr<DictionaryValue> profile_prefs(GetDefaultProfilePreferences());
ASSERT_TRUE(profile_prefs.get());
ASSERT_TRUE(profile_prefs->GetBoolean(prefs::kSessionExitedCleanly,
&exited_cleanly));
ASSERT_TRUE(exited_cleanly);
}
#endif
// Test that scripts can fork a new renderer process for a tab in a particular
// case (which matches following a link in Gmail). The script must open a new
// tab, set its window.opener to null, and redirect it to a cross-site URL.
// (Bug 1115708)
// This test can only run if V8 is in use, and not KJS, because KJS will not
// set window.opener to null properly.
#ifdef CHROME_V8
TEST_F(BrowserTest, NullOpenerRedirectForksProcess) {
// This test only works in multi-process mode
if (in_process_renderer())
return;
const wchar_t kDocRoot[] = L"chrome/test/data";
scoped_refptr<HTTPTestServer> server =
HTTPTestServer::CreateServer(kDocRoot, NULL);
ASSERT_TRUE(NULL != server.get());
FilePath test_file(test_data_directory_);
scoped_refptr<BrowserProxy> window(automation()->GetBrowserWindow(0));
scoped_refptr<TabProxy> tab(window->GetActiveTab());
ASSERT_TRUE(tab.get());
// Start with a file:// url
test_file = test_file.AppendASCII("title2.html");
tab->NavigateToURL(net::FilePathToFileURL(test_file));
int orig_tab_count = -1;
ASSERT_TRUE(window->GetTabCount(&orig_tab_count));
int orig_process_count = GetBrowserProcessCount();
ASSERT_GE(orig_process_count, 1);
// Use JavaScript URL to "fork" a new tab, just like Gmail. (Open tab to a
// blank page, set its opener to null, and redirect it cross-site.)
std::wstring url_prefix(L"javascript:(function(){w=window.open();");
GURL fork_url(url_prefix +
L"w.opener=null;w.document.location=\"http://localhost:1337\";})()");
// Make sure that a new tab has been created and that we have a new renderer
// process for it.
ASSERT_TRUE(tab->NavigateToURLAsync(fork_url));
PlatformThread::Sleep(action_timeout_ms());
ASSERT_EQ(orig_process_count + 1, GetBrowserProcessCount());
int new_tab_count = -1;
ASSERT_TRUE(window->GetTabCount(&new_tab_count));
ASSERT_EQ(orig_tab_count + 1, new_tab_count);
}
#endif
#if !defined(OS_LINUX)
// TODO(port): This passes on linux locally, but fails on the try bot.
// Tests that non-Gmail-like script redirects (i.e., non-null window.opener) or
// a same-page-redirect) will not fork a new process.
TEST_F(BrowserTest, OtherRedirectsDontForkProcess) {
// This test only works in multi-process mode
if (in_process_renderer())
return;
const wchar_t kDocRoot[] = L"chrome/test/data";
scoped_refptr<HTTPTestServer> server =
HTTPTestServer::CreateServer(kDocRoot, NULL);
ASSERT_TRUE(NULL != server.get());
FilePath test_file(test_data_directory_);
scoped_refptr<BrowserProxy> window(automation()->GetBrowserWindow(0));
scoped_refptr<TabProxy> tab(window->GetActiveTab());
ASSERT_TRUE(tab.get());
// Start with a file:// url
test_file = test_file.AppendASCII("title2.html");
tab->NavigateToURL(net::FilePathToFileURL(test_file));
int orig_tab_count = -1;
ASSERT_TRUE(window->GetTabCount(&orig_tab_count));
int orig_process_count = GetBrowserProcessCount();
ASSERT_GE(orig_process_count, 1);
// Use JavaScript URL to almost fork a new tab, but not quite. (Leave the
// opener non-null.) Should not fork a process.
std::string url_prefix("javascript:(function(){w=window.open();");
GURL dont_fork_url(url_prefix +
"w.document.location=\"http://localhost:1337\";})()");
// Make sure that a new tab but not new process has been created.
ASSERT_TRUE(tab->NavigateToURLAsync(dont_fork_url));
PlatformThread::Sleep(action_timeout_ms());
ASSERT_EQ(orig_process_count, GetBrowserProcessCount());
int new_tab_count = -1;
ASSERT_TRUE(window->GetTabCount(&new_tab_count));
ASSERT_EQ(orig_tab_count + 1, new_tab_count);
// Same thing if the current tab tries to redirect itself.
GURL dont_fork_url2(url_prefix +
"document.location=\"http://localhost:1337\";})()");
// Make sure that no new process has been created.
ASSERT_TRUE(tab->NavigateToURLAsync(dont_fork_url2));
PlatformThread::Sleep(action_timeout_ms());
ASSERT_EQ(orig_process_count, GetBrowserProcessCount());
}
#endif
#if defined(OS_WIN)
// TODO(estade): need to port GetActiveTabTitle().
TEST_F(VisibleBrowserTest, WindowOpenClose) {
FilePath test_file(test_data_directory_);
test_file = test_file.AppendASCII("window.close.html");
NavigateToURL(net::FilePathToFileURL(test_file));
int i;
for (i = 0; i < 10; ++i) {
PlatformThread::Sleep(action_max_timeout_ms() / 10);
std::wstring title = GetActiveTabTitle();
if (title == L"PASSED") {
// Success, bail out.
break;
}
}
if (i == 10)
FAIL() << "failed to get error page title";
}
#endif
#if defined(OS_WIN) // only works on Windows for now: http:://crbug.com/15891
class ShowModalDialogTest : public UITest {
public:
ShowModalDialogTest() {
launch_arguments_.AppendSwitch(switches::kDisablePopupBlocking);
}
};
TEST_F(ShowModalDialogTest, BasicTest) {
// Test that a modal dialog is shown.
FilePath test_file(test_data_directory_);
test_file = test_file.AppendASCII("showmodaldialog.html");
NavigateToURL(net::FilePathToFileURL(test_file));
ASSERT_TRUE(automation()->WaitForWindowCountToBecome(
2, action_max_timeout_ms()));
scoped_refptr<BrowserProxy> browser = automation()->GetBrowserWindow(1);
scoped_refptr<TabProxy> tab = browser->GetActiveTab();
ASSERT_TRUE(tab.get());
std::wstring title;
ASSERT_TRUE(tab->GetTabTitle(&title));
ASSERT_EQ(title, L"ModalDialogTitle");
// Test that window.close() works. Since we don't have a way of executing a
// JS function on the page through TabProxy, reload it and use an unload
// handler that closes the page.
ASSERT_EQ(tab->Reload(), AUTOMATION_MSG_NAVIGATION_SUCCESS);
ASSERT_TRUE(automation()->WaitForWindowCountToBecome(
1, action_max_timeout_ms()));
}
#endif
} // namespace
<commit_msg>Disable flaky ShowModalDialogTest.BasicTest<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/file_path.h"
#include "base/gfx/native_widget_types.h"
#include "base/string_util.h"
#include "base/sys_info.h"
#include "base/values.h"
#include "chrome/app/chrome_dll_resource.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/platform_util.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/window_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"
#include "net/url_request/url_request_unittest.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
namespace {
class BrowserTest : public UITest {
protected:
#if defined(OS_WIN)
HWND GetMainWindow() {
scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
scoped_refptr<WindowProxy> window(browser->GetWindow());
HWND window_handle;
EXPECT_TRUE(window->GetHWND(&window_handle));
return window_handle;
}
#endif
};
class VisibleBrowserTest : public UITest {
protected:
VisibleBrowserTest() : UITest() {
show_window_ = true;
}
};
#if defined(OS_WIN)
// The browser should quit quickly if it receives a WM_ENDSESSION message.
TEST_F(BrowserTest, WindowsSessionEnd) {
FilePath test_file(test_data_directory_);
test_file = test_file.AppendASCII("title1.html");
NavigateToURL(net::FilePathToFileURL(test_file));
PlatformThread::Sleep(action_timeout_ms());
// Simulate an end of session. Normally this happens when the user
// shuts down the pc or logs off.
HWND window_handle = GetMainWindow();
ASSERT_TRUE(::PostMessageW(window_handle, WM_ENDSESSION, 0, 0));
PlatformThread::Sleep(action_timeout_ms());
ASSERT_FALSE(IsBrowserRunning());
// Make sure the UMA metrics say we didn't crash.
scoped_ptr<DictionaryValue> local_prefs(GetLocalState());
bool exited_cleanly;
ASSERT_TRUE(local_prefs.get());
ASSERT_TRUE(local_prefs->GetBoolean(prefs::kStabilityExitedCleanly,
&exited_cleanly));
ASSERT_TRUE(exited_cleanly);
// And that session end was successful.
bool session_end_completed;
ASSERT_TRUE(local_prefs->GetBoolean(prefs::kStabilitySessionEndCompleted,
&session_end_completed));
ASSERT_TRUE(session_end_completed);
// Make sure session restore says we didn't crash.
scoped_ptr<DictionaryValue> profile_prefs(GetDefaultProfilePreferences());
ASSERT_TRUE(profile_prefs.get());
ASSERT_TRUE(profile_prefs->GetBoolean(prefs::kSessionExitedCleanly,
&exited_cleanly));
ASSERT_TRUE(exited_cleanly);
}
#endif
// Test that scripts can fork a new renderer process for a tab in a particular
// case (which matches following a link in Gmail). The script must open a new
// tab, set its window.opener to null, and redirect it to a cross-site URL.
// (Bug 1115708)
// This test can only run if V8 is in use, and not KJS, because KJS will not
// set window.opener to null properly.
#ifdef CHROME_V8
TEST_F(BrowserTest, NullOpenerRedirectForksProcess) {
// This test only works in multi-process mode
if (in_process_renderer())
return;
const wchar_t kDocRoot[] = L"chrome/test/data";
scoped_refptr<HTTPTestServer> server =
HTTPTestServer::CreateServer(kDocRoot, NULL);
ASSERT_TRUE(NULL != server.get());
FilePath test_file(test_data_directory_);
scoped_refptr<BrowserProxy> window(automation()->GetBrowserWindow(0));
scoped_refptr<TabProxy> tab(window->GetActiveTab());
ASSERT_TRUE(tab.get());
// Start with a file:// url
test_file = test_file.AppendASCII("title2.html");
tab->NavigateToURL(net::FilePathToFileURL(test_file));
int orig_tab_count = -1;
ASSERT_TRUE(window->GetTabCount(&orig_tab_count));
int orig_process_count = GetBrowserProcessCount();
ASSERT_GE(orig_process_count, 1);
// Use JavaScript URL to "fork" a new tab, just like Gmail. (Open tab to a
// blank page, set its opener to null, and redirect it cross-site.)
std::wstring url_prefix(L"javascript:(function(){w=window.open();");
GURL fork_url(url_prefix +
L"w.opener=null;w.document.location=\"http://localhost:1337\";})()");
// Make sure that a new tab has been created and that we have a new renderer
// process for it.
ASSERT_TRUE(tab->NavigateToURLAsync(fork_url));
PlatformThread::Sleep(action_timeout_ms());
ASSERT_EQ(orig_process_count + 1, GetBrowserProcessCount());
int new_tab_count = -1;
ASSERT_TRUE(window->GetTabCount(&new_tab_count));
ASSERT_EQ(orig_tab_count + 1, new_tab_count);
}
#endif
#if !defined(OS_LINUX)
// TODO(port): This passes on linux locally, but fails on the try bot.
// Tests that non-Gmail-like script redirects (i.e., non-null window.opener) or
// a same-page-redirect) will not fork a new process.
TEST_F(BrowserTest, OtherRedirectsDontForkProcess) {
// This test only works in multi-process mode
if (in_process_renderer())
return;
const wchar_t kDocRoot[] = L"chrome/test/data";
scoped_refptr<HTTPTestServer> server =
HTTPTestServer::CreateServer(kDocRoot, NULL);
ASSERT_TRUE(NULL != server.get());
FilePath test_file(test_data_directory_);
scoped_refptr<BrowserProxy> window(automation()->GetBrowserWindow(0));
scoped_refptr<TabProxy> tab(window->GetActiveTab());
ASSERT_TRUE(tab.get());
// Start with a file:// url
test_file = test_file.AppendASCII("title2.html");
tab->NavigateToURL(net::FilePathToFileURL(test_file));
int orig_tab_count = -1;
ASSERT_TRUE(window->GetTabCount(&orig_tab_count));
int orig_process_count = GetBrowserProcessCount();
ASSERT_GE(orig_process_count, 1);
// Use JavaScript URL to almost fork a new tab, but not quite. (Leave the
// opener non-null.) Should not fork a process.
std::string url_prefix("javascript:(function(){w=window.open();");
GURL dont_fork_url(url_prefix +
"w.document.location=\"http://localhost:1337\";})()");
// Make sure that a new tab but not new process has been created.
ASSERT_TRUE(tab->NavigateToURLAsync(dont_fork_url));
PlatformThread::Sleep(action_timeout_ms());
ASSERT_EQ(orig_process_count, GetBrowserProcessCount());
int new_tab_count = -1;
ASSERT_TRUE(window->GetTabCount(&new_tab_count));
ASSERT_EQ(orig_tab_count + 1, new_tab_count);
// Same thing if the current tab tries to redirect itself.
GURL dont_fork_url2(url_prefix +
"document.location=\"http://localhost:1337\";})()");
// Make sure that no new process has been created.
ASSERT_TRUE(tab->NavigateToURLAsync(dont_fork_url2));
PlatformThread::Sleep(action_timeout_ms());
ASSERT_EQ(orig_process_count, GetBrowserProcessCount());
}
#endif
#if defined(OS_WIN)
// TODO(estade): need to port GetActiveTabTitle().
TEST_F(VisibleBrowserTest, WindowOpenClose) {
FilePath test_file(test_data_directory_);
test_file = test_file.AppendASCII("window.close.html");
NavigateToURL(net::FilePathToFileURL(test_file));
int i;
for (i = 0; i < 10; ++i) {
PlatformThread::Sleep(action_max_timeout_ms() / 10);
std::wstring title = GetActiveTabTitle();
if (title == L"PASSED") {
// Success, bail out.
break;
}
}
if (i == 10)
FAIL() << "failed to get error page title";
}
#endif
#if defined(OS_WIN) // only works on Windows for now: http:://crbug.com/15891
class ShowModalDialogTest : public UITest {
public:
ShowModalDialogTest() {
launch_arguments_.AppendSwitch(switches::kDisablePopupBlocking);
}
};
// So flaky, http://crbug.com/17806. Do *not* re-enable without a real fix.
// Increasing timeouts is not a fix.
TEST_F(ShowModalDialogTest, DISABLED_BasicTest) {
// Test that a modal dialog is shown.
FilePath test_file(test_data_directory_);
test_file = test_file.AppendASCII("showmodaldialog.html");
NavigateToURL(net::FilePathToFileURL(test_file));
ASSERT_TRUE(automation()->WaitForWindowCountToBecome(
2, action_max_timeout_ms()));
scoped_refptr<BrowserProxy> browser = automation()->GetBrowserWindow(1);
scoped_refptr<TabProxy> tab = browser->GetActiveTab();
ASSERT_TRUE(tab.get());
std::wstring title;
ASSERT_TRUE(tab->GetTabTitle(&title));
ASSERT_EQ(title, L"ModalDialogTitle");
// Test that window.close() works. Since we don't have a way of executing a
// JS function on the page through TabProxy, reload it and use an unload
// handler that closes the page.
ASSERT_EQ(tab->Reload(), AUTOMATION_MSG_NAVIGATION_SUCCESS);
ASSERT_TRUE(automation()->WaitForWindowCountToBecome(
1, action_max_timeout_ms()));
}
#endif
} // namespace
<|endoftext|> |
<commit_before>#include "ChunkManager.h"
#include <math.h>
#include <iostream>
#include <GL/glew.h>
#include "Primitives.h"
constexpr int64 encodePosition(int32 x, int32 z)
{
return ((int64)x << 32) | ((int64)z & 0x00000000FFFFFFFF);
}
ChunkManager::ChunkManager()
:cmTerrainBuilder(ChunkManager::SEED)
{
cmSemaphore = CreateSemaphore(
NULL,
0,
9999,
NULL
);
for (uint32 i = 0; i < THREADCOUNT; i++)
{
cmThreadH[i] = CreateThread(
NULL, //Default security attributes
0, //Default stack size
cmRoutine, //Thread function name
NULL, //Argument to thread function
CREATE_SUSPENDED, //Creation flag
&cmThreadId[i] //The thread identifiers
);
}
if (cmSemaphore == NULL)
{
printf("CreateSemaphore error: %d\n", GetLastError());
//ERROR LOGGING
}
}
//Chunk Loading Thread Routine
DWORD WINAPI cmRoutine(LPVOID p)
{
for(;;)
{
WaitForSingleObject(ChunkManager::sChunkManager->getSemaphoreHandle(), INFINITE);
Chunk tempChunk = Chunk(ChunkManager::sChunkManager->fetchQueueIn());
std::vector<Block> newBlocks = ChunkManager::sChunkManager->cmTerrainBuilder.getChunkBlocks(tempChunk);
ChunkManager::sChunkManager->pushQueueOut(tempChunk.getPosition(), newBlocks);
}
return 0;
}
void ChunkManager::loadChunks(glm::vec3 currentChunk)
{
float32 flooredX = currentChunk.x, flooredZ = currentChunk.z;
float32 currentX = flooredX, currentZ = flooredZ;
std::vector<glm::vec3> chunksToLoad;
uint32 decrementor = 0;
//Chunk on player
chunksToLoad.push_back(glm::vec3(currentX, 0, currentZ));
//Middle pass
for (uint32 i = 1; i <= LOADINGRADIUS; i++)
{
currentZ = flooredZ + i*CHUNKWIDTH;
chunksToLoad.push_back(glm::vec3(currentX, 0, currentZ));
currentZ = flooredZ - i*CHUNKWIDTH;
chunksToLoad.push_back(glm::vec3(currentX, 0, currentZ));
}
//Outer pass
for (uint32 i = 1; i <= LOADINGRADIUS; i++)
{
currentX = flooredX + i*CHUNKWIDTH;
currentZ = flooredZ;
chunksToLoad.push_back(glm::vec3(currentX, 0, currentZ));
currentX = flooredX - i*CHUNKWIDTH;
chunksToLoad.push_back(glm::vec3(currentX, 0, currentZ));
for (uint32 k = 1; k < LOADINGRADIUS - decrementor; k++)
{
currentZ = flooredZ + k*CHUNKWIDTH;
chunksToLoad.push_back(glm::vec3(currentX, 0, currentZ));
currentX = flooredX + i*CHUNKWIDTH;
chunksToLoad.push_back(glm::vec3(currentX, 0, currentZ));
currentZ = flooredZ - k*CHUNKWIDTH;
chunksToLoad.push_back(glm::vec3(currentX, 0, currentZ));
currentX = flooredX - i*CHUNKWIDTH;
chunksToLoad.push_back(glm::vec3(currentX, 0, currentZ));
}
decrementor++;
}
//Check for loaded and loading chunks
for (int32 i = 0; i < chunksToLoad.size(); i++)
{
int64 chunkPosition = encodePosition(chunksToLoad.at(i).x, chunksToLoad.at(i).z);
const auto& loadedIt = cmLoadedChunks.find(chunkPosition);
const auto& loadingIt = cmLoadingChunks.find(chunkPosition);
if (loadedIt != cmLoadedChunks.end() || loadingIt != cmLoadingChunks.end())
{
chunksToLoad.erase(chunksToLoad.begin() + i);
}
}
pushQueueIn(chunksToLoad);
}
void ChunkManager::pushQueueIn(std::vector<glm::vec3> data)
{
cmInMutex.lock();
for (uint32_t i = 0; i < data.size(); i++)
{
glm::vec3 currentPos = data.at(i);
cmLoadingChunks[encodePosition(currentPos.x, currentPos.z)] = Chunk(currentPos);
cmInQueue.push(currentPos);
//Signal semaphore
ReleaseSemaphore(
cmSemaphore,
1,
NULL
);
}
cmInMutex.unlock();
}
void ChunkManager::pushQueueOut(const glm::vec3 chunkPosition, std::vector<Block>& data)
{
cmOutMutex.lock();
cmOutQueue.push(std::pair<glm::vec3, std::vector<Block>>(chunkPosition, data));
cmOutMutex.unlock();
}
glm::vec3 ChunkManager::fetchQueueIn()
{
cmInMutex.lock();
glm::vec3 data = cmInQueue.front();
cmInQueue.pop();
cmInMutex.unlock();
return data;
}
void ChunkManager::uploadQueuedChunk()
{
cmOutMutex.lock();
if (cmOutQueue.empty()) {
cmOutMutex.unlock();
return;
}
const auto data = cmOutQueue.front();
cmOutQueue.pop();
cmOutMutex.unlock();
uploadChunk(data.first, data.second);
}
ChunkManager* ChunkManager::instance()
{
if (!sChunkManager)
{
sChunkManager = new ChunkManager;
sChunkManager->startThreads();
}
return sChunkManager;
}
void ChunkManager::startThreads()
{
for (uint32 i = 0; i < THREADCOUNT; i++)
{
ResumeThread(cmThreadH[i]);
}
}
glm::vec3 ChunkManager::getCurrentChunk(glm::vec3 playerPosition) const
{
float32 flooredX = floor((playerPosition.x / CHUNKWIDTH) + 0.5)*CHUNKWIDTH;
float32 flooredZ = floor((playerPosition.z / CHUNKWIDTH) + 0.5)*CHUNKWIDTH;
return glm::vec3(flooredX, 0, flooredZ);
}
ChunkManager::~ChunkManager()
{
CloseHandle(cmSemaphore);
for (uint32_t i = 0; i < THREADCOUNT; i++)
{
CloseHandle(cmThreadH[i]);
}
delete sChunkManager;
}
void ChunkManager::uploadChunk(const glm::vec3& chunkPosition, const std::vector<Block>& chunkData) {
GLuint chunkVao;
glGenVertexArrays(1, &chunkVao);
glBindVertexArray(chunkVao);
std::vector<float32> vertices;
std::vector<float32> uvCoords;
std::vector<float32> normals;
std::vector<uint32> indices;
std::vector<GLuint> vbos;
cube::fill(vertices, uvCoords, normals, indices);
GLuint vbo;
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(float32) * vertices.size(), vertices.data(), GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, false, 0, nullptr);
vbos.push_back(vbo);
GLuint uvVbo;
glGenBuffers(1, &uvVbo);
glBindBuffer(GL_ARRAY_BUFFER, uvVbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(float32) * uvCoords.size(), uvCoords.data(), GL_STATIC_DRAW);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, false, 0, nullptr);
vbos.push_back(uvVbo);
GLuint normalVbo;
glGenBuffers(1, &normalVbo);
glBindBuffer(GL_ARRAY_BUFFER, normalVbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(float32) * normals.size(), normals.data(), GL_STATIC_DRAW);
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 3, GL_FLOAT, false, 0, nullptr);
vbos.push_back(normalVbo);
GLuint ebo;
glGenBuffers(1, &ebo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(uint32) * indices.size(), indices.data(), GL_STATIC_DRAW);
vbos.push_back(ebo);
GLuint positionBuffer;
GLuint textureIndexBuffer;
glGenBuffers(1, &positionBuffer);
glGenBuffers(1, &textureIndexBuffer);
float32* positions = new float32[chunkData.size() * 3];
uint32* textureIndices = new uint32[chunkData.size()];
for (int32 i = 0; i < chunkData.size(); i++) {
glm::vec3 pos = chunkData[i].getPosition();
uint32 type = static_cast<uint32>(chunkData[i].getBlockType());
positions[(i * 3)] = pos.x;
positions[(i * 3) + 1] = pos.y;
positions[(i * 3) + 2] = pos.z;
textureIndices[i] = type;
}
glBindBuffer(GL_ARRAY_BUFFER, positionBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(float32) * chunkData.size() * 3, positions, GL_STATIC_DRAW);
glEnableVertexAttribArray(3);
glVertexAttribPointer(3, 3, GL_FLOAT, false, 0, nullptr);
glVertexAttribDivisor(3, 1);
glBindBuffer(GL_ARRAY_BUFFER, textureIndexBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(uint32) * chunkData.size(), textureIndices, GL_STATIC_DRAW);
glEnableVertexAttribArray(4);
glVertexAttribIPointer(4, 1, GL_UNSIGNED_INT, 0, nullptr);
glVertexAttribDivisor(4, 1);
vbos.push_back(positionBuffer);
vbos.push_back(textureIndexBuffer);
delete[] positions;
delete[] textureIndices;
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
Chunk chunky(chunkPosition);
chunky.setVao(chunkVao);
chunky.setVbos(vbos);
chunky.setBlockCount(chunkData.size());
cmLoadedChunks[encodePosition(chunkPosition.x, chunkPosition.z)] = chunky;
cmLoadingChunks.erase(encodePosition(chunkPosition.x, chunkPosition.z));
}
ChunkManager* ChunkManager::sChunkManager = nullptr;
<commit_msg>Fix the loop<commit_after>#include "ChunkManager.h"
#include <math.h>
#include <iostream>
#include <GL/glew.h>
#include "Primitives.h"
constexpr int64 encodePosition(int32 x, int32 z)
{
return ((int64)x << 32) | ((int64)z & 0x00000000FFFFFFFF);
}
ChunkManager::ChunkManager()
:cmTerrainBuilder(ChunkManager::SEED)
{
cmSemaphore = CreateSemaphore(
NULL,
0,
9999,
NULL
);
for (uint32 i = 0; i < THREADCOUNT; i++)
{
cmThreadH[i] = CreateThread(
NULL, //Default security attributes
0, //Default stack size
cmRoutine, //Thread function name
NULL, //Argument to thread function
CREATE_SUSPENDED, //Creation flag
&cmThreadId[i] //The thread identifiers
);
}
if (cmSemaphore == NULL)
{
printf("CreateSemaphore error: %d\n", GetLastError());
//ERROR LOGGING
}
}
//Chunk Loading Thread Routine
DWORD WINAPI cmRoutine(LPVOID p)
{
for(;;)
{
WaitForSingleObject(ChunkManager::sChunkManager->getSemaphoreHandle(), INFINITE);
Chunk tempChunk = Chunk(ChunkManager::sChunkManager->fetchQueueIn());
std::vector<Block> newBlocks = ChunkManager::sChunkManager->cmTerrainBuilder.getChunkBlocks(tempChunk);
ChunkManager::sChunkManager->pushQueueOut(tempChunk.getPosition(), newBlocks);
}
return 0;
}
void ChunkManager::loadChunks(glm::vec3 currentChunk)
{
float32 flooredX = currentChunk.x, flooredZ = currentChunk.z;
float32 currentX = flooredX, currentZ = flooredZ;
std::vector<glm::vec3> chunksToLoad;
uint32 decrementor = 0;
//Chunk on player
chunksToLoad.push_back(glm::vec3(currentX, 0, currentZ));
//Middle pass
for (uint32 i = 1; i <= LOADINGRADIUS; i++)
{
currentZ = flooredZ + i*CHUNKWIDTH;
chunksToLoad.push_back(glm::vec3(currentX, 0, currentZ));
currentZ = flooredZ - i*CHUNKWIDTH;
chunksToLoad.push_back(glm::vec3(currentX, 0, currentZ));
}
//Outer pass
for (uint32 i = 1; i <= LOADINGRADIUS; i++)
{
currentX = flooredX + i*CHUNKWIDTH;
currentZ = flooredZ;
chunksToLoad.push_back(glm::vec3(currentX, 0, currentZ));
currentX = flooredX - i*CHUNKWIDTH;
chunksToLoad.push_back(glm::vec3(currentX, 0, currentZ));
for (uint32 k = 1; k < LOADINGRADIUS - decrementor; k++)
{
currentZ = flooredZ + k*CHUNKWIDTH;
chunksToLoad.push_back(glm::vec3(currentX, 0, currentZ));
currentX = flooredX + i*CHUNKWIDTH;
chunksToLoad.push_back(glm::vec3(currentX, 0, currentZ));
currentZ = flooredZ - k*CHUNKWIDTH;
chunksToLoad.push_back(glm::vec3(currentX, 0, currentZ));
currentX = flooredX - i*CHUNKWIDTH;
chunksToLoad.push_back(glm::vec3(currentX, 0, currentZ));
}
decrementor++;
}
//Check for loaded and loading chunks
for (int32 i = chunksToLoad.size() - 1; i >= 0; i--)
{
int64 chunkPosition = encodePosition(chunksToLoad.at(i).x, chunksToLoad.at(i).z);
const auto& loadedIt = cmLoadedChunks.find(chunkPosition);
const auto& loadingIt = cmLoadingChunks.find(chunkPosition);
if (loadedIt != cmLoadedChunks.end() || loadingIt != cmLoadingChunks.end())
{
chunksToLoad.erase(chunksToLoad.begin() + i);
}
}
pushQueueIn(chunksToLoad);
}
void ChunkManager::pushQueueIn(std::vector<glm::vec3> data)
{
cmInMutex.lock();
for (uint32_t i = 0; i < data.size(); i++)
{
glm::vec3 currentPos = data.at(i);
cmLoadingChunks[encodePosition(currentPos.x, currentPos.z)] = Chunk(currentPos);
cmInQueue.push(currentPos);
//Signal semaphore
ReleaseSemaphore(
cmSemaphore,
1,
NULL
);
}
cmInMutex.unlock();
}
void ChunkManager::pushQueueOut(const glm::vec3 chunkPosition, std::vector<Block>& data)
{
cmOutMutex.lock();
cmOutQueue.push(std::pair<glm::vec3, std::vector<Block>>(chunkPosition, data));
cmOutMutex.unlock();
}
glm::vec3 ChunkManager::fetchQueueIn()
{
cmInMutex.lock();
glm::vec3 data = cmInQueue.front();
cmInQueue.pop();
cmInMutex.unlock();
return data;
}
void ChunkManager::uploadQueuedChunk()
{
cmOutMutex.lock();
if (cmOutQueue.empty()) {
cmOutMutex.unlock();
return;
}
const auto data = cmOutQueue.front();
cmOutQueue.pop();
cmOutMutex.unlock();
uploadChunk(data.first, data.second);
}
ChunkManager* ChunkManager::instance()
{
if (!sChunkManager)
{
sChunkManager = new ChunkManager;
sChunkManager->startThreads();
}
return sChunkManager;
}
void ChunkManager::startThreads()
{
for (uint32 i = 0; i < THREADCOUNT; i++)
{
ResumeThread(cmThreadH[i]);
}
}
glm::vec3 ChunkManager::getCurrentChunk(glm::vec3 playerPosition) const
{
float32 flooredX = floor((playerPosition.x / CHUNKWIDTH) + 0.5)*CHUNKWIDTH;
float32 flooredZ = floor((playerPosition.z / CHUNKWIDTH) + 0.5)*CHUNKWIDTH;
return glm::vec3(flooredX, 0, flooredZ);
}
ChunkManager::~ChunkManager()
{
CloseHandle(cmSemaphore);
for (uint32_t i = 0; i < THREADCOUNT; i++)
{
CloseHandle(cmThreadH[i]);
}
delete sChunkManager;
}
void ChunkManager::uploadChunk(const glm::vec3& chunkPosition, const std::vector<Block>& chunkData) {
GLuint chunkVao;
glGenVertexArrays(1, &chunkVao);
glBindVertexArray(chunkVao);
std::vector<float32> vertices;
std::vector<float32> uvCoords;
std::vector<float32> normals;
std::vector<uint32> indices;
std::vector<GLuint> vbos;
cube::fill(vertices, uvCoords, normals, indices);
GLuint vbo;
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(float32) * vertices.size(), vertices.data(), GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, false, 0, nullptr);
vbos.push_back(vbo);
GLuint uvVbo;
glGenBuffers(1, &uvVbo);
glBindBuffer(GL_ARRAY_BUFFER, uvVbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(float32) * uvCoords.size(), uvCoords.data(), GL_STATIC_DRAW);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, false, 0, nullptr);
vbos.push_back(uvVbo);
GLuint normalVbo;
glGenBuffers(1, &normalVbo);
glBindBuffer(GL_ARRAY_BUFFER, normalVbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(float32) * normals.size(), normals.data(), GL_STATIC_DRAW);
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 3, GL_FLOAT, false, 0, nullptr);
vbos.push_back(normalVbo);
GLuint ebo;
glGenBuffers(1, &ebo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(uint32) * indices.size(), indices.data(), GL_STATIC_DRAW);
vbos.push_back(ebo);
GLuint positionBuffer;
GLuint textureIndexBuffer;
glGenBuffers(1, &positionBuffer);
glGenBuffers(1, &textureIndexBuffer);
float32* positions = new float32[chunkData.size() * 3];
uint32* textureIndices = new uint32[chunkData.size()];
for (int32 i = 0; i < chunkData.size(); i++) {
glm::vec3 pos = chunkData[i].getPosition();
uint32 type = static_cast<uint32>(chunkData[i].getBlockType());
positions[(i * 3)] = pos.x;
positions[(i * 3) + 1] = pos.y;
positions[(i * 3) + 2] = pos.z;
textureIndices[i] = type;
}
glBindBuffer(GL_ARRAY_BUFFER, positionBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(float32) * chunkData.size() * 3, positions, GL_STATIC_DRAW);
glEnableVertexAttribArray(3);
glVertexAttribPointer(3, 3, GL_FLOAT, false, 0, nullptr);
glVertexAttribDivisor(3, 1);
glBindBuffer(GL_ARRAY_BUFFER, textureIndexBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(uint32) * chunkData.size(), textureIndices, GL_STATIC_DRAW);
glEnableVertexAttribArray(4);
glVertexAttribIPointer(4, 1, GL_UNSIGNED_INT, 0, nullptr);
glVertexAttribDivisor(4, 1);
vbos.push_back(positionBuffer);
vbos.push_back(textureIndexBuffer);
delete[] positions;
delete[] textureIndices;
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
Chunk chunky(chunkPosition);
chunky.setVao(chunkVao);
chunky.setVbos(vbos);
chunky.setBlockCount(chunkData.size());
cmLoadedChunks[encodePosition(chunkPosition.x, chunkPosition.z)] = chunky;
cmLoadingChunks.erase(encodePosition(chunkPosition.x, chunkPosition.z));
}
ChunkManager* ChunkManager::sChunkManager = nullptr;
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2010 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
*
*****************************************************************************/
// $Id$
#include "sqlite_datasource.hpp"
#include "sqlite_featureset.hpp"
// mapnik
#include <mapnik/ptree_helpers.hpp>
#include <mapnik/sql_utils.hpp>
// boost
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/tokenizer.hpp>
#include <boost/filesystem/operations.hpp>
using boost::lexical_cast;
using boost::bad_lexical_cast;
using mapnik::datasource;
using mapnik::parameters;
DATASOURCE_PLUGIN(sqlite_datasource)
using mapnik::box2d;
using mapnik::coord2d;
using mapnik::query;
using mapnik::featureset_ptr;
using mapnik::layer_descriptor;
using mapnik::attribute_descriptor;
using mapnik::datasource_exception;
sqlite_datasource::sqlite_datasource(parameters const& params, bool bind)
: datasource(params),
extent_(),
extent_initialized_(false),
type_(datasource::Vector),
table_(*params_.get<std::string>("table","")),
fields_(*params_.get<std::string>("fields","*")),
metadata_(*params_.get<std::string>("metadata","")),
geometry_table_(*params_.get<std::string>("geometry_table","")),
geometry_field_(*params_.get<std::string>("geometry_field","the_geom")),
// http://www.sqlite.org/lang_createtable.html#rowid
key_field_(*params_.get<std::string>("key_field","rowid")),
row_offset_(*params_.get<int>("row_offset",0)),
row_limit_(*params_.get<int>("row_limit",0)),
desc_(*params_.get<std::string>("type"), *params_.get<std::string>("encoding","utf-8")),
format_(mapnik::wkbGeneric)
{
boost::optional<std::string> file = params_.get<std::string>("file");
if (!file) throw datasource_exception("Sqlite Plugin: missing <file> parameter");
if (table_.empty()) throw mapnik::datasource_exception("Sqlite Plugin: missing <table> parameter");
boost::optional<std::string> wkb = params_.get<std::string>("wkb_format");
if (wkb)
{
if (*wkb == "spatialite")
format_ = mapnik::wkbSpatiaLite;
}
multiple_geometries_ = *params_.get<mapnik::boolean>("multiple_geometries",false);
use_spatial_index_ = *params_.get<mapnik::boolean>("use_spatial_index",true);
boost::optional<std::string> ext = params_.get<std::string>("extent");
if (ext) extent_initialized_ = extent_.from_string(*ext);
boost::optional<std::string> base = params_.get<std::string>("base");
if (base)
dataset_name_ = *base + "/" + *file;
else
dataset_name_ = *file;
if (bind)
{
this->bind();
}
}
void sqlite_datasource::bind() const
{
if (is_bound_) return;
if (!boost::filesystem::exists(dataset_name_))
throw datasource_exception("Sqlite Plugin: " + dataset_name_ + " does not exist");
dataset_ = new sqlite_connection (dataset_name_);
if(geometry_table_.empty())
{
geometry_table_ = mapnik::table_from_sql(table_);
}
if (use_spatial_index_)
{
std::ostringstream s;
s << "SELECT COUNT (*) FROM sqlite_master";
s << " WHERE LOWER(name) = LOWER('idx_" << geometry_table_ << "_" << geometry_field_ << "')";
boost::scoped_ptr<sqlite_resultset> rs (dataset_->execute_query (s.str()));
if (rs->is_valid () && rs->step_next())
{
use_spatial_index_ = rs->column_integer (0) == 1;
}
if (!use_spatial_index_)
std::clog << "Sqlite Plugin: spatial index not found for table '"
<< geometry_table_ << "'" << std::endl;
}
if (metadata_ != "" && !extent_initialized_)
{
std::ostringstream s;
s << "SELECT xmin, ymin, xmax, ymax FROM " << metadata_;
s << " WHERE LOWER(f_table_name) = LOWER('" << geometry_table_ << "')";
boost::scoped_ptr<sqlite_resultset> rs (dataset_->execute_query (s.str()));
if (rs->is_valid () && rs->step_next())
{
double xmin = rs->column_double (0);
double ymin = rs->column_double (1);
double xmax = rs->column_double (2);
double ymax = rs->column_double (3);
extent_.init (xmin,ymin,xmax,ymax);
extent_initialized_ = true;
}
}
if (!extent_initialized_ && use_spatial_index_)
{
std::ostringstream s;
s << "SELECT xmin, ymin, xmax, ymax FROM "
<< "idx_" << geometry_table_ << "_" << geometry_field_;
boost::scoped_ptr<sqlite_resultset> rs (dataset_->execute_query (s.str()));
if (rs->is_valid () && rs->step_next())
{
double xmin = rs->column_double (0);
double ymin = rs->column_double (1);
double xmax = rs->column_double (2);
double ymax = rs->column_double (3);
extent_.init (xmin,ymin,xmax,ymax);
extent_initialized_ = true;
}
}
{
// should we deduce column names and types using PRAGMA?
bool use_pragma_table_info = true;
if (table_ != geometry_table_)
{
// if 'table_' is a subquery then we try to deduce names
// and types from the first row returned from that query
use_pragma_table_info = false;
}
if (!use_pragma_table_info)
{
std::ostringstream s;
s << "SELECT " << fields_ << " FROM (" << table_ << ") LIMIT 1";
boost::scoped_ptr<sqlite_resultset> rs (dataset_->execute_query (s.str()));
if (rs->is_valid () && rs->step_next())
{
for (int i = 0; i < rs->column_count (); ++i)
{
const int type_oid = rs->column_type (i);
const char* fld_name = rs->column_name (i);
switch (type_oid)
{
case SQLITE_INTEGER:
desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::Integer));
break;
case SQLITE_FLOAT:
desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::Double));
break;
case SQLITE_TEXT:
desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::String));
break;
case SQLITE_NULL:
// sqlite reports based on value, not actual column type unless
// PRAGMA table_info is used so here we assume the column is a string
// which is a lesser evil than altogether dropping the column
desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::String));
case SQLITE_BLOB:
break;
default:
#ifdef MAPNIK_DEBUG
std::clog << "Sqlite Plugin: unknown type_oid=" << type_oid << std::endl;
#endif
break;
}
}
}
else
{
// if we do not have at least a row and
// we cannot determine the right columns types and names
// as all column_type are SQLITE_NULL
// so we fallback to using PRAGMA table_info
use_pragma_table_info = true;
}
}
if (use_pragma_table_info)
{
std::ostringstream s;
s << "PRAGMA table_info(" << geometry_table_ << ")";
boost::scoped_ptr<sqlite_resultset> rs (dataset_->execute_query (s.str()));
while (rs->is_valid () && rs->step_next())
{
const char* fld_name = rs->column_text(1);
std::string fld_type(rs->column_text(2));
boost::algorithm::to_lower(fld_type);
// see 2.1 "Column Affinity" at http://www.sqlite.org/datatype3.html
if (boost::algorithm::contains(fld_type,"int"))
{
desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::Integer));
}
else if (boost::algorithm::contains(fld_type,"text") ||
boost::algorithm::contains(fld_type,"char") ||
boost::algorithm::contains(fld_type,"clob"))
{
desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::String));
}
else if (boost::algorithm::contains(fld_type,"real") ||
boost::algorithm::contains(fld_type,"float") ||
boost::algorithm::contains(fld_type,"double"))
{
desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::Double));
}
//else if (boost::algorithm::contains(fld_type,"blob")
// desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::String));
#ifdef MAPNIK_DEBUG
else
{
// "Column Affinity" says default to "Numeric" but for now we pass..
//desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::Double));
std::clog << "Sqlite Plugin: unknown type_oid=" << fld_type << std::endl;
}
#endif
}
}
}
is_bound_ = true;
}
sqlite_datasource::~sqlite_datasource()
{
if (is_bound_)
{
delete dataset_;
}
}
std::string sqlite_datasource::name()
{
return "sqlite";
}
int sqlite_datasource::type() const
{
return type_;
}
box2d<double> sqlite_datasource::envelope() const
{
if (!is_bound_) bind();
return extent_;
}
layer_descriptor sqlite_datasource::get_descriptor() const
{
if (!is_bound_) bind();
return desc_;
}
featureset_ptr sqlite_datasource::features(query const& q) const
{
if (!is_bound_) bind();
if (dataset_)
{
mapnik::box2d<double> const& e = q.get_bbox();
std::ostringstream s;
s << "SELECT " << geometry_field_ << "," << key_field_;
std::set<std::string> const& props = q.property_names();
std::set<std::string>::const_iterator pos = props.begin();
std::set<std::string>::const_iterator end = props.end();
while (pos != end)
{
s << ",\"" << *pos << "\"";
++pos;
}
s << " FROM ";
std::string query (table_);
if (use_spatial_index_)
{
std::ostringstream spatial_sql;
spatial_sql << std::setprecision(16);
spatial_sql << " WHERE " << key_field_ << " IN (SELECT pkid FROM idx_" << geometry_table_ << "_" << geometry_field_;
spatial_sql << " WHERE xmax>=" << e.minx() << " AND xmin<=" << e.maxx() ;
spatial_sql << " AND ymax>=" << e.miny() << " AND ymin<=" << e.maxy() << ")";
if (boost::algorithm::ifind_first(query, "WHERE"))
{
boost::algorithm::ireplace_first(query, "WHERE", spatial_sql.str() + " AND ");
}
else if (boost::algorithm::ifind_first(query, geometry_table_))
{
boost::algorithm::ireplace_first(query, table_, table_ + " " + spatial_sql.str());
}
}
s << query ;
if (row_limit_ > 0) {
s << " LIMIT " << row_limit_;
}
if (row_offset_ > 0) {
s << " OFFSET " << row_offset_;
}
#ifdef MAPNIK_DEBUG
std::clog << "Sqlite Plugin: " << s.str() << std::endl;
#endif
boost::shared_ptr<sqlite_resultset> rs (dataset_->execute_query (s.str()));
return featureset_ptr (new sqlite_featureset(rs, desc_.get_encoding(), format_, multiple_geometries_));
}
return featureset_ptr();
}
featureset_ptr sqlite_datasource::features_at_point(coord2d const& pt) const
{
if (!is_bound_) bind();
return featureset_ptr();
}
<commit_msg>sqlite plugin: aggregate extents from rtree spatial index<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2010 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
*
*****************************************************************************/
// $Id$
#include "sqlite_datasource.hpp"
#include "sqlite_featureset.hpp"
// mapnik
#include <mapnik/ptree_helpers.hpp>
#include <mapnik/sql_utils.hpp>
// boost
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/tokenizer.hpp>
#include <boost/filesystem/operations.hpp>
using boost::lexical_cast;
using boost::bad_lexical_cast;
using mapnik::datasource;
using mapnik::parameters;
DATASOURCE_PLUGIN(sqlite_datasource)
using mapnik::box2d;
using mapnik::coord2d;
using mapnik::query;
using mapnik::featureset_ptr;
using mapnik::layer_descriptor;
using mapnik::attribute_descriptor;
using mapnik::datasource_exception;
sqlite_datasource::sqlite_datasource(parameters const& params, bool bind)
: datasource(params),
extent_(),
extent_initialized_(false),
type_(datasource::Vector),
table_(*params_.get<std::string>("table","")),
fields_(*params_.get<std::string>("fields","*")),
metadata_(*params_.get<std::string>("metadata","")),
geometry_table_(*params_.get<std::string>("geometry_table","")),
geometry_field_(*params_.get<std::string>("geometry_field","the_geom")),
// http://www.sqlite.org/lang_createtable.html#rowid
key_field_(*params_.get<std::string>("key_field","rowid")),
row_offset_(*params_.get<int>("row_offset",0)),
row_limit_(*params_.get<int>("row_limit",0)),
desc_(*params_.get<std::string>("type"), *params_.get<std::string>("encoding","utf-8")),
format_(mapnik::wkbGeneric)
{
boost::optional<std::string> file = params_.get<std::string>("file");
if (!file) throw datasource_exception("Sqlite Plugin: missing <file> parameter");
if (table_.empty()) throw mapnik::datasource_exception("Sqlite Plugin: missing <table> parameter");
boost::optional<std::string> wkb = params_.get<std::string>("wkb_format");
if (wkb)
{
if (*wkb == "spatialite")
format_ = mapnik::wkbSpatiaLite;
}
multiple_geometries_ = *params_.get<mapnik::boolean>("multiple_geometries",false);
use_spatial_index_ = *params_.get<mapnik::boolean>("use_spatial_index",true);
boost::optional<std::string> ext = params_.get<std::string>("extent");
if (ext) extent_initialized_ = extent_.from_string(*ext);
boost::optional<std::string> base = params_.get<std::string>("base");
if (base)
dataset_name_ = *base + "/" + *file;
else
dataset_name_ = *file;
if (bind)
{
this->bind();
}
}
void sqlite_datasource::bind() const
{
if (is_bound_) return;
if (!boost::filesystem::exists(dataset_name_))
throw datasource_exception("Sqlite Plugin: " + dataset_name_ + " does not exist");
dataset_ = new sqlite_connection (dataset_name_);
if(geometry_table_.empty())
{
geometry_table_ = mapnik::table_from_sql(table_);
}
if (use_spatial_index_)
{
std::ostringstream s;
s << "SELECT COUNT (*) FROM sqlite_master";
s << " WHERE LOWER(name) = LOWER('idx_" << geometry_table_ << "_" << geometry_field_ << "')";
boost::scoped_ptr<sqlite_resultset> rs (dataset_->execute_query (s.str()));
if (rs->is_valid () && rs->step_next())
{
use_spatial_index_ = rs->column_integer (0) == 1;
}
if (!use_spatial_index_)
std::clog << "Sqlite Plugin: spatial index not found for table '"
<< geometry_table_ << "'" << std::endl;
}
if (metadata_ != "" && !extent_initialized_)
{
std::ostringstream s;
s << "SELECT xmin, ymin, xmax, ymax FROM " << metadata_;
s << " WHERE LOWER(f_table_name) = LOWER('" << geometry_table_ << "')";
boost::scoped_ptr<sqlite_resultset> rs (dataset_->execute_query (s.str()));
if (rs->is_valid () && rs->step_next())
{
double xmin = rs->column_double (0);
double ymin = rs->column_double (1);
double xmax = rs->column_double (2);
double ymax = rs->column_double (3);
extent_.init (xmin,ymin,xmax,ymax);
extent_initialized_ = true;
}
}
if (!extent_initialized_ && use_spatial_index_)
{
std::ostringstream s;
s << "SELECT MIN(xmin), MIN(ymin), MAX(xmax), MAX(ymax) FROM "
<< "idx_" << geometry_table_ << "_" << geometry_field_;
boost::scoped_ptr<sqlite_resultset> rs (dataset_->execute_query (s.str()));
if (rs->is_valid () && rs->step_next())
{
double xmin = rs->column_double (0);
double ymin = rs->column_double (1);
double xmax = rs->column_double (2);
double ymax = rs->column_double (3);
extent_.init (xmin,ymin,xmax,ymax);
extent_initialized_ = true;
}
}
{
// should we deduce column names and types using PRAGMA?
bool use_pragma_table_info = true;
if (table_ != geometry_table_)
{
// if 'table_' is a subquery then we try to deduce names
// and types from the first row returned from that query
use_pragma_table_info = false;
}
if (!use_pragma_table_info)
{
std::ostringstream s;
s << "SELECT " << fields_ << " FROM (" << table_ << ") LIMIT 1";
boost::scoped_ptr<sqlite_resultset> rs (dataset_->execute_query (s.str()));
if (rs->is_valid () && rs->step_next())
{
for (int i = 0; i < rs->column_count (); ++i)
{
const int type_oid = rs->column_type (i);
const char* fld_name = rs->column_name (i);
switch (type_oid)
{
case SQLITE_INTEGER:
desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::Integer));
break;
case SQLITE_FLOAT:
desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::Double));
break;
case SQLITE_TEXT:
desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::String));
break;
case SQLITE_NULL:
// sqlite reports based on value, not actual column type unless
// PRAGMA table_info is used so here we assume the column is a string
// which is a lesser evil than altogether dropping the column
desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::String));
case SQLITE_BLOB:
break;
default:
#ifdef MAPNIK_DEBUG
std::clog << "Sqlite Plugin: unknown type_oid=" << type_oid << std::endl;
#endif
break;
}
}
}
else
{
// if we do not have at least a row and
// we cannot determine the right columns types and names
// as all column_type are SQLITE_NULL
// so we fallback to using PRAGMA table_info
use_pragma_table_info = true;
}
}
if (use_pragma_table_info)
{
std::ostringstream s;
s << "PRAGMA table_info(" << geometry_table_ << ")";
boost::scoped_ptr<sqlite_resultset> rs (dataset_->execute_query (s.str()));
while (rs->is_valid () && rs->step_next())
{
const char* fld_name = rs->column_text(1);
std::string fld_type(rs->column_text(2));
boost::algorithm::to_lower(fld_type);
// see 2.1 "Column Affinity" at http://www.sqlite.org/datatype3.html
if (boost::algorithm::contains(fld_type,"int"))
{
desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::Integer));
}
else if (boost::algorithm::contains(fld_type,"text") ||
boost::algorithm::contains(fld_type,"char") ||
boost::algorithm::contains(fld_type,"clob"))
{
desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::String));
}
else if (boost::algorithm::contains(fld_type,"real") ||
boost::algorithm::contains(fld_type,"float") ||
boost::algorithm::contains(fld_type,"double"))
{
desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::Double));
}
//else if (boost::algorithm::contains(fld_type,"blob")
// desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::String));
#ifdef MAPNIK_DEBUG
else
{
// "Column Affinity" says default to "Numeric" but for now we pass..
//desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::Double));
std::clog << "Sqlite Plugin: unknown type_oid=" << fld_type << std::endl;
}
#endif
}
}
}
is_bound_ = true;
}
sqlite_datasource::~sqlite_datasource()
{
if (is_bound_)
{
delete dataset_;
}
}
std::string sqlite_datasource::name()
{
return "sqlite";
}
int sqlite_datasource::type() const
{
return type_;
}
box2d<double> sqlite_datasource::envelope() const
{
if (!is_bound_) bind();
return extent_;
}
layer_descriptor sqlite_datasource::get_descriptor() const
{
if (!is_bound_) bind();
return desc_;
}
featureset_ptr sqlite_datasource::features(query const& q) const
{
if (!is_bound_) bind();
if (dataset_)
{
mapnik::box2d<double> const& e = q.get_bbox();
std::ostringstream s;
s << "SELECT " << geometry_field_ << "," << key_field_;
std::set<std::string> const& props = q.property_names();
std::set<std::string>::const_iterator pos = props.begin();
std::set<std::string>::const_iterator end = props.end();
while (pos != end)
{
s << ",\"" << *pos << "\"";
++pos;
}
s << " FROM ";
std::string query (table_);
if (use_spatial_index_)
{
std::ostringstream spatial_sql;
spatial_sql << std::setprecision(16);
spatial_sql << " WHERE " << key_field_ << " IN (SELECT pkid FROM idx_" << geometry_table_ << "_" << geometry_field_;
spatial_sql << " WHERE xmax>=" << e.minx() << " AND xmin<=" << e.maxx() ;
spatial_sql << " AND ymax>=" << e.miny() << " AND ymin<=" << e.maxy() << ")";
if (boost::algorithm::ifind_first(query, "WHERE"))
{
boost::algorithm::ireplace_first(query, "WHERE", spatial_sql.str() + " AND ");
}
else if (boost::algorithm::ifind_first(query, geometry_table_))
{
boost::algorithm::ireplace_first(query, table_, table_ + " " + spatial_sql.str());
}
}
s << query ;
if (row_limit_ > 0) {
s << " LIMIT " << row_limit_;
}
if (row_offset_ > 0) {
s << " OFFSET " << row_offset_;
}
#ifdef MAPNIK_DEBUG
std::clog << "Sqlite Plugin: " << s.str() << std::endl;
#endif
boost::shared_ptr<sqlite_resultset> rs (dataset_->execute_query (s.str()));
return featureset_ptr (new sqlite_featureset(rs, desc_.get_encoding(), format_, multiple_geometries_));
}
return featureset_ptr();
}
featureset_ptr sqlite_datasource::features_at_point(coord2d const& pt) const
{
if (!is_bound_) bind();
return featureset_ptr();
}
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2011 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/global.hpp>
#include <mapnik/debug.hpp>
#include <mapnik/datasource.hpp>
#include <mapnik/box2d.hpp>
#include <mapnik/geometry.hpp>
#include <mapnik/feature.hpp>
#include <mapnik/feature_layer_desc.hpp>
#include <mapnik/wkb.hpp>
#include <mapnik/unicode.hpp>
#include <mapnik/feature_factory.hpp>
// ogr
#include "sqlite_featureset.hpp"
#include "sqlite_utils.hpp"
using mapnik::query;
using mapnik::box2d;
using mapnik::Feature;
using mapnik::feature_ptr;
using mapnik::geometry_utils;
using mapnik::transcoder;
using mapnik::feature_factory;
sqlite_featureset::sqlite_featureset(boost::shared_ptr<sqlite_resultset> rs,
mapnik::context_ptr const& ctx,
std::string const& encoding,
mapnik::box2d<double> const& bbox,
mapnik::wkbFormat format,
bool spatial_index,
bool using_subquery)
: rs_(rs),
ctx_(ctx),
tr_(new transcoder(encoding)),
bbox_(bbox),
format_(format),
spatial_index_(spatial_index),
using_subquery_(using_subquery)
{}
sqlite_featureset::~sqlite_featureset() {}
feature_ptr sqlite_featureset::next()
{
while (rs_->is_valid () && rs_->step_next ())
{
int size;
const char* data = (const char*) rs_->column_blob(0, size);
if (data == 0)
{
return feature_ptr();
}
feature_ptr feature = feature_factory::create(ctx_,rs_->column_integer(1));
if (!geometry_utils::from_wkb(feature->paths(), data, size, format_))
continue;
if (!spatial_index_)
{
// we are not using r-tree index, check if feature intersects bounding box
if (!bbox_.intersects(feature->envelope()))
continue;
}
for (int i = 2; i < rs_->column_count(); ++i)
{
const int type_oid = rs_->column_type(i);
const char* fld_name = rs_->column_name(i);
if (! fld_name)
continue;
std::string fld_name_str(fld_name);
// subqueries in sqlite lead to field double quoting which we need to strip
if (using_subquery_)
{
sqlite_utils::dequote(fld_name_str);
}
switch (type_oid)
{
case SQLITE_INTEGER:
{
feature->put(fld_name_str, rs_->column_integer(i));
break;
}
case SQLITE_FLOAT:
{
feature->put(fld_name_str, rs_->column_double(i));
break;
}
case SQLITE_TEXT:
{
int text_size;
const char * data = rs_->column_text(i, text_size);
UnicodeString ustr = tr_->transcode(data, text_size);
feature->put(fld_name_str, ustr);
break;
}
case SQLITE_NULL:
{
feature->put(fld_name_str, mapnik::value_null());
break;
}
case SQLITE_BLOB:
break;
default:
MAPNIK_LOG_WARN(sqlite) << "sqlite_featureset: Field=" << fld_name_str << " unhandled type_oid=" << type_oid;
break;
}
}
return feature;
}
return feature_ptr();
}
<commit_msg>rename variable to avoid confusion with text_size<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2011 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/global.hpp>
#include <mapnik/debug.hpp>
#include <mapnik/datasource.hpp>
#include <mapnik/box2d.hpp>
#include <mapnik/geometry.hpp>
#include <mapnik/feature.hpp>
#include <mapnik/feature_layer_desc.hpp>
#include <mapnik/wkb.hpp>
#include <mapnik/unicode.hpp>
#include <mapnik/feature_factory.hpp>
// ogr
#include "sqlite_featureset.hpp"
#include "sqlite_utils.hpp"
using mapnik::query;
using mapnik::box2d;
using mapnik::Feature;
using mapnik::feature_ptr;
using mapnik::geometry_utils;
using mapnik::transcoder;
using mapnik::feature_factory;
sqlite_featureset::sqlite_featureset(boost::shared_ptr<sqlite_resultset> rs,
mapnik::context_ptr const& ctx,
std::string const& encoding,
mapnik::box2d<double> const& bbox,
mapnik::wkbFormat format,
bool spatial_index,
bool using_subquery)
: rs_(rs),
ctx_(ctx),
tr_(new transcoder(encoding)),
bbox_(bbox),
format_(format),
spatial_index_(spatial_index),
using_subquery_(using_subquery)
{}
sqlite_featureset::~sqlite_featureset() {}
feature_ptr sqlite_featureset::next()
{
while (rs_->is_valid () && rs_->step_next ())
{
int size;
const char* data = (const char*) rs_->column_blob(0, size);
if (data == 0)
{
return feature_ptr();
}
feature_ptr feature = feature_factory::create(ctx_,rs_->column_integer(1));
if (!geometry_utils::from_wkb(feature->paths(), data, size, format_))
continue;
if (!spatial_index_)
{
// we are not using r-tree index, check if feature intersects bounding box
if (!bbox_.intersects(feature->envelope()))
continue;
}
for (int i = 2; i < rs_->column_count(); ++i)
{
const int type_oid = rs_->column_type(i);
const char* fld_name = rs_->column_name(i);
if (! fld_name)
continue;
std::string fld_name_str(fld_name);
// subqueries in sqlite lead to field double quoting which we need to strip
if (using_subquery_)
{
sqlite_utils::dequote(fld_name_str);
}
switch (type_oid)
{
case SQLITE_INTEGER:
{
feature->put(fld_name_str, rs_->column_integer(i));
break;
}
case SQLITE_FLOAT:
{
feature->put(fld_name_str, rs_->column_double(i));
break;
}
case SQLITE_TEXT:
{
int text_col_size;
const char * data = rs_->column_text(i, text_col_size);
UnicodeString ustr = tr_->transcode(data, text_col_size);
feature->put(fld_name_str, ustr);
break;
}
case SQLITE_NULL:
{
feature->put(fld_name_str, mapnik::value_null());
break;
}
case SQLITE_BLOB:
break;
default:
MAPNIK_LOG_WARN(sqlite) << "sqlite_featureset: Field=" << fld_name_str << " unhandled type_oid=" << type_oid;
break;
}
}
return feature;
}
return feature_ptr();
}
<|endoftext|> |
<commit_before>// Copyright (c) 2013, Facebook, Inc. All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
#include <map>
#include <string>
#include "db/compaction_job.h"
#include "db/column_family.h"
#include "db/version_set.h"
#include "db/writebuffer.h"
#include "rocksdb/cache.h"
#include "rocksdb/options.h"
#include "rocksdb/db.h"
#include "util/string_util.h"
#include "util/testharness.h"
#include "util/testutil.h"
#include "table/mock_table.h"
namespace rocksdb {
// TODO(icanadi) Make it simpler once we mock out VersionSet
class CompactionJobTest : public testing::Test {
public:
CompactionJobTest()
: env_(Env::Default()),
dbname_(test::TmpDir() + "/compaction_job_test"),
mutable_cf_options_(Options(), ImmutableCFOptions(Options())),
table_cache_(NewLRUCache(50000, 16)),
write_buffer_(db_options_.db_write_buffer_size),
versions_(new VersionSet(dbname_, &db_options_, env_options_,
table_cache_.get(), &write_buffer_,
&write_controller_)),
shutting_down_(false),
mock_table_factory_(new mock::MockTableFactory()) {
EXPECT_OK(env_->CreateDirIfMissing(dbname_));
db_options_.db_paths.emplace_back(dbname_,
std::numeric_limits<uint64_t>::max());
NewDB();
std::vector<ColumnFamilyDescriptor> column_families;
cf_options_.table_factory = mock_table_factory_;
column_families.emplace_back(kDefaultColumnFamilyName, cf_options_);
EXPECT_OK(versions_->Recover(column_families, false));
}
std::string GenerateFileName(uint64_t file_number) {
FileMetaData meta;
std::vector<DbPath> db_paths;
db_paths.emplace_back(dbname_, std::numeric_limits<uint64_t>::max());
meta.fd = FileDescriptor(file_number, 0, 0);
return TableFileName(db_paths, meta.fd.GetNumber(), meta.fd.GetPathId());
}
// returns expected result after compaction
mock::MockFileContents CreateTwoFiles() {
mock::MockFileContents expected_results;
const int kKeysPerFile = 10000;
SequenceNumber sequence_number = 0;
for (int i = 0; i < 2; ++i) {
mock::MockFileContents contents;
SequenceNumber smallest_seqno = 0, largest_seqno = 0;
InternalKey smallest, largest;
for (int k = 0; k < kKeysPerFile; ++k) {
auto key = ToString(i * (kKeysPerFile / 2) + k);
auto value = ToString(i * kKeysPerFile + k);
InternalKey internal_key(key, ++sequence_number, kTypeValue);
// This is how the key will look like once it's written in bottommost
// file
InternalKey bottommost_internal_key(key, 0, kTypeValue);
if (k == 0) {
smallest = internal_key;
smallest_seqno = sequence_number;
} else if (k == kKeysPerFile - 1) {
largest = internal_key;
largest_seqno = sequence_number;
}
contents.insert({internal_key.Encode().ToString(), value});
if (i == 1 || k < kKeysPerFile / 2) {
expected_results.insert(
{bottommost_internal_key.Encode().ToString(), value});
}
}
uint64_t file_number = versions_->NewFileNumber();
EXPECT_OK(mock_table_factory_->CreateMockTable(
env_, GenerateFileName(file_number), std::move(contents)));
VersionEdit edit;
edit.AddFile(0, file_number, 0, 10, smallest, largest, smallest_seqno,
largest_seqno, false);
mutex_.Lock();
versions_->LogAndApply(versions_->GetColumnFamilySet()->GetDefault(),
mutable_cf_options_, &edit, &mutex_);
mutex_.Unlock();
}
versions_->SetLastSequence(sequence_number + 1);
return expected_results;
}
void NewDB() {
VersionEdit new_db;
new_db.SetLogNumber(0);
new_db.SetNextFile(2);
new_db.SetLastSequence(0);
const std::string manifest = DescriptorFileName(dbname_, 1);
unique_ptr<WritableFile> file;
Status s = env_->NewWritableFile(
manifest, &file, env_->OptimizeForManifestWrite(env_options_));
ASSERT_OK(s);
{
log::Writer log(std::move(file));
std::string record;
new_db.EncodeTo(&record);
s = log.AddRecord(record);
}
ASSERT_OK(s);
// Make "CURRENT" file that points to the new manifest file.
s = SetCurrentFile(env_, dbname_, 1, nullptr);
}
Env* env_;
std::string dbname_;
EnvOptions env_options_;
MutableCFOptions mutable_cf_options_;
std::shared_ptr<Cache> table_cache_;
WriteController write_controller_;
DBOptions db_options_;
ColumnFamilyOptions cf_options_;
WriteBuffer write_buffer_;
std::unique_ptr<VersionSet> versions_;
InstrumentedMutex mutex_;
std::atomic<bool> shutting_down_;
std::shared_ptr<mock::MockTableFactory> mock_table_factory_;
};
namespace {
void VerifyInitializationOfCompactionJobStats(
const CompactionJobStats& compaction_job_stats) {
#if !defined(IOS_CROSS_COMPILE)
ASSERT_EQ(compaction_job_stats.elapsed_micros, 0U);
ASSERT_EQ(compaction_job_stats.num_input_records, 0U);
ASSERT_EQ(compaction_job_stats.num_input_files, 0U);
ASSERT_EQ(compaction_job_stats.num_input_files_at_output_level, 0U);
ASSERT_EQ(compaction_job_stats.num_output_records, 0U);
ASSERT_EQ(compaction_job_stats.num_output_files, 0U);
ASSERT_EQ(compaction_job_stats.is_manual_compaction, 0U);
ASSERT_EQ(compaction_job_stats.total_input_bytes, 0U);
ASSERT_EQ(compaction_job_stats.total_output_bytes, 0U);
ASSERT_EQ(compaction_job_stats.total_input_raw_key_bytes, 0U);
ASSERT_EQ(compaction_job_stats.total_input_raw_value_bytes, 0U);
ASSERT_EQ(compaction_job_stats.smallest_output_key_prefix[0], 0);
ASSERT_EQ(compaction_job_stats.largest_output_key_prefix[0], 0);
ASSERT_EQ(compaction_job_stats.num_records_replaced, 0U);
#endif // !defined(IOS_CROSS_COMPILE)
}
void VerifyCompactionJobStats(
const CompactionJobStats& compaction_job_stats,
const std::vector<FileMetaData*>& files,
size_t num_output_files,
uint64_t min_elapsed_time) {
ASSERT_GE(compaction_job_stats.elapsed_micros, min_elapsed_time);
ASSERT_EQ(compaction_job_stats.num_input_files, files.size());
ASSERT_EQ(compaction_job_stats.num_output_files, num_output_files);
}
} // namespace
TEST_F(CompactionJobTest, Simple) {
auto cfd = versions_->GetColumnFamilySet()->GetDefault();
auto expected_results = CreateTwoFiles();
auto files = cfd->current()->storage_info()->LevelFiles(0);
ASSERT_EQ(2U, files.size());
CompactionInputFiles compaction_input_files;
compaction_input_files.level = 0;
compaction_input_files.files.push_back(files[0]);
compaction_input_files.files.push_back(files[1]);
std::unique_ptr<Compaction> compaction(new Compaction(
cfd->current()->storage_info(), *cfd->GetLatestMutableCFOptions(),
{compaction_input_files}, 1, 1024 * 1024, 10, 0, kNoCompression, {}));
compaction->SetInputVersion(cfd->current());
int yield_callback_called = 0;
std::function<uint64_t()> yield_callback = [&]() {
yield_callback_called++;
return 0;
};
LogBuffer log_buffer(InfoLogLevel::INFO_LEVEL, db_options_.info_log.get());
mutex_.Lock();
EventLogger event_logger(db_options_.info_log.get());
std::string db_name = "dbname";
CompactionJobStats compaction_job_stats;
CompactionJob compaction_job(0, compaction.get(), db_options_, env_options_,
versions_.get(), &shutting_down_, &log_buffer,
nullptr, nullptr, nullptr, {}, table_cache_,
std::move(yield_callback), &event_logger, false,
db_name, &compaction_job_stats);
auto start_micros = Env::Default()->NowMicros();
VerifyInitializationOfCompactionJobStats(compaction_job_stats);
compaction_job.Prepare();
mutex_.Unlock();
ASSERT_OK(compaction_job.Run());
mutex_.Lock();
Status s;
compaction_job.Install(&s, *cfd->GetLatestMutableCFOptions(), &mutex_);
ASSERT_OK(s);
mutex_.Unlock();
VerifyCompactionJobStats(
compaction_job_stats,
files, 1, (Env::Default()->NowMicros() - start_micros) / 2);
mock_table_factory_->AssertLatestFile(expected_results);
ASSERT_EQ(yield_callback_called, 20000);
}
} // namespace rocksdb
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<commit_msg>Fix occasional failure in compaction_job_test<commit_after>// Copyright (c) 2013, Facebook, Inc. All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
#include <map>
#include <string>
#include "db/compaction_job.h"
#include "db/column_family.h"
#include "db/version_set.h"
#include "db/writebuffer.h"
#include "rocksdb/cache.h"
#include "rocksdb/options.h"
#include "rocksdb/db.h"
#include "util/string_util.h"
#include "util/testharness.h"
#include "util/testutil.h"
#include "table/mock_table.h"
namespace rocksdb {
// TODO(icanadi) Make it simpler once we mock out VersionSet
class CompactionJobTest : public testing::Test {
public:
CompactionJobTest()
: env_(Env::Default()),
dbname_(test::TmpDir() + "/compaction_job_test"),
mutable_cf_options_(Options(), ImmutableCFOptions(Options())),
table_cache_(NewLRUCache(50000, 16)),
write_buffer_(db_options_.db_write_buffer_size),
versions_(new VersionSet(dbname_, &db_options_, env_options_,
table_cache_.get(), &write_buffer_,
&write_controller_)),
shutting_down_(false),
mock_table_factory_(new mock::MockTableFactory()) {
EXPECT_OK(env_->CreateDirIfMissing(dbname_));
db_options_.db_paths.emplace_back(dbname_,
std::numeric_limits<uint64_t>::max());
NewDB();
std::vector<ColumnFamilyDescriptor> column_families;
cf_options_.table_factory = mock_table_factory_;
column_families.emplace_back(kDefaultColumnFamilyName, cf_options_);
EXPECT_OK(versions_->Recover(column_families, false));
}
std::string GenerateFileName(uint64_t file_number) {
FileMetaData meta;
std::vector<DbPath> db_paths;
db_paths.emplace_back(dbname_, std::numeric_limits<uint64_t>::max());
meta.fd = FileDescriptor(file_number, 0, 0);
return TableFileName(db_paths, meta.fd.GetNumber(), meta.fd.GetPathId());
}
// returns expected result after compaction
mock::MockFileContents CreateTwoFiles() {
mock::MockFileContents expected_results;
const int kKeysPerFile = 10000;
SequenceNumber sequence_number = 0;
for (int i = 0; i < 2; ++i) {
mock::MockFileContents contents;
SequenceNumber smallest_seqno = 0, largest_seqno = 0;
InternalKey smallest, largest;
for (int k = 0; k < kKeysPerFile; ++k) {
auto key = ToString(i * (kKeysPerFile / 2) + k);
auto value = ToString(i * kKeysPerFile + k);
InternalKey internal_key(key, ++sequence_number, kTypeValue);
// This is how the key will look like once it's written in bottommost
// file
InternalKey bottommost_internal_key(key, 0, kTypeValue);
if (k == 0) {
smallest = internal_key;
smallest_seqno = sequence_number;
} else if (k == kKeysPerFile - 1) {
largest = internal_key;
largest_seqno = sequence_number;
}
contents.insert({internal_key.Encode().ToString(), value});
if (i == 1 || k < kKeysPerFile / 2) {
expected_results.insert(
{bottommost_internal_key.Encode().ToString(), value});
}
}
uint64_t file_number = versions_->NewFileNumber();
EXPECT_OK(mock_table_factory_->CreateMockTable(
env_, GenerateFileName(file_number), std::move(contents)));
VersionEdit edit;
edit.AddFile(0, file_number, 0, 10, smallest, largest, smallest_seqno,
largest_seqno, false);
mutex_.Lock();
versions_->LogAndApply(versions_->GetColumnFamilySet()->GetDefault(),
mutable_cf_options_, &edit, &mutex_);
mutex_.Unlock();
}
versions_->SetLastSequence(sequence_number + 1);
return expected_results;
}
void NewDB() {
VersionEdit new_db;
new_db.SetLogNumber(0);
new_db.SetNextFile(2);
new_db.SetLastSequence(0);
const std::string manifest = DescriptorFileName(dbname_, 1);
unique_ptr<WritableFile> file;
Status s = env_->NewWritableFile(
manifest, &file, env_->OptimizeForManifestWrite(env_options_));
ASSERT_OK(s);
{
log::Writer log(std::move(file));
std::string record;
new_db.EncodeTo(&record);
s = log.AddRecord(record);
}
ASSERT_OK(s);
// Make "CURRENT" file that points to the new manifest file.
s = SetCurrentFile(env_, dbname_, 1, nullptr);
}
Env* env_;
std::string dbname_;
EnvOptions env_options_;
MutableCFOptions mutable_cf_options_;
std::shared_ptr<Cache> table_cache_;
WriteController write_controller_;
DBOptions db_options_;
ColumnFamilyOptions cf_options_;
WriteBuffer write_buffer_;
std::unique_ptr<VersionSet> versions_;
InstrumentedMutex mutex_;
std::atomic<bool> shutting_down_;
std::shared_ptr<mock::MockTableFactory> mock_table_factory_;
};
namespace {
void VerifyInitializationOfCompactionJobStats(
const CompactionJobStats& compaction_job_stats) {
#if !defined(IOS_CROSS_COMPILE)
ASSERT_EQ(compaction_job_stats.elapsed_micros, 0U);
ASSERT_EQ(compaction_job_stats.num_input_records, 0U);
ASSERT_EQ(compaction_job_stats.num_input_files, 0U);
ASSERT_EQ(compaction_job_stats.num_input_files_at_output_level, 0U);
ASSERT_EQ(compaction_job_stats.num_output_records, 0U);
ASSERT_EQ(compaction_job_stats.num_output_files, 0U);
ASSERT_EQ(compaction_job_stats.is_manual_compaction, 0U);
ASSERT_EQ(compaction_job_stats.total_input_bytes, 0U);
ASSERT_EQ(compaction_job_stats.total_output_bytes, 0U);
ASSERT_EQ(compaction_job_stats.total_input_raw_key_bytes, 0U);
ASSERT_EQ(compaction_job_stats.total_input_raw_value_bytes, 0U);
ASSERT_EQ(compaction_job_stats.smallest_output_key_prefix[0], 0);
ASSERT_EQ(compaction_job_stats.largest_output_key_prefix[0], 0);
ASSERT_EQ(compaction_job_stats.num_records_replaced, 0U);
#endif // !defined(IOS_CROSS_COMPILE)
}
void VerifyCompactionJobStats(
const CompactionJobStats& compaction_job_stats,
const std::vector<FileMetaData*>& files,
size_t num_output_files) {
ASSERT_GE(compaction_job_stats.elapsed_micros, 0U);
ASSERT_EQ(compaction_job_stats.num_input_files, files.size());
ASSERT_EQ(compaction_job_stats.num_output_files, num_output_files);
}
} // namespace
TEST_F(CompactionJobTest, Simple) {
auto cfd = versions_->GetColumnFamilySet()->GetDefault();
auto expected_results = CreateTwoFiles();
auto files = cfd->current()->storage_info()->LevelFiles(0);
ASSERT_EQ(2U, files.size());
CompactionInputFiles compaction_input_files;
compaction_input_files.level = 0;
compaction_input_files.files.push_back(files[0]);
compaction_input_files.files.push_back(files[1]);
std::unique_ptr<Compaction> compaction(new Compaction(
cfd->current()->storage_info(), *cfd->GetLatestMutableCFOptions(),
{compaction_input_files}, 1, 1024 * 1024, 10, 0, kNoCompression, {}));
compaction->SetInputVersion(cfd->current());
int yield_callback_called = 0;
std::function<uint64_t()> yield_callback = [&]() {
yield_callback_called++;
return 0;
};
LogBuffer log_buffer(InfoLogLevel::INFO_LEVEL, db_options_.info_log.get());
mutex_.Lock();
EventLogger event_logger(db_options_.info_log.get());
std::string db_name = "dbname";
CompactionJobStats compaction_job_stats;
CompactionJob compaction_job(0, compaction.get(), db_options_, env_options_,
versions_.get(), &shutting_down_, &log_buffer,
nullptr, nullptr, nullptr, {}, table_cache_,
std::move(yield_callback), &event_logger, false,
db_name, &compaction_job_stats);
VerifyInitializationOfCompactionJobStats(compaction_job_stats);
compaction_job.Prepare();
mutex_.Unlock();
ASSERT_OK(compaction_job.Run());
mutex_.Lock();
Status s;
compaction_job.Install(&s, *cfd->GetLatestMutableCFOptions(), &mutex_);
ASSERT_OK(s);
mutex_.Unlock();
VerifyCompactionJobStats(
compaction_job_stats,
files, 1);
mock_table_factory_->AssertLatestFile(expected_results);
ASSERT_EQ(yield_callback_called, 20000);
}
} // namespace rocksdb
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<|endoftext|> |
<commit_before>///
/// @file S2_sieve.cpp
/// @brief Calculate the contribution of the special leaves which
/// require a sieve in the Deleglise-Rivat algorithm.
/// This is a parallel implementation which uses compression
/// (PiTable & FactorTable) to reduce the memory usage by
/// about 10x.
///
/// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <PiTable.hpp>
#include <FactorTable.hpp>
#include <primecount-internal.hpp>
#include <inttypes.hpp>
#include <pmath.hpp>
#include <BitSieve.hpp>
#include <tos_counters.hpp>
#include <S2LoadBalancer.hpp>
#include <S2Status.hpp>
#include <stdint.h>
#include <algorithm>
#include <iostream>
#include <vector>
#ifdef _OPENMP
#include <omp.h>
#endif
using namespace std;
using namespace primecount;
namespace {
namespace S2_sieve {
/// For each prime calculate its first multiple >= low
template <typename T>
vector<int64_t> generate_next_multiples(int64_t low, int64_t size, vector<T>& primes)
{
vector<int64_t> next;
next.reserve(size);
next.push_back(0);
for (int64_t b = 1; b < size; b++)
{
int64_t prime = primes[b];
int64_t next_multiple = ceil_div(low, prime) * prime;
next_multiple += prime * (~next_multiple & 1);
next.push_back(next_multiple);
}
return next;
}
/// Cross-off the multiples of prime in the sieve array.
/// For each element that is unmarked the first time update
/// the special counters tree data structure.
///
template <typename T>
void cross_off(int64_t prime,
int64_t low,
int64_t high,
int64_t& next_multiple,
BitSieve& sieve,
T& counters)
{
int64_t segment_size = sieve.size();
int64_t k = next_multiple;
for (; k < high; k += prime * 2)
{
if (sieve[k - low])
{
sieve.unset(k - low);
cnt_update(counters, k - low, segment_size);
}
}
next_multiple = k;
}
/// Compute the S2 contribution of the special leaves that require
/// a sieve. Each thread processes the interval
/// [low_thread, low_thread + segments * segment_size[
/// and the missing special leaf contributions for the interval
/// [1, low_process[ are later reconstructed and added in
/// the parent S2_sieve() function.
///
template <typename T, typename P, typename F>
T S2_sieve_thread(T x,
int64_t y,
int64_t z,
int64_t c,
int64_t segment_size,
int64_t segments_per_thread,
int64_t thread_num,
int64_t low,
int64_t limit,
FactorTable<F>& factors,
PiTable& pi,
vector<P>& primes,
vector<int64_t>& mu_sum,
vector<int64_t>& phi)
{
low += segment_size * segments_per_thread * thread_num;
limit = min(low + segment_size * segments_per_thread, limit);
int64_t pi_sqrty = pi[isqrt(y)];
int64_t max_prime = min3(isqrt(x / low), isqrt(z), y);
int64_t pi_max = pi[max_prime];
T S2_thread = 0;
BitSieve sieve(segment_size);
vector<int32_t> counters(segment_size);
vector<int64_t> next = generate_next_multiples(low, pi_max + 1, primes);
phi.resize(pi_max + 1, 0);
mu_sum.resize(pi_max + 1, 0);
// Segmeted sieve of Eratosthenes
for (; low < limit; low += segment_size)
{
// Current segment = interval [low, high[
int64_t high = min(low + segment_size, limit);
int64_t b = c + 1;
// check if we need the sieve
if (c <= pi_max)
{
sieve.fill(low, high);
// phi(y, i) nodes with i <= c do not contribute to S2, so we
// simply sieve out the multiples of the first c primes
for (int64_t i = 2; i <= c; i++)
{
int64_t k = next[i];
for (int64_t prime = primes[i]; k < high; k += prime * 2)
sieve.unset(k - low);
next[i] = k;
}
// Initialize special tree data structure from sieve
cnt_finit(sieve, counters, segment_size);
}
// For c + 1 <= b <= pi_sqrty
// Find all special leaves: n = primes[b] * m, with mu[m] != 0 and primes[b] < lpf[m]
// which satisfy: low <= (x / n) < high
for (int64_t end = min(pi_sqrty, pi_max); b <= end; b++)
{
int64_t prime = primes[b];
int64_t min_m = max(min(x / ((T) prime * (T) high), y), y / prime);
int64_t max_m = min(x / ((T) prime * (T) low), y);
if (prime >= max_m)
goto next_segment;
factors.to_index(&min_m);
factors.to_index(&max_m);
for (int64_t m = max_m; m > min_m; m--)
{
if (prime < factors.lpf(m))
{
int64_t n = prime * factors.get_number(m);
int64_t xn = (int64_t) (x / n);
int64_t count = cnt_query(counters, xn - low);
int64_t phi_xn = phi[b] + count;
int64_t mu_m = factors.mu(m);
S2_thread -= mu_m * phi_xn;
mu_sum[b] -= mu_m;
}
}
phi[b] += cnt_query(counters, (high - 1) - low);
cross_off(prime, low, high, next[b], sieve, counters);
}
// For pi_sqrty <= b <= pi_sqrtz
// Find all hard special leaves: n = primes[b] * primes[l]
// which satisfy: low <= (x / n) < high
for (; b <= pi_max; b++)
{
int64_t prime = primes[b];
int64_t l = pi[min3(x / ((T) prime * (T) low), z / prime, y)];
int64_t min_hard_leaf = max3(min(x / ((T) prime * (T) high), y), y / prime, prime);
if (prime >= primes[l])
goto next_segment;
for (; primes[l] > min_hard_leaf; l--)
{
int64_t n = prime * primes[l];
int64_t xn = x / n;
int64_t count = cnt_query(counters, xn - low);
int64_t phi_xn = phi[b] + count;
S2_thread += phi_xn;
mu_sum[b]++;
}
phi[b] += cnt_query(counters, (high - 1) - low);
cross_off(prime, low, high, next[b], sieve, counters);
}
next_segment:;
}
return S2_thread;
}
/// Calculate the contribution of the special leaves which require
/// a sieve (in order to reduce the memory usage).
/// This is a parallel implementation with advanced load balancing.
/// As most special leaves tend to be in the first segments we
/// start off with a small segment size and few segments
/// per thread, after each iteration we dynamically increase
/// the segment size and the segments per thread.
///
template <typename T, typename P, typename F>
T S2_sieve(T x,
int64_t y,
int64_t z,
int64_t c,
T s2_sieve_approx,
PiTable& pi,
vector<P>& primes,
FactorTable<F>& factors,
int threads)
{
if (print_status())
{
cout << endl;
cout << "=== S2_sieve(x, y) ===" << endl;
cout << "Computation of the special leaves requiring a sieve" << endl;
}
double time = get_wtime();
T s2_sieve = 0;
int64_t low = 1;
int64_t limit = z + 1;
S2Status status;
S2LoadBalancer loadBalancer(x, limit, threads);
int64_t segment_size = loadBalancer.get_min_segment_size();
int64_t segments_per_thread = 1;
vector<int64_t> phi_total(pi[min(isqrt(z), y)] + 1, 0);
while (low < limit)
{
int64_t segments = ceil_div(limit - low, segment_size);
threads = in_between(1, threads, segments);
segments_per_thread = in_between(1, segments_per_thread, ceil_div(segments, threads));
aligned_vector<vector<int64_t> > phi(threads);
aligned_vector<vector<int64_t> > mu_sum(threads);
aligned_vector<double> timings(threads);
#pragma omp parallel for num_threads(threads) reduction(+: s2_sieve)
for (int i = 0; i < threads; i++)
{
timings[i] = get_wtime();
s2_sieve += S2_sieve_thread(x, y, z, c, segment_size, segments_per_thread,
i, low, limit, factors, pi, primes, mu_sum[i], phi[i]);
timings[i] = get_wtime() - timings[i];
}
// Once all threads have finished reconstruct and add the
// missing contribution of all special leaves. This must
// be done in order as each thread (i) requires the sum of
// the phi values from the previous threads.
//
for (int i = 0; i < threads; i++)
{
for (size_t j = 1; j < phi[i].size(); j++)
{
s2_sieve += phi_total[j] * (T) mu_sum[i][j];
phi_total[j] += phi[i][j];
}
}
low += segments_per_thread * threads * segment_size;
loadBalancer.update(low, threads, &segment_size, &segments_per_thread, timings);
if (print_status())
status.print(s2_sieve, s2_sieve_approx, loadBalancer.get_rsd());
}
if (print_status())
print_result("S2_sieve", s2_sieve, time);
return s2_sieve;
}
} // namespace S2_sieve
} // namespace
namespace primecount {
int64_t S2_sieve(int64_t x,
int64_t y,
int64_t z,
int64_t c,
int64_t s2_sieve_approx,
PiTable& pi,
vector<int32_t>& primes,
FactorTable<uint16_t>& factors,
int threads)
{
assert(x >= 0);
return S2_sieve::S2_sieve((uint64_t) x, y, z, c, (uint64_t) s2_sieve_approx, pi, primes, factors, threads);
}
#ifdef HAVE_INT128_T
int128_t S2_sieve(int128_t x,
int64_t y,
int64_t z,
int64_t c,
int128_t s2_sieve_approx,
PiTable& pi,
vector<uint32_t>& primes,
FactorTable<uint16_t>& factors,
int threads)
{
assert(x >= 0);
return S2_sieve::S2_sieve((uint128_t) x, y, z, c, (uint128_t) s2_sieve_approx, pi, primes, factors, threads);
}
int128_t S2_sieve(int128_t x,
int64_t y,
int64_t z,
int64_t c,
int128_t s2_sieve_approx,
PiTable& pi,
vector<int64_t>& primes,
FactorTable<uint32_t>& factors,
int threads)
{
assert(x >= 0);
return S2_sieve::S2_sieve((uint128_t) x, y, z, c, (uint128_t) s2_sieve_approx, pi, primes, factors, threads);
}
#endif
} // namespace primecount
<commit_msg>Use intfast* types<commit_after>///
/// @file S2_sieve.cpp
/// @brief Calculate the contribution of the special leaves which
/// require a sieve in the Deleglise-Rivat algorithm.
/// This is a parallel implementation which uses compression
/// (PiTable & FactorTable) to reduce the memory usage by
/// about 10x.
///
/// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <PiTable.hpp>
#include <FactorTable.hpp>
#include <primecount-internal.hpp>
#include <inttypes.hpp>
#include <pmath.hpp>
#include <BitSieve.hpp>
#include <tos_counters.hpp>
#include <S2LoadBalancer.hpp>
#include <S2Status.hpp>
#include <stdint.h>
#include <algorithm>
#include <iostream>
#include <vector>
#ifdef _OPENMP
#include <omp.h>
#endif
using namespace std;
using namespace primecount;
namespace {
namespace S2_sieve {
/// For each prime calculate its first multiple >= low
template <typename T>
vector<int64_t> generate_next_multiples(int64_t low, int64_t size, vector<T>& primes)
{
vector<int64_t> next;
next.reserve(size);
next.push_back(0);
for (int64_t b = 1; b < size; b++)
{
int64_t prime = primes[b];
int64_t next_multiple = ceil_div(low, prime) * prime;
next_multiple += prime * (~next_multiple & 1);
next.push_back(next_multiple);
}
return next;
}
/// Cross-off the multiples of prime in the sieve array.
/// For each element that is unmarked the first time update
/// the special counters tree data structure.
///
template <typename T>
void cross_off(int64_t prime,
int64_t low,
int64_t high,
int64_t& next_multiple,
BitSieve& sieve,
T& counters)
{
int64_t segment_size = sieve.size();
int64_t k = next_multiple;
for (; k < high; k += prime * 2)
{
if (sieve[k - low])
{
sieve.unset(k - low);
cnt_update(counters, k - low, segment_size);
}
}
next_multiple = k;
}
/// Compute the S2 contribution of the special leaves that require
/// a sieve. Each thread processes the interval
/// [low_thread, low_thread + segments * segment_size[
/// and the missing special leaf contributions for the interval
/// [1, low_process[ are later reconstructed and added in
/// the parent S2_sieve() function.
///
template <typename T, typename P, typename F>
T S2_sieve_thread(T x,
int64_t y,
int64_t z,
int64_t c,
int64_t segment_size,
int64_t segments_per_thread,
int64_t thread_num,
int64_t low,
int64_t limit,
FactorTable<F>& factors,
PiTable& pi,
vector<P>& primes,
vector<int64_t>& mu_sum,
vector<int64_t>& phi)
{
low += segment_size * segments_per_thread * thread_num;
limit = min(low + segment_size * segments_per_thread, limit);
int64_t pi_sqrty = pi[isqrt(y)];
int64_t max_prime = min3(isqrt(x / low), isqrt(z), y);
int64_t pi_max = pi[max_prime];
T S2_thread = 0;
BitSieve sieve(segment_size);
vector<int32_t> counters(segment_size);
vector<int64_t> next = generate_next_multiples(low, pi_max + 1, primes);
phi.resize(pi_max + 1, 0);
mu_sum.resize(pi_max + 1, 0);
// Segmeted sieve of Eratosthenes
for (; low < limit; low += segment_size)
{
// Current segment = interval [low, high[
int64_t high = min(low + segment_size, limit);
int64_t b = c + 1;
// check if we need the sieve
if (c <= pi_max)
{
sieve.fill(low, high);
// phi(y, i) nodes with i <= c do not contribute to S2, so we
// simply sieve out the multiples of the first c primes
for (int64_t i = 2; i <= c; i++)
{
int64_t k = next[i];
for (int64_t prime = primes[i]; k < high; k += prime * 2)
sieve.unset(k - low);
next[i] = k;
}
// Initialize special tree data structure from sieve
cnt_finit(sieve, counters, segment_size);
}
// For c + 1 <= b <= pi_sqrty
// Find all special leaves: n = primes[b] * m, with mu[m] != 0 and primes[b] < lpf[m]
// which satisfy: low <= (x / n) < high
for (int64_t end = min(pi_sqrty, pi_max); b <= end; b++)
{
int64_t prime = primes[b];
int64_t min_m = max(min(x / ((T) prime * (T) high), y), y / prime);
int64_t max_m = min(x / ((T) prime * (T) low), y);
if (prime >= max_m)
goto next_segment;
factors.to_index(&min_m);
factors.to_index(&max_m);
for (int64_t m = max_m; m > min_m; m--)
{
if (prime < factors.lpf(m))
{
int64_t n = prime * factors.get_number(m);
int64_t xn = (int64_t) (x / n);
int64_t count = cnt_query(counters, xn - low);
int64_t phi_xn = phi[b] + count;
int64_t mu_m = factors.mu(m);
S2_thread -= mu_m * phi_xn;
mu_sum[b] -= mu_m;
}
}
phi[b] += cnt_query(counters, (high - 1) - low);
cross_off(prime, low, high, next[b], sieve, counters);
}
// For pi_sqrty <= b <= pi_sqrtz
// Find all hard special leaves: n = primes[b] * primes[l]
// which satisfy: low <= (x / n) < high
for (; b <= pi_max; b++)
{
int64_t prime = primes[b];
int64_t l = pi[min3(x / ((T) prime * (T) low), z / prime, y)];
int64_t min_hard_leaf = max3(min(x / ((T) prime * (T) high), y), y / prime, prime);
if (prime >= primes[l])
goto next_segment;
for (; primes[l] > min_hard_leaf; l--)
{
int64_t n = prime * primes[l];
int64_t xn = x / n;
int64_t count = cnt_query(counters, xn - low);
int64_t phi_xn = phi[b] + count;
S2_thread += phi_xn;
mu_sum[b]++;
}
phi[b] += cnt_query(counters, (high - 1) - low);
cross_off(prime, low, high, next[b], sieve, counters);
}
next_segment:;
}
return S2_thread;
}
/// Calculate the contribution of the special leaves which require
/// a sieve (in order to reduce the memory usage).
/// This is a parallel implementation with advanced load balancing.
/// As most special leaves tend to be in the first segments we
/// start off with a small segment size and few segments
/// per thread, after each iteration we dynamically increase
/// the segment size and the segments per thread.
///
template <typename T, typename P, typename F>
T S2_sieve(T x,
int64_t y,
int64_t z,
int64_t c,
T s2_sieve_approx,
PiTable& pi,
vector<P>& primes,
FactorTable<F>& factors,
int threads)
{
if (print_status())
{
cout << endl;
cout << "=== S2_sieve(x, y) ===" << endl;
cout << "Computation of the special leaves requiring a sieve" << endl;
}
double time = get_wtime();
T s2_sieve = 0;
int64_t low = 1;
int64_t limit = z + 1;
S2Status status;
S2LoadBalancer loadBalancer(x, limit, threads);
int64_t segment_size = loadBalancer.get_min_segment_size();
int64_t segments_per_thread = 1;
vector<int64_t> phi_total(pi[min(isqrt(z), y)] + 1, 0);
while (low < limit)
{
int64_t segments = ceil_div(limit - low, segment_size);
threads = in_between(1, threads, segments);
segments_per_thread = in_between(1, segments_per_thread, ceil_div(segments, threads));
aligned_vector<vector<int64_t> > phi(threads);
aligned_vector<vector<int64_t> > mu_sum(threads);
aligned_vector<double> timings(threads);
#pragma omp parallel for num_threads(threads) reduction(+: s2_sieve)
for (int i = 0; i < threads; i++)
{
timings[i] = get_wtime();
s2_sieve += S2_sieve_thread(x, y, z, c, segment_size, segments_per_thread,
i, low, limit, factors, pi, primes, mu_sum[i], phi[i]);
timings[i] = get_wtime() - timings[i];
}
// Once all threads have finished reconstruct and add the
// missing contribution of all special leaves. This must
// be done in order as each thread (i) requires the sum of
// the phi values from the previous threads.
//
for (int i = 0; i < threads; i++)
{
for (size_t j = 1; j < phi[i].size(); j++)
{
s2_sieve += phi_total[j] * (T) mu_sum[i][j];
phi_total[j] += phi[i][j];
}
}
low += segments_per_thread * threads * segment_size;
loadBalancer.update(low, threads, &segment_size, &segments_per_thread, timings);
if (print_status())
status.print(s2_sieve, s2_sieve_approx, loadBalancer.get_rsd());
}
if (print_status())
print_result("S2_sieve", s2_sieve, time);
return s2_sieve;
}
} // namespace S2_sieve
} // namespace
namespace primecount {
int64_t S2_sieve(int64_t x,
int64_t y,
int64_t z,
int64_t c,
int64_t s2_sieve_approx,
PiTable& pi,
vector<int32_t>& primes,
FactorTable<uint16_t>& factors,
int threads)
{
return S2_sieve::S2_sieve((intfast64_t) x, y, z, c, (intfast64_t) s2_sieve_approx, pi, primes, factors, threads);
}
#ifdef HAVE_INT128_T
int128_t S2_sieve(int128_t x,
int64_t y,
int64_t z,
int64_t c,
int128_t s2_sieve_approx,
PiTable& pi,
vector<uint32_t>& primes,
FactorTable<uint16_t>& factors,
int threads)
{
return S2_sieve::S2_sieve((intfast128_t) x, y, z, c, (intfast128_t) s2_sieve_approx, pi, primes, factors, threads);
}
int128_t S2_sieve(int128_t x,
int64_t y,
int64_t z,
int64_t c,
int128_t s2_sieve_approx,
PiTable& pi,
vector<int64_t>& primes,
FactorTable<uint32_t>& factors,
int threads)
{
return S2_sieve::S2_sieve((intfast128_t) x, y, z, c, (intfast128_t) s2_sieve_approx, pi, primes, factors, threads);
}
#endif
} // namespace primecount
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: locale.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: vg $ $Date: 2005-02-16 15:56: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): _______________________________________
*
*
************************************************************************/
#ifndef _COMPHELPER_LOCALE_HXX_
#define _COMPHELPER_LOCALE_HXX_
//_______________________________________________
// includes
#include <vector>
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef INCLUDED_COMPHELPERDLLAPI_H
#include "comphelper/comphelperdllapi.h"
#endif
//_______________________________________________
// namespace
namespace comphelper{
//_______________________________________________
// definitions
/** @short A Locale object represents a specific geographical, political, or cultural region.
@descr This Locale class can be used to:
- provide the different parts of a Locale (Language, Country, Variant)
- converting it from/to ISO formated string values (like e.g. "en-US")
- provide some predefined (static) Locale objects
*/
class COMPHELPER_DLLPUBLIC Locale
{
//-------------------------------------------
// const
public:
/** @short seperates LANGUAGE and COUNTRY part of an ISO formated Locale. */
static const sal_Unicode SEPERATOR_LC;
/** @short seperates COUNTRY and VARIANT part of an ISO formated Locale. */
static const sal_Unicode SEPERATOR_CV;
/** @short seperates COUNTRY and VARIANT part of an ISO formated Locale.
@descr Its true for some linux derivates only :-( */
static const sal_Unicode SEPERATOR_CV_LINUX;
/** @short some predefined Locale objects. */
static const Locale EN_US();
static const Locale EN();
static const Locale DE_DE();
static const Locale DE_CH();
static const Locale DE_AT();
static const Locale AR();
static const Locale CA();
static const Locale CS();
static const Locale DA();
static const Locale EL();
static const Locale ES();
static const Locale FI();
static const Locale FR();
static const Locale HE();
static const Locale HI_IN();
static const Locale HU();
static const Locale IT();
static const Locale JA();
static const Locale KO();
static const Locale NL();
static const Locale PL();
static const Locale PT();
static const Locale PT_BR();
static const Locale RU();
static const Locale SK();
static const Locale SL();
static const Locale SV();
static const Locale TH();
static const Locale TR();
static const Locale X_DEFAULT();
static const Locale X_COMMENT();
static const Locale X_TRANSLATE();
static const Locale X_NOTRANSLATE();
static const Locale ZH_CN();
static const Locale ZH_TW();
//-------------------------------------------
// types
public:
/** @short will be throw during convertion, if a Locale cant be interpreted. */
struct MalFormedLocaleException
{
public:
::rtl::OUString Message;
MalFormedLocaleException()
{}
MalFormedLocaleException(const ::rtl::OUString& sMessage)
: Message(sMessage)
{}
};
//-------------------------------------------
// member
private :
//---------------------------------------
/** @short must be a valid ISO Language Code.
@descr These codes are the lower-case two-letter codes as defined by ISO-639.
You can find a full list of these codes at a number of sites, such as:
<BR><a href ="http://www.ics.uci.edu/pub/ietf/http/related/iso639.txt">
http://www.ics.uci.edu/pub/ietf/http/related/iso639.txt</a>
*/
::rtl::OUString m_sLanguage;
//---------------------------------------
/** @short must be a valid ISO Country Code.
@descr These codes are the upper-case two-letter codes as defined by ISO-3166.
You can find a full list of these codes at a number of sites, such as:
<BR><a href="http://www.chemie.fu-berlin.de/diverse/doc/ISO_3166.html">
http://www.chemie.fu-berlin.de/diverse/doc/ISO_3166.html</a>
*/
::rtl::OUString m_sCountry;
//---------------------------------------
/** @short Variant codes are vendor and browser-specific.
@descr For example, use WIN for Windows, MAC for Macintosh, and POSIX for POSIX.
Where there are two variants, separate them with an underscore, and
put the most important one first. For example, a Traditional Spanish collation
might be referenced, with "ES", "ES", "Traditional_WIN".
*/
::rtl::OUString m_sVariant;
//-------------------------------------------
// interface
public :
//---------------------------------------
/** @short needed by outside users!
@descr Otherwise it wouldnt be possible to use
any instance of such Locale static ...
*/
Locale();
//---------------------------------------
/** @short construct a Locale from an ISO formated string value.
@seealso fromISO()
@param sISO
an ISO formated string value, which can be parsed and
tokenized into a Lamnguage, Country and Variant part.
@throw MalFormedLocaleException
if conversion failed.
*/
Locale(const ::rtl::OUString& sISO)
throw(MalFormedLocaleException);
//---------------------------------------
/** @short construct a Locale from language, country and variant.
@seealso setLanguage()
@seealso setCountry()
@seealso setVariant()
@param sLanguage
lowercase two-letter ISO-639 code.
@param sCountry
uppercase two-letter ISO-3166 code.
@param sVariant
vendor and browser specific code.
*/
Locale(const ::rtl::OUString& sLanguage ,
const ::rtl::OUString& sCountry ,
const ::rtl::OUString& sVariant = ::rtl::OUString());
//---------------------------------------
/** @short copy constructor.
@param aCopy
the copy object.
*/
Locale(const Locale& aCopy);
//---------------------------------------
/** @short returns the language code for this locale.
@descr That will either be the empty string or
a lowercase ISO 639 code.
@return [string]
the language code.
*/
::rtl::OUString getLanguage() const;
//---------------------------------------
/** @short returns the country/region code for this locale.
@descr That will either be the empty string or an
upercase ISO 3166 2-letter code.
@return [string]
the country code.
*/
::rtl::OUString getCountry() const;
//---------------------------------------
/** @short returns the variant code for this locale.
@return [string]
the variant code.
*/
::rtl::OUString getVariant() const;
//---------------------------------------
/** @short set the new language code for this locale.
@descr That will either be the empty string or
a lowercase ISO 639 code.
@param sLanguage
the language code.
*/
void setLanguage(const ::rtl::OUString& sLanguage);
//---------------------------------------
/** @short set the new country/region code for this locale.
@descr That will either be the empty string or an
upercase ISO 3166 2-letter code.
@param sCountry
the country code.
*/
void setCountry(const ::rtl::OUString& sCountry);
//---------------------------------------
/** @short set the new variant code for this locale.
@param sVariant
the variant code.
*/
void setVariant(const ::rtl::OUString& sVariant);
//---------------------------------------
/** @short take over new Locale informations.
@seealso Locale(const ::rtl::OUString& sISO)
@param sISO
an ISO formated string value, which can be parsed and
tokenized into a Lamnguage, Country and Variant part.
e.g. "en-US" or "en-US_WIN"
@throw MalFormedLocaleException
if conversion failed.
*/
void fromISO(const ::rtl::OUString& sISO)
throw(MalFormedLocaleException);
//---------------------------------------
/** @short converts this Locale to an ISO formated string value.
@descr The different parts of this Locale will be assempled
e.g. to "en-US" or "en-US_WIN"
@return [string]
the ISO formated string.
*/
::rtl::OUString toISO() const;
//---------------------------------------
/** @short check, if two Locale objects are equals.
@descr All parts of a Locale (means Language, Country and Variant)
will be checked.
@param aComparable
the Locale object for compare.
@return [boolean]
TRUE if both objects uses the same values for
Language, Country and Variant.
*/
sal_Bool equals(const Locale& aComparable) const;
//---------------------------------------
/** @short check, if two Locale objects
uses the same language.
@descr The Country and Variant parts of a Locale
wont be checked here.
@return [boolean]
TRUE if both objects uses the same
Language value.
*/
sal_Bool similar(const Locale& aComparable) const;
//---------------------------------------
/** @short search for an equal or at least for a similar
Locale in a list of possible ones.
@descr First it searches for a Locale, which is equals
to the reference Locale.
(means: same Language, Country, Variant)
If the reference Locale couldnt be located, it will
tried again - but we are checking for "similar" Locales then.
(means: same Language)
If no similar Locale could be located, we search
for a Locale "en-US" inside the given Locale list.
If "en-US" could not be located, we search for
a Locale "en" inside the given list.
If no "same" nor any "similar" locale could be found,
we try "x-default" and "x-notranslate" explicitly.
Sometimes localized variables are optimized and doesnt use
localzation realy. E.g. in case the localized value is a fix
product name.
If no locale match till now, we use any other existing
locale, which exists inside the set of given ones!
@seealso equals()
@seealso similar()
@param lISOList
the list of possible Locales
(as formated ISO strings).
@param sReferenceISO
the reference Locale, which should be searched
if its equals or similar to any Locale inside
the provided Locale list.
@return An iterator, which points to the found element
inside the given Locale list.
If no matching Locale could be found, it points
to the end of the list.
@throw [MalFormedLocaleException]
if at least one ISO formated string couldnt
be converted to a valid Locale Object.
*/
static ::std::vector< ::rtl::OUString >::const_iterator getFallback(const ::std::vector< ::rtl::OUString >& lISOList ,
const ::rtl::OUString& sReferenceISO)
throw(MalFormedLocaleException);
//---------------------------------------
/** @short search for the next possible fallback locale.
@descr Instead of getFallback(vector<>, string) this method
uses the given locale and decide by using an algorithm
which locale can be the next possible one.
Algorithm:
- if locale has country return language only
- if locale different "en-US" return "en-US"
- if locale "en-US" return "en"
@param aLocale [in/out]!
the incoming value will be used to start
search for a possible fallback ...
and in case such fallback was found this parameter
will be used for return too.
@return TRUE if the parameter aLocale contains a new fallback value;
FALSE otherwise.
*/
static sal_Bool getFallback(Locale& aLocale);
//---------------------------------------
/** @short assign elements of another locale
to this instance.
@param rCopy
another locale object.
*/
void operator=(const Locale& rCopy);
//---------------------------------------
/** @short check if two Locale objects are equals.
@seealso equals()
@param aComparable
the Locale object for compare.
@return [boolean]
TRUE if both objects uses the same values for
Language, Country and Variant.
*/
sal_Bool operator==(const Locale& aComparable) const;
//---------------------------------------
/** @short check if two Locale objects are different.
@param aComparable
the Locale object for compare.
@return [boolean]
TRUE if at least one part of such Locale
isnt the same.
*/
sal_Bool operator!=(const Locale& aComparable) const;
};
} // namespace salhelper
#endif // _COMPHELPER_LOCALE_HXX_
<commit_msg>INTEGRATION: CWS ooo19126 (1.6.56); FILE MERGED 2005/09/05 15:23:43 rt 1.6.56.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: locale.hxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: rt $ $Date: 2005-09-08 02:32:35 $
*
* 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 _COMPHELPER_LOCALE_HXX_
#define _COMPHELPER_LOCALE_HXX_
//_______________________________________________
// includes
#include <vector>
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef INCLUDED_COMPHELPERDLLAPI_H
#include "comphelper/comphelperdllapi.h"
#endif
//_______________________________________________
// namespace
namespace comphelper{
//_______________________________________________
// definitions
/** @short A Locale object represents a specific geographical, political, or cultural region.
@descr This Locale class can be used to:
- provide the different parts of a Locale (Language, Country, Variant)
- converting it from/to ISO formated string values (like e.g. "en-US")
- provide some predefined (static) Locale objects
*/
class COMPHELPER_DLLPUBLIC Locale
{
//-------------------------------------------
// const
public:
/** @short seperates LANGUAGE and COUNTRY part of an ISO formated Locale. */
static const sal_Unicode SEPERATOR_LC;
/** @short seperates COUNTRY and VARIANT part of an ISO formated Locale. */
static const sal_Unicode SEPERATOR_CV;
/** @short seperates COUNTRY and VARIANT part of an ISO formated Locale.
@descr Its true for some linux derivates only :-( */
static const sal_Unicode SEPERATOR_CV_LINUX;
/** @short some predefined Locale objects. */
static const Locale EN_US();
static const Locale EN();
static const Locale DE_DE();
static const Locale DE_CH();
static const Locale DE_AT();
static const Locale AR();
static const Locale CA();
static const Locale CS();
static const Locale DA();
static const Locale EL();
static const Locale ES();
static const Locale FI();
static const Locale FR();
static const Locale HE();
static const Locale HI_IN();
static const Locale HU();
static const Locale IT();
static const Locale JA();
static const Locale KO();
static const Locale NL();
static const Locale PL();
static const Locale PT();
static const Locale PT_BR();
static const Locale RU();
static const Locale SK();
static const Locale SL();
static const Locale SV();
static const Locale TH();
static const Locale TR();
static const Locale X_DEFAULT();
static const Locale X_COMMENT();
static const Locale X_TRANSLATE();
static const Locale X_NOTRANSLATE();
static const Locale ZH_CN();
static const Locale ZH_TW();
//-------------------------------------------
// types
public:
/** @short will be throw during convertion, if a Locale cant be interpreted. */
struct MalFormedLocaleException
{
public:
::rtl::OUString Message;
MalFormedLocaleException()
{}
MalFormedLocaleException(const ::rtl::OUString& sMessage)
: Message(sMessage)
{}
};
//-------------------------------------------
// member
private :
//---------------------------------------
/** @short must be a valid ISO Language Code.
@descr These codes are the lower-case two-letter codes as defined by ISO-639.
You can find a full list of these codes at a number of sites, such as:
<BR><a href ="http://www.ics.uci.edu/pub/ietf/http/related/iso639.txt">
http://www.ics.uci.edu/pub/ietf/http/related/iso639.txt</a>
*/
::rtl::OUString m_sLanguage;
//---------------------------------------
/** @short must be a valid ISO Country Code.
@descr These codes are the upper-case two-letter codes as defined by ISO-3166.
You can find a full list of these codes at a number of sites, such as:
<BR><a href="http://www.chemie.fu-berlin.de/diverse/doc/ISO_3166.html">
http://www.chemie.fu-berlin.de/diverse/doc/ISO_3166.html</a>
*/
::rtl::OUString m_sCountry;
//---------------------------------------
/** @short Variant codes are vendor and browser-specific.
@descr For example, use WIN for Windows, MAC for Macintosh, and POSIX for POSIX.
Where there are two variants, separate them with an underscore, and
put the most important one first. For example, a Traditional Spanish collation
might be referenced, with "ES", "ES", "Traditional_WIN".
*/
::rtl::OUString m_sVariant;
//-------------------------------------------
// interface
public :
//---------------------------------------
/** @short needed by outside users!
@descr Otherwise it wouldnt be possible to use
any instance of such Locale static ...
*/
Locale();
//---------------------------------------
/** @short construct a Locale from an ISO formated string value.
@seealso fromISO()
@param sISO
an ISO formated string value, which can be parsed and
tokenized into a Lamnguage, Country and Variant part.
@throw MalFormedLocaleException
if conversion failed.
*/
Locale(const ::rtl::OUString& sISO)
throw(MalFormedLocaleException);
//---------------------------------------
/** @short construct a Locale from language, country and variant.
@seealso setLanguage()
@seealso setCountry()
@seealso setVariant()
@param sLanguage
lowercase two-letter ISO-639 code.
@param sCountry
uppercase two-letter ISO-3166 code.
@param sVariant
vendor and browser specific code.
*/
Locale(const ::rtl::OUString& sLanguage ,
const ::rtl::OUString& sCountry ,
const ::rtl::OUString& sVariant = ::rtl::OUString());
//---------------------------------------
/** @short copy constructor.
@param aCopy
the copy object.
*/
Locale(const Locale& aCopy);
//---------------------------------------
/** @short returns the language code for this locale.
@descr That will either be the empty string or
a lowercase ISO 639 code.
@return [string]
the language code.
*/
::rtl::OUString getLanguage() const;
//---------------------------------------
/** @short returns the country/region code for this locale.
@descr That will either be the empty string or an
upercase ISO 3166 2-letter code.
@return [string]
the country code.
*/
::rtl::OUString getCountry() const;
//---------------------------------------
/** @short returns the variant code for this locale.
@return [string]
the variant code.
*/
::rtl::OUString getVariant() const;
//---------------------------------------
/** @short set the new language code for this locale.
@descr That will either be the empty string or
a lowercase ISO 639 code.
@param sLanguage
the language code.
*/
void setLanguage(const ::rtl::OUString& sLanguage);
//---------------------------------------
/** @short set the new country/region code for this locale.
@descr That will either be the empty string or an
upercase ISO 3166 2-letter code.
@param sCountry
the country code.
*/
void setCountry(const ::rtl::OUString& sCountry);
//---------------------------------------
/** @short set the new variant code for this locale.
@param sVariant
the variant code.
*/
void setVariant(const ::rtl::OUString& sVariant);
//---------------------------------------
/** @short take over new Locale informations.
@seealso Locale(const ::rtl::OUString& sISO)
@param sISO
an ISO formated string value, which can be parsed and
tokenized into a Lamnguage, Country and Variant part.
e.g. "en-US" or "en-US_WIN"
@throw MalFormedLocaleException
if conversion failed.
*/
void fromISO(const ::rtl::OUString& sISO)
throw(MalFormedLocaleException);
//---------------------------------------
/** @short converts this Locale to an ISO formated string value.
@descr The different parts of this Locale will be assempled
e.g. to "en-US" or "en-US_WIN"
@return [string]
the ISO formated string.
*/
::rtl::OUString toISO() const;
//---------------------------------------
/** @short check, if two Locale objects are equals.
@descr All parts of a Locale (means Language, Country and Variant)
will be checked.
@param aComparable
the Locale object for compare.
@return [boolean]
TRUE if both objects uses the same values for
Language, Country and Variant.
*/
sal_Bool equals(const Locale& aComparable) const;
//---------------------------------------
/** @short check, if two Locale objects
uses the same language.
@descr The Country and Variant parts of a Locale
wont be checked here.
@return [boolean]
TRUE if both objects uses the same
Language value.
*/
sal_Bool similar(const Locale& aComparable) const;
//---------------------------------------
/** @short search for an equal or at least for a similar
Locale in a list of possible ones.
@descr First it searches for a Locale, which is equals
to the reference Locale.
(means: same Language, Country, Variant)
If the reference Locale couldnt be located, it will
tried again - but we are checking for "similar" Locales then.
(means: same Language)
If no similar Locale could be located, we search
for a Locale "en-US" inside the given Locale list.
If "en-US" could not be located, we search for
a Locale "en" inside the given list.
If no "same" nor any "similar" locale could be found,
we try "x-default" and "x-notranslate" explicitly.
Sometimes localized variables are optimized and doesnt use
localzation realy. E.g. in case the localized value is a fix
product name.
If no locale match till now, we use any other existing
locale, which exists inside the set of given ones!
@seealso equals()
@seealso similar()
@param lISOList
the list of possible Locales
(as formated ISO strings).
@param sReferenceISO
the reference Locale, which should be searched
if its equals or similar to any Locale inside
the provided Locale list.
@return An iterator, which points to the found element
inside the given Locale list.
If no matching Locale could be found, it points
to the end of the list.
@throw [MalFormedLocaleException]
if at least one ISO formated string couldnt
be converted to a valid Locale Object.
*/
static ::std::vector< ::rtl::OUString >::const_iterator getFallback(const ::std::vector< ::rtl::OUString >& lISOList ,
const ::rtl::OUString& sReferenceISO)
throw(MalFormedLocaleException);
//---------------------------------------
/** @short search for the next possible fallback locale.
@descr Instead of getFallback(vector<>, string) this method
uses the given locale and decide by using an algorithm
which locale can be the next possible one.
Algorithm:
- if locale has country return language only
- if locale different "en-US" return "en-US"
- if locale "en-US" return "en"
@param aLocale [in/out]!
the incoming value will be used to start
search for a possible fallback ...
and in case such fallback was found this parameter
will be used for return too.
@return TRUE if the parameter aLocale contains a new fallback value;
FALSE otherwise.
*/
static sal_Bool getFallback(Locale& aLocale);
//---------------------------------------
/** @short assign elements of another locale
to this instance.
@param rCopy
another locale object.
*/
void operator=(const Locale& rCopy);
//---------------------------------------
/** @short check if two Locale objects are equals.
@seealso equals()
@param aComparable
the Locale object for compare.
@return [boolean]
TRUE if both objects uses the same values for
Language, Country and Variant.
*/
sal_Bool operator==(const Locale& aComparable) const;
//---------------------------------------
/** @short check if two Locale objects are different.
@param aComparable
the Locale object for compare.
@return [boolean]
TRUE if at least one part of such Locale
isnt the same.
*/
sal_Bool operator!=(const Locale& aComparable) const;
};
} // namespace salhelper
#endif // _COMPHELPER_LOCALE_HXX_
<|endoftext|> |
<commit_before>#include <klocale.h>
/****************************************************************************
** Form implementation generated from reading ui file './perlscriptprefsbase.ui'
**
** Created: Thu Jan 30 16:51:04 2003
** by: The User Interface Compiler ()
**
** WARNING! All changes made in this file will be lost!
****************************************************************************/
#include "perlscriptprefsbase.h"
#include <qvariant.h>
#include <klistview.h>
#include <ktrader.h>
#include <klibloader.h>
#include <qhbox.h>
#include <kpushbutton.h>
#include <qheader.h>
#include <qlayout.h>
#include <qtooltip.h>
#include <qwhatsthis.h>
#include <kstdaction.h>
#include <kactioncollection.h>
#include <ktexteditor/clipboardinterface.h>
#include <ktexteditor/highlightinginterface.h>
#include <ktexteditor/document.h>
#include <ktexteditor/view.h>
/*
* Constructs a PerlScriptPrefsUI as a child of 'parent', with the
* name 'name' and widget flags set to 'f'.
*/
PerlScriptPrefsUI::PerlScriptPrefsUI( QWidget* parent, const char* name, WFlags fl )
: QWidget( parent, name, fl )
{
if ( !name )
setName( "PerlScriptPrefsUI" );
QVBoxLayout *v = new QVBoxLayout( this, 4 );
scriptView = new KListView( this, "scriptView" );
scriptView->setAllColumnsShowFocus( true );
scriptView->addColumn( i18n("Name") );
scriptView->addColumn( i18n("Description") );
scriptView->addColumn( i18n("Path") );
scriptView->setMaximumHeight( 140 );
v->addWidget( scriptView );
QHBoxLayout *h = new QHBoxLayout( this, 4 );
h->insertStretch(0);
removeButton = new KPushButton( this, "removeButton" );
removeButton->setSizePolicy( QSizePolicy::Fixed, QSizePolicy::Fixed );
h->addWidget( removeButton );
addButton = new KPushButton( this, "addButton" );
addButton->setSizePolicy( QSizePolicy::Fixed, QSizePolicy::Fixed );
h->addWidget( addButton );
v->addLayout( h );
QHBox *f = new QHBox( this );
f->setFrameStyle( QFrame::WinPanel | QFrame::Sunken );
KTrader::OfferList offers = KTrader::self()->query( "KTextEditor/Document" );
KService::Ptr service = *offers.begin();
KLibFactory *factory = KLibLoader::self()->factory( service->library() );
editDocument = static_cast<KTextEditor::Document *>( factory->create( f, 0, "KTextEditor::Document" ) );
editArea = editDocument->createView( f, 0 );
setHighlight();
//v->addWidget( editArea );
v->addWidget( f );
cp = KTextEditor::clipboardInterface( editArea );
KActionCollection *coll = new KActionCollection(this);
KStdAction::cut( this, SLOT(slotCut()), coll);
KStdAction::copy( this, SLOT(slotCopy()), coll);
KStdAction::paste( this, SLOT(slotPaste()), coll);
QHBoxLayout *h2 = new QHBoxLayout( this, 4 );
h2->insertStretch(0);
saveButton = new KPushButton( this, "saveButton" );
saveButton->setSizePolicy( QSizePolicy::Fixed, QSizePolicy::Fixed );
h2->addWidget( saveButton );
v->addLayout(h2);
languageChange();
}
/*
* Destroys the object and frees any allocated resources
*/
PerlScriptPrefsUI::~PerlScriptPrefsUI()
{
// no need to delete child widgets, Qt does it all for us
}
void PerlScriptPrefsUI::setHighlight()
{
KTextEditor::HighlightingInterface *hi = KTextEditor::highlightingInterface( editDocument );
int count = hi->hlModeCount();
for( int i=0; i < count; i++ )
{
if( hi->hlModeName(i) == QString::fromLatin1("Perl") )
{
hi->setHlMode(i);
break;
}
}
}
void PerlScriptPrefsUI::slotCut()
{
cp->cut();
}
void PerlScriptPrefsUI::slotCopy()
{
cp->copy();
}
void PerlScriptPrefsUI::slotPaste()
{
cp->paste();
}
/*
* Sets the strings of the subwidgets using the current
* language.
*/
void PerlScriptPrefsUI::languageChange()
{
saveButton->setText( tr2i18n( "Save Changes" ) );
addButton->setText( tr2i18n( "Add Script" ) );
removeButton->setText( tr2i18n( "Remove Script" ) );
}
#include "perlscriptprefsbase.moc"
<commit_msg>make it compile.<commit_after>#include "perlscriptprefsbase.h"
#include <qhbox.h>
#include <qheader.h>
#include <qlayout.h>
#include <qtooltip.h>
#include <qvariant.h>
#include <qwhatsthis.h>
#include <kactioncollection.h>
#include <klibloader.h>
#include <klistview.h>
#include <klocale.h>
#include <kpushbutton.h>
#include <kstdaction.h>
#include <ktexteditor/clipboardinterface.h>
#include <ktexteditor/document.h>
#include <ktexteditor/highlightinginterface.h>
#include <ktexteditor/view.h>
#include <ktrader.h>
/*
* Constructs a PerlScriptPrefsUI as a child of 'parent', with the
* name 'name' and widget flags set to 'f'.
*/
PerlScriptPrefsUI::PerlScriptPrefsUI( QWidget* parent, const char* name, WFlags fl )
: QWidget( parent, name, fl )
{
if ( !name )
setName( "PerlScriptPrefsUI" );
QVBoxLayout *v = new QVBoxLayout( this, 4 );
scriptView = new KListView( this, "scriptView" );
scriptView->setAllColumnsShowFocus( true );
scriptView->addColumn( i18n("Name") );
scriptView->addColumn( i18n("Description") );
scriptView->addColumn( i18n("Path") );
scriptView->setMaximumHeight( 140 );
v->addWidget( scriptView );
QHBoxLayout *h = new QHBoxLayout( this, 4 );
h->insertStretch(0);
removeButton = new KPushButton( this, "removeButton" );
removeButton->setSizePolicy( QSizePolicy::Fixed, QSizePolicy::Fixed );
h->addWidget( removeButton );
addButton = new KPushButton( this, "addButton" );
addButton->setSizePolicy( QSizePolicy::Fixed, QSizePolicy::Fixed );
h->addWidget( addButton );
v->addLayout( h );
QHBox *f = new QHBox( this );
f->setFrameStyle( QFrame::WinPanel | QFrame::Sunken );
KTrader::OfferList offers = KTrader::self()->query( "KTextEditor/Document" );
KService::Ptr service = *offers.begin();
KLibFactory *factory = KLibLoader::self()->factory( service->library().latin1() );
editDocument = static_cast<KTextEditor::Document *>( factory->create( f, 0, "KTextEditor::Document" ) );
editArea = editDocument->createView( f, 0 );
setHighlight();
//v->addWidget( editArea );
v->addWidget( f );
cp = KTextEditor::clipboardInterface( editArea );
KActionCollection *coll = new KActionCollection(this);
KStdAction::cut( this, SLOT(slotCut()), coll);
KStdAction::copy( this, SLOT(slotCopy()), coll);
KStdAction::paste( this, SLOT(slotPaste()), coll);
QHBoxLayout *h2 = new QHBoxLayout( this, 4 );
h2->insertStretch(0);
saveButton = new KPushButton( this, "saveButton" );
saveButton->setSizePolicy( QSizePolicy::Fixed, QSizePolicy::Fixed );
h2->addWidget( saveButton );
v->addLayout(h2);
languageChange();
}
/*
* Destroys the object and frees any allocated resources
*/
PerlScriptPrefsUI::~PerlScriptPrefsUI()
{
// no need to delete child widgets, Qt does it all for us
}
void PerlScriptPrefsUI::setHighlight()
{
KTextEditor::HighlightingInterface *hi = KTextEditor::highlightingInterface( editDocument );
int count = hi->hlModeCount();
for( int i=0; i < count; i++ )
{
if( hi->hlModeName(i) == QString::fromLatin1("Perl") )
{
hi->setHlMode(i);
break;
}
}
}
void PerlScriptPrefsUI::slotCut()
{
cp->cut();
}
void PerlScriptPrefsUI::slotCopy()
{
cp->copy();
}
void PerlScriptPrefsUI::slotPaste()
{
cp->paste();
}
/*
* Sets the strings of the subwidgets using the current
* language.
*/
void PerlScriptPrefsUI::languageChange()
{
saveButton->setText( tr2i18n( "Save Changes" ) );
addButton->setText( tr2i18n( "Add Script" ) );
removeButton->setText( tr2i18n( "Remove Script" ) );
}
#include "perlscriptprefsbase.moc"
<|endoftext|> |
<commit_before>/* dtkPluginManager.cpp ---
*
* Author: Julien Wintz
* Copyright (C) 2008 - Julien Wintz, Inria.
* Created: Tue Aug 4 12:20:59 2009 (+0200)
* Version: $Id$
* Last-Updated: Thu May 3 11:01:55 2012 (+0200)
* By: Julien Wintz
* Update #: 248
*/
/* Commentary:
*
*/
/* Change log:
*
*/
#include "dtkPlugin.h"
#include "dtkPluginManager.h"
#include <dtkLog/dtkLog.h>
#define DTK_VERBOSE_LOAD false
// /////////////////////////////////////////////////////////////////
// Helper functions
// /////////////////////////////////////////////////////////////////
QStringList dtkPluginManagerPathSplitter(QString path)
{
QString paths = path;
#ifdef Q_WS_WIN
QStringList pathList;
QRegExp pathFilterRx("(([a-zA-Z]:|)[^:]+)");
int pos = 0;
while ((pos = pathFilterRx.indexIn(paths, pos)) != -1) {
QString pathItem = pathFilterRx.cap(1);
pathItem.replace( "\\" , "/" );
if (!pathItem.isEmpty())
pathList << pathItem;
pos += pathFilterRx.matchedLength();
}
#else
QStringList pathList = paths.split(":", QString::SkipEmptyParts);
#endif
return pathList;
}
// /////////////////////////////////////////////////////////////////
// dtkPluginManagerPrivate
// /////////////////////////////////////////////////////////////////
class dtkPluginManagerPrivate
{
public:
QString path;
QHash<QString, QPluginLoader *> loaders;
};
#include "dtkAbstractData.h"
#include <dtkMath/dtkVector3D.h>
#include <dtkMath/dtkQuaternion.h>
dtkPluginManager *dtkPluginManager::instance(void)
{
if(!s_instance) {
s_instance = new dtkPluginManager;
dtkTrace() << "dtkAbstractData has meta user type" << qRegisterMetaType<dtkAbstractData>("dtkAbstractData");
dtkTrace() << "dtkVector3DReal has meta user type" << qRegisterMetaType<dtkVector3DReal>("dtkVector3DReal");
dtkTrace() << "dtkQuaternionReal has meta user type" << qRegisterMetaType<dtkQuaternionReal>("dtkQuaternionReal");
}
return s_instance;
}
// /////////////////////////////////////////////////////////////////
// dtkPluginManager
// /////////////////////////////////////////////////////////////////
void dtkPluginManager::initialize(void)
{
if(d->path.isNull())
this->readSettings();
QStringList pathList = dtkPluginManagerPathSplitter(d->path);
const QString appDir = qApp->applicationDirPath();
foreach(QString path, pathList) {
QDir dir(appDir);
if (dir.cd(path)) {
dir.setFilter(QDir::AllEntries | QDir::NoDotAndDotDot);
foreach (QFileInfo entry, dir.entryInfoList())
loadPlugin(entry.absoluteFilePath());
} else {
dtkWarn() << "Failed to load plugins from path " << path << ". Could not cd to directory.";
}
}
}
void dtkPluginManager::uninitialize(void)
{
this->writeSettings();
foreach(QString path, d->loaders.keys())
unloadPlugin(path);
}
//! Load a specific plugin designated by its name.
/*! The path is retrieved through the plugin manager settings.
*
* \param name The name of the plugin, without platform specific prefix (.e.g lib) and suffix (e.g. .so or .dylib or .dll)
*/
void dtkPluginManager::load(const QString& name)
{
if(d->path.isNull())
this->readSettings();
QStringList pathList = dtkPluginManagerPathSplitter(d->path);
const QString appDir = qApp->applicationDirPath();
foreach(QString path, pathList) {
QDir dir(appDir);
if (dir.cd(path)) {
dir.setFilter(QDir::AllEntries | QDir::NoDotAndDotDot);
foreach (QFileInfo entry, dir.entryInfoList())
if(entry.fileName().contains(name))
loadPlugin(entry.absoluteFilePath());
} else {
dtkWarn() << "Failed to load plugins from path " << path << ". Could not cd to directory.";
}
}
}
//! Unload a specific plugin designated by its name.
/*! The path is retrieved through the plugin manager settings.
*
* \param name The name of the plugin, without platform specific prefix (.e.g lib) and suffix (e.g. .so or .dylib or .dll)
*/
void dtkPluginManager::unload(const QString& name)
{
if(d->path.isNull())
this->readSettings();
QStringList pathList = dtkPluginManagerPathSplitter(d->path);
const QString appDir = qApp->applicationDirPath();
foreach(QString path, pathList) {
QDir dir(appDir);
if (dir.cd(path)) {
dir.setFilter(QDir::AllEntries | QDir::NoDotAndDotDot);
foreach (QFileInfo entry, dir.entryInfoList())
if(entry.fileName().contains(name))
if (this->plugin(name))
this->unloadPlugin(entry.absoluteFilePath());
} else {
dtkWarn() << "Failed to load plugins from path " << path << ". Could not cd to directory.";
}
}
}
void dtkPluginManager::readSettings(void)
{
QSettings settings("inria", "dtk");
QString defaultPath;
QDir plugins_dir;
#ifdef Q_WS_MAC
plugins_dir = qApp->applicationDirPath() + "/../PlugIns";
#else
plugins_dir = qApp->applicationDirPath() + "/../plugins";
#endif
defaultPath = plugins_dir.absolutePath();
settings.beginGroup("plugins");
if (!settings.contains("path")) {
dtkDebug() << "Filling in empty path in settings with default path:" << defaultPath;
settings.setValue("path", defaultPath);
}
d->path = settings.value("path", defaultPath).toString();
settings.endGroup();
if(d->path.isEmpty()) {
dtkWarn() << "Your dtk config does not seem to be set correctly.";
dtkWarn() << "Please set plugins.path.";
}
}
void dtkPluginManager::writeSettings(void)
{
// QSettings settings("inria", "dtk");
// settings.beginGroup("plugins");
// settings.setValue("path", d->path);
// settings.endGroup();
}
void dtkPluginManager::printPlugins(void)
{
foreach(QString path, d->loaders.keys())
dtkTrace() << path;
}
dtkPlugin *dtkPluginManager::plugin(const QString& name)
{
foreach(QPluginLoader *loader, d->loaders) {
dtkPlugin *plugin = qobject_cast<dtkPlugin *>(loader->instance());
if(plugin->name() == name)
return plugin;
}
return NULL;
}
QList<dtkPlugin *> dtkPluginManager::plugins(void)
{
QList<dtkPlugin *> list;
foreach(QPluginLoader *loader, d->loaders)
list << qobject_cast<dtkPlugin *>(loader->instance());
return list;
}
void dtkPluginManager::setPath(const QString& path)
{
d->path = path;
}
QString dtkPluginManager::path(void) const
{
return d->path;
}
dtkPluginManager::dtkPluginManager(void) : d(new dtkPluginManagerPrivate)
{
}
dtkPluginManager::~dtkPluginManager(void)
{
delete d;
d = NULL;
}
/*!
\brief Loads the plugin from the given filename.
Derived classes may override to prevent certain plugins being loaded,
or provide additional functionality. In most cases they should still
call the base implementation (this).
\param path : Path to plugin file to be loaded.
*/
void dtkPluginManager::loadPlugin(const QString& path)
{
QPluginLoader *loader = new QPluginLoader(path);
loader->setLoadHints (QLibrary::ExportExternalSymbolsHint);
if(!loader->load()) {
QString error = "Unable to load ";
error += path;
error += " - ";
error += loader->errorString();
if (DTK_VERBOSE_LOAD) {
dtkDebug() << error;
}
emit loadError(error);
delete loader;
return;
}
dtkPlugin *plugin = qobject_cast<dtkPlugin *>(loader->instance());
if(!plugin) {
QString error = "Unable to retrieve ";
error += path;
if (DTK_VERBOSE_LOAD) {
dtkDebug() << error;
}
emit loadError(error);
return;
}
if(!plugin->initialize()) {
QString error = "Unable to initialize ";
error += plugin->name();
error += " plugin";
if (DTK_VERBOSE_LOAD) {
dtkTrace() << error;
}
emit loadError(error);
return;
}
d->loaders.insert(path, loader);
if (DTK_VERBOSE_LOAD) {
dtkTrace() << "Loaded plugin " << plugin->name() << " from " << path;
}
emit loaded(plugin->name());
}
//! Unloads the plugin previously loaded from the given filename.
/*! Derived classes may override to prevent certain plugins being
* unloaded, or provide additional functionality. In most
* cases they should still call the base implementation
* (this).
*
* \param path Path to plugin file to be unloaded.
*/
void dtkPluginManager::unloadPlugin(const QString& path)
{
dtkPlugin *plugin = qobject_cast<dtkPlugin *>(d->loaders.value(path)->instance());
if(!plugin) {
if (DTK_VERBOSE_LOAD) {
dtkDebug() << "dtkPluginManager - Unable to retrieve " << plugin->name() << " plugin";
}
return;
}
if(!plugin->uninitialize()) {
if (DTK_VERBOSE_LOAD) {
dtkTrace() << "Unable to uninitialize " << plugin->name() << " plugin";
}
return;
}
QPluginLoader *loader = d->loaders.value(path);
if(!loader->unload()) {
if (DTK_VERBOSE_LOAD) {
dtkDebug() << "dtkPluginManager - Unable to unload plugin: " << loader->errorString();
}
return;
}
delete loader;
d->loaders.remove(path);
// emit unloaded(plugin->name());
}
dtkPluginManager *dtkPluginManager::s_instance = NULL;
<commit_msg>Do not trace code that NEED to be executed.<commit_after>/* dtkPluginManager.cpp ---
*
* Author: Julien Wintz
* Copyright (C) 2008 - Julien Wintz, Inria.
* Created: Tue Aug 4 12:20:59 2009 (+0200)
* Version: $Id$
* Last-Updated: Thu May 3 14:10:25 2012 (+0200)
* By: Julien Wintz
* Update #: 249
*/
/* Commentary:
*
*/
/* Change log:
*
*/
#include "dtkPlugin.h"
#include "dtkPluginManager.h"
#include <dtkLog/dtkLog.h>
#define DTK_VERBOSE_LOAD false
// /////////////////////////////////////////////////////////////////
// Helper functions
// /////////////////////////////////////////////////////////////////
QStringList dtkPluginManagerPathSplitter(QString path)
{
QString paths = path;
#ifdef Q_WS_WIN
QStringList pathList;
QRegExp pathFilterRx("(([a-zA-Z]:|)[^:]+)");
int pos = 0;
while ((pos = pathFilterRx.indexIn(paths, pos)) != -1) {
QString pathItem = pathFilterRx.cap(1);
pathItem.replace( "\\" , "/" );
if (!pathItem.isEmpty())
pathList << pathItem;
pos += pathFilterRx.matchedLength();
}
#else
QStringList pathList = paths.split(":", QString::SkipEmptyParts);
#endif
return pathList;
}
// /////////////////////////////////////////////////////////////////
// dtkPluginManagerPrivate
// /////////////////////////////////////////////////////////////////
class dtkPluginManagerPrivate
{
public:
QString path;
QHash<QString, QPluginLoader *> loaders;
};
#include "dtkAbstractData.h"
#include <dtkMath/dtkVector3D.h>
#include <dtkMath/dtkQuaternion.h>
dtkPluginManager *dtkPluginManager::instance(void)
{
if(!s_instance) {
s_instance = new dtkPluginManager;
qRegisterMetaType<dtkAbstractData>("dtkAbstractData");
qRegisterMetaType<dtkVector3DReal>("dtkVector3DReal");
qRegisterMetaType<dtkQuaternionReal>("dtkQuaternionReal");
}
return s_instance;
}
// /////////////////////////////////////////////////////////////////
// dtkPluginManager
// /////////////////////////////////////////////////////////////////
void dtkPluginManager::initialize(void)
{
if(d->path.isNull())
this->readSettings();
QStringList pathList = dtkPluginManagerPathSplitter(d->path);
const QString appDir = qApp->applicationDirPath();
foreach(QString path, pathList) {
QDir dir(appDir);
if (dir.cd(path)) {
dir.setFilter(QDir::AllEntries | QDir::NoDotAndDotDot);
foreach (QFileInfo entry, dir.entryInfoList())
loadPlugin(entry.absoluteFilePath());
} else {
dtkWarn() << "Failed to load plugins from path " << path << ". Could not cd to directory.";
}
}
}
void dtkPluginManager::uninitialize(void)
{
this->writeSettings();
foreach(QString path, d->loaders.keys())
unloadPlugin(path);
}
//! Load a specific plugin designated by its name.
/*! The path is retrieved through the plugin manager settings.
*
* \param name The name of the plugin, without platform specific prefix (.e.g lib) and suffix (e.g. .so or .dylib or .dll)
*/
void dtkPluginManager::load(const QString& name)
{
if(d->path.isNull())
this->readSettings();
QStringList pathList = dtkPluginManagerPathSplitter(d->path);
const QString appDir = qApp->applicationDirPath();
foreach(QString path, pathList) {
QDir dir(appDir);
if (dir.cd(path)) {
dir.setFilter(QDir::AllEntries | QDir::NoDotAndDotDot);
foreach (QFileInfo entry, dir.entryInfoList())
if(entry.fileName().contains(name))
loadPlugin(entry.absoluteFilePath());
} else {
dtkWarn() << "Failed to load plugins from path " << path << ". Could not cd to directory.";
}
}
}
//! Unload a specific plugin designated by its name.
/*! The path is retrieved through the plugin manager settings.
*
* \param name The name of the plugin, without platform specific prefix (.e.g lib) and suffix (e.g. .so or .dylib or .dll)
*/
void dtkPluginManager::unload(const QString& name)
{
if(d->path.isNull())
this->readSettings();
QStringList pathList = dtkPluginManagerPathSplitter(d->path);
const QString appDir = qApp->applicationDirPath();
foreach(QString path, pathList) {
QDir dir(appDir);
if (dir.cd(path)) {
dir.setFilter(QDir::AllEntries | QDir::NoDotAndDotDot);
foreach (QFileInfo entry, dir.entryInfoList())
if(entry.fileName().contains(name))
if (this->plugin(name))
this->unloadPlugin(entry.absoluteFilePath());
} else {
dtkWarn() << "Failed to load plugins from path " << path << ". Could not cd to directory.";
}
}
}
void dtkPluginManager::readSettings(void)
{
QSettings settings("inria", "dtk");
QString defaultPath;
QDir plugins_dir;
#ifdef Q_WS_MAC
plugins_dir = qApp->applicationDirPath() + "/../PlugIns";
#else
plugins_dir = qApp->applicationDirPath() + "/../plugins";
#endif
defaultPath = plugins_dir.absolutePath();
settings.beginGroup("plugins");
if (!settings.contains("path")) {
dtkDebug() << "Filling in empty path in settings with default path:" << defaultPath;
settings.setValue("path", defaultPath);
}
d->path = settings.value("path", defaultPath).toString();
settings.endGroup();
if(d->path.isEmpty()) {
dtkWarn() << "Your dtk config does not seem to be set correctly.";
dtkWarn() << "Please set plugins.path.";
}
}
void dtkPluginManager::writeSettings(void)
{
// QSettings settings("inria", "dtk");
// settings.beginGroup("plugins");
// settings.setValue("path", d->path);
// settings.endGroup();
}
void dtkPluginManager::printPlugins(void)
{
foreach(QString path, d->loaders.keys())
dtkTrace() << path;
}
dtkPlugin *dtkPluginManager::plugin(const QString& name)
{
foreach(QPluginLoader *loader, d->loaders) {
dtkPlugin *plugin = qobject_cast<dtkPlugin *>(loader->instance());
if(plugin->name() == name)
return plugin;
}
return NULL;
}
QList<dtkPlugin *> dtkPluginManager::plugins(void)
{
QList<dtkPlugin *> list;
foreach(QPluginLoader *loader, d->loaders)
list << qobject_cast<dtkPlugin *>(loader->instance());
return list;
}
void dtkPluginManager::setPath(const QString& path)
{
d->path = path;
}
QString dtkPluginManager::path(void) const
{
return d->path;
}
dtkPluginManager::dtkPluginManager(void) : d(new dtkPluginManagerPrivate)
{
}
dtkPluginManager::~dtkPluginManager(void)
{
delete d;
d = NULL;
}
/*!
\brief Loads the plugin from the given filename.
Derived classes may override to prevent certain plugins being loaded,
or provide additional functionality. In most cases they should still
call the base implementation (this).
\param path : Path to plugin file to be loaded.
*/
void dtkPluginManager::loadPlugin(const QString& path)
{
QPluginLoader *loader = new QPluginLoader(path);
loader->setLoadHints (QLibrary::ExportExternalSymbolsHint);
if(!loader->load()) {
QString error = "Unable to load ";
error += path;
error += " - ";
error += loader->errorString();
if (DTK_VERBOSE_LOAD) {
dtkDebug() << error;
}
emit loadError(error);
delete loader;
return;
}
dtkPlugin *plugin = qobject_cast<dtkPlugin *>(loader->instance());
if(!plugin) {
QString error = "Unable to retrieve ";
error += path;
if (DTK_VERBOSE_LOAD) {
dtkDebug() << error;
}
emit loadError(error);
return;
}
if(!plugin->initialize()) {
QString error = "Unable to initialize ";
error += plugin->name();
error += " plugin";
if (DTK_VERBOSE_LOAD) {
dtkTrace() << error;
}
emit loadError(error);
return;
}
d->loaders.insert(path, loader);
if (DTK_VERBOSE_LOAD) {
dtkTrace() << "Loaded plugin " << plugin->name() << " from " << path;
}
emit loaded(plugin->name());
}
//! Unloads the plugin previously loaded from the given filename.
/*! Derived classes may override to prevent certain plugins being
* unloaded, or provide additional functionality. In most
* cases they should still call the base implementation
* (this).
*
* \param path Path to plugin file to be unloaded.
*/
void dtkPluginManager::unloadPlugin(const QString& path)
{
dtkPlugin *plugin = qobject_cast<dtkPlugin *>(d->loaders.value(path)->instance());
if(!plugin) {
if (DTK_VERBOSE_LOAD) {
dtkDebug() << "dtkPluginManager - Unable to retrieve " << plugin->name() << " plugin";
}
return;
}
if(!plugin->uninitialize()) {
if (DTK_VERBOSE_LOAD) {
dtkTrace() << "Unable to uninitialize " << plugin->name() << " plugin";
}
return;
}
QPluginLoader *loader = d->loaders.value(path);
if(!loader->unload()) {
if (DTK_VERBOSE_LOAD) {
dtkDebug() << "dtkPluginManager - Unable to unload plugin: " << loader->errorString();
}
return;
}
delete loader;
d->loaders.remove(path);
// emit unloaded(plugin->name());
}
dtkPluginManager *dtkPluginManager::s_instance = NULL;
<|endoftext|> |
<commit_before>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 2003 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* $Log$
* Revision 1.7 2003/12/15 19:04:55 neilg
* fix segfault when a writeAnnotation() method was called
*
* Revision 1.6 2003/11/27 21:29:05 neilg
* implement writeAnnotation; thanks to Dave Cargill
*
* Revision 1.5 2003/11/14 22:47:53 neilg
* fix bogus log message from previous commit...
*
* Revision 1.4 2003/11/14 22:33:30 neilg
* Second phase of schema component model implementation.
* Implement XSModel, XSNamespaceItem, and the plumbing necessary
* to connect them to the other components.
* Thanks to David Cargill.
*
* Revision 1.3 2003/11/11 22:48:13 knoaman
* Serialization of XSAnnotation.
*
* Revision 1.2 2003/11/06 19:28:11 knoaman
* PSVI support for annotations.
*
* Revision 1.1 2003/09/16 14:33:36 neilg
* PSVI/schema component model classes, with Makefile/configuration changes necessary to build them
*
*/
#include <xercesc/framework/psvi/XSAnnotation.hpp>
#include <xercesc/util/XMLString.hpp>
#include <xercesc/framework/MemBufInputSource.hpp>
#include <xercesc/sax2/SAX2XMLReader.hpp>
#include <xercesc/sax2/XMLReaderFactory.hpp>
#include <xercesc/parsers/XercesDOMParser.hpp>
#include <xercesc/dom/DOMElement.hpp>
XERCES_CPP_NAMESPACE_BEGIN
XSAnnotation::XSAnnotation(const XMLCh* const content,
MemoryManager * const manager):
XSObject(XSConstants::ANNOTATION, 0, manager)
, fContents(XMLString::replicate(content, manager))
, fNext(0)
{
}
XSAnnotation::XSAnnotation(MemoryManager * const manager):
XSObject(XSConstants::ANNOTATION, 0, manager)
, fContents(0)
, fNext(0)
{
}
XSAnnotation::~XSAnnotation()
{
fMemoryManager->deallocate(fContents);
if (fNext)
delete fNext;
}
// XSAnnotation methods
void XSAnnotation::writeAnnotation(DOMNode* node, ANNOTATION_TARGET targetType)
{
XercesDOMParser *parser = new (fMemoryManager) XercesDOMParser(0, fMemoryManager);
parser->setDoNamespaces(true);
parser->setValidationScheme(XercesDOMParser::Val_Never);
DOMDocument* futureOwner = (targetType == W3C_DOM_ELEMENT) ?
((DOMElement*)node)->getOwnerDocument() :
(DOMDocument*)node;
MemBufInputSource* memBufIS = new (fMemoryManager) MemBufInputSource
(
(const XMLByte*)fContents
, XMLString::stringLen(fContents)*sizeof(XMLCh)
, ""
, false
, fMemoryManager
);
memBufIS->setEncoding(XMLUni::fgXMLChEncodingString);
try
{
parser->parse(*memBufIS);
}
catch (const XMLException&)
{
throw;
}
DOMNode* newElem = futureOwner->importNode((parser->getDocument())->getDocumentElement(), true);
node->insertBefore(newElem, node->getFirstChild());
delete parser;
delete memBufIS;
}
void XSAnnotation::writeAnnotation(ContentHandler* handler)
{
SAX2XMLReader* parser = XMLReaderFactory::createXMLReader(fMemoryManager);
parser->setFeature(XMLUni::fgSAX2CoreNameSpaces, true);
parser->setFeature(XMLUni::fgSAX2CoreValidation, false);
parser->setContentHandler(handler);
MemBufInputSource* memBufIS = new (fMemoryManager) MemBufInputSource
(
(const XMLByte*)fContents
, XMLString::stringLen(fContents)*sizeof(XMLCh)
, ""
, false
, fMemoryManager
);
memBufIS->setEncoding(XMLUni::fgXMLChEncodingString);
try
{
parser->parse(*memBufIS);
}
catch (const XMLException&)
{
}
delete parser;
delete memBufIS;
}
void XSAnnotation::setNext(XSAnnotation* const nextAnnotation)
{
if (fNext)
fNext->setNext(nextAnnotation);
else
fNext = nextAnnotation;
}
XSAnnotation* XSAnnotation::getNext()
{
return fNext;
}
/***
* Support for Serialization/De-serialization
***/
IMPL_XSERIALIZABLE_TOCREATE(XSAnnotation)
void XSAnnotation::serialize(XSerializeEngine& serEng)
{
/***
* Since we are pretty sure that fIdMap and fHashTable is
* not shared by any other object, therefore there is no owned/referenced
* issue. Thus we can serialize the raw data only, rather than serializing
* both fIdMap and fHashTable.
*
* And we can rebuild the fIdMap and fHashTable out of the raw data during
* deserialization.
*
***/
if (serEng.isStoring())
{
serEng.writeString(fContents);
serEng<<fNext;
}
else
{
serEng.readString(fContents);
serEng>>fNext;
}
}
XERCES_CPP_NAMESPACE_END
<commit_msg>remove a throw clause inserted during debugging (but should we really swallow this exception?)<commit_after>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 2003 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* $Log$
* Revision 1.8 2003/12/19 07:18:56 neilg
* remove a throw clause inserted during debugging (but should we really swallow this exception?)
*
* Revision 1.7 2003/12/15 19:04:55 neilg
* fix segfault when a writeAnnotation() method was called
*
* Revision 1.6 2003/11/27 21:29:05 neilg
* implement writeAnnotation; thanks to Dave Cargill
*
* Revision 1.5 2003/11/14 22:47:53 neilg
* fix bogus log message from previous commit...
*
* Revision 1.4 2003/11/14 22:33:30 neilg
* Second phase of schema component model implementation.
* Implement XSModel, XSNamespaceItem, and the plumbing necessary
* to connect them to the other components.
* Thanks to David Cargill.
*
* Revision 1.3 2003/11/11 22:48:13 knoaman
* Serialization of XSAnnotation.
*
* Revision 1.2 2003/11/06 19:28:11 knoaman
* PSVI support for annotations.
*
* Revision 1.1 2003/09/16 14:33:36 neilg
* PSVI/schema component model classes, with Makefile/configuration changes necessary to build them
*
*/
#include <xercesc/framework/psvi/XSAnnotation.hpp>
#include <xercesc/util/XMLString.hpp>
#include <xercesc/framework/MemBufInputSource.hpp>
#include <xercesc/sax2/SAX2XMLReader.hpp>
#include <xercesc/sax2/XMLReaderFactory.hpp>
#include <xercesc/parsers/XercesDOMParser.hpp>
#include <xercesc/dom/DOMElement.hpp>
XERCES_CPP_NAMESPACE_BEGIN
XSAnnotation::XSAnnotation(const XMLCh* const content,
MemoryManager * const manager):
XSObject(XSConstants::ANNOTATION, 0, manager)
, fContents(XMLString::replicate(content, manager))
, fNext(0)
{
}
XSAnnotation::XSAnnotation(MemoryManager * const manager):
XSObject(XSConstants::ANNOTATION, 0, manager)
, fContents(0)
, fNext(0)
{
}
XSAnnotation::~XSAnnotation()
{
fMemoryManager->deallocate(fContents);
if (fNext)
delete fNext;
}
// XSAnnotation methods
void XSAnnotation::writeAnnotation(DOMNode* node, ANNOTATION_TARGET targetType)
{
XercesDOMParser *parser = new (fMemoryManager) XercesDOMParser(0, fMemoryManager);
parser->setDoNamespaces(true);
parser->setValidationScheme(XercesDOMParser::Val_Never);
DOMDocument* futureOwner = (targetType == W3C_DOM_ELEMENT) ?
((DOMElement*)node)->getOwnerDocument() :
(DOMDocument*)node;
MemBufInputSource* memBufIS = new (fMemoryManager) MemBufInputSource
(
(const XMLByte*)fContents
, XMLString::stringLen(fContents)*sizeof(XMLCh)
, ""
, false
, fMemoryManager
);
memBufIS->setEncoding(XMLUni::fgXMLChEncodingString);
try
{
parser->parse(*memBufIS);
}
catch (const XMLException&)
{
// REVISIT: should we really eat this?
}
DOMNode* newElem = futureOwner->importNode((parser->getDocument())->getDocumentElement(), true);
node->insertBefore(newElem, node->getFirstChild());
delete parser;
delete memBufIS;
}
void XSAnnotation::writeAnnotation(ContentHandler* handler)
{
SAX2XMLReader* parser = XMLReaderFactory::createXMLReader(fMemoryManager);
parser->setFeature(XMLUni::fgSAX2CoreNameSpaces, true);
parser->setFeature(XMLUni::fgSAX2CoreValidation, false);
parser->setContentHandler(handler);
MemBufInputSource* memBufIS = new (fMemoryManager) MemBufInputSource
(
(const XMLByte*)fContents
, XMLString::stringLen(fContents)*sizeof(XMLCh)
, ""
, false
, fMemoryManager
);
memBufIS->setEncoding(XMLUni::fgXMLChEncodingString);
try
{
parser->parse(*memBufIS);
}
catch (const XMLException&)
{
}
delete parser;
delete memBufIS;
}
void XSAnnotation::setNext(XSAnnotation* const nextAnnotation)
{
if (fNext)
fNext->setNext(nextAnnotation);
else
fNext = nextAnnotation;
}
XSAnnotation* XSAnnotation::getNext()
{
return fNext;
}
/***
* Support for Serialization/De-serialization
***/
IMPL_XSERIALIZABLE_TOCREATE(XSAnnotation)
void XSAnnotation::serialize(XSerializeEngine& serEng)
{
/***
* Since we are pretty sure that fIdMap and fHashTable is
* not shared by any other object, therefore there is no owned/referenced
* issue. Thus we can serialize the raw data only, rather than serializing
* both fIdMap and fHashTable.
*
* And we can rebuild the fIdMap and fHashTable out of the raw data during
* deserialization.
*
***/
if (serEng.isStoring())
{
serEng.writeString(fContents);
serEng<<fNext;
}
else
{
serEng.readString(fContents);
serEng>>fNext;
}
}
XERCES_CPP_NAMESPACE_END
<|endoftext|> |
<commit_before># include <stdio.h>
# include <string.h>
# include <stdlib.h>
# include <ctype.h>
# include <limits.h>
# include <time.h>
# include <assert.h>
#include <algorithm>
#include <omp.h>
#include "SpMP/COO.hpp"
#include "SpMP/mm_io.h"
#include "SpMP/Vector.hpp"
using namespace std;
using namespace SpMP;
COO coo;
extern "C" {
// The following two functions are for Julia
void load_matrix_market_step1(char *file, int *sizes, bool force_symmetric /*=false*/, bool transpose /*=false*/)
{
if (transpose) {
loadMatrixMarketTransposed(file, coo);
}
else {
loadMatrixMarket(file, coo, force_symmetric);
}
sizes[0] = (int)coo.isSymmetric;
sizes[1] = coo.m;
sizes[2] = coo.n;
sizes[3] = coo.nnz;
}
#define T double
void load_matrix_market_step2(
char *file, int *rowptr, int *colidx, T *values, int *sizes, bool one_based_CSR)
{
int m = sizes[1];
int n = sizes[2];
int nnz = sizes[3];
dcoo2csr(m, nnz, rowptr, colidx, values, coo.rowidx, coo.colidx, coo.values);
if (one_based_CSR) {
CSR csr;
csr.m = m;
csr.n = n;
csr.rowptr = rowptr;
csr.colidx = colidx;
csr.values = values;
csr.make1BasedIndexing();
}
}
void load_matrix_market(
char *file,
int **rowptr, int **colidx, T **values,
int *is_symmetric, int *m, int *n, int *nnz,
bool one_based_CSR /*=false*/, bool force_symmetric /*=false*/)
{
// Read into a COO array (stored statically insded mm_read)
int sizes[] = {0, 0, 0, 0};
load_matrix_market_step1(file, sizes, force_symmetric, false /*no transpose*/);
*is_symmetric = sizes[0];
*m = sizes[1];
*n = sizes[2];
*nnz = sizes[3];
// Allocate space for the CSR array
*rowptr = (int *)_mm_malloc(sizeof(int)*(*m+1), 64);
*colidx = (int *)_mm_malloc(sizeof(int)*(*nnz), 64);
*values = (T *)_mm_malloc(sizeof(T)*(*nnz), 64);
// Convert COO to CSR
load_matrix_market_step2(file, *rowptr, *colidx, *values, sizes, one_based_CSR);
}
void load_vector_matrix_market(const char *fileName, double **v, int *m, int *n)
{
SpMP::loadVectorMatrixMarket(fileName, v, m, n);
}
} // extern "C"
<commit_msg>add store_matrix_market<commit_after># include <stdio.h>
# include <string.h>
# include <stdlib.h>
# include <ctype.h>
# include <limits.h>
# include <time.h>
# include <assert.h>
#include <algorithm>
#include <omp.h>
#include "SpMP/COO.hpp"
#include "SpMP/mm_io.h"
#include "SpMP/Vector.hpp"
using namespace std;
using namespace SpMP;
COO coo;
extern "C" {
// The following two functions are for Julia
void load_matrix_market_step1(char *file, int *sizes, bool force_symmetric /*=false*/, bool transpose /*=false*/)
{
if (transpose) {
loadMatrixMarketTransposed(file, coo);
}
else {
loadMatrixMarket(file, coo, force_symmetric);
}
sizes[0] = (int)coo.isSymmetric;
sizes[1] = coo.m;
sizes[2] = coo.n;
sizes[3] = coo.nnz;
}
#define T double
void load_matrix_market_step2(
char *file, int *rowptr, int *colidx, T *values, int *sizes, bool one_based_CSR)
{
int m = sizes[1];
int n = sizes[2];
int nnz = sizes[3];
dcoo2csr(m, nnz, rowptr, colidx, values, coo.rowidx, coo.colidx, coo.values);
if (one_based_CSR) {
CSR csr;
csr.m = m;
csr.n = n;
csr.rowptr = rowptr;
csr.colidx = colidx;
csr.values = values;
csr.make1BasedIndexing();
}
}
void load_matrix_market(
char *file,
int **rowptr, int **colidx, T **values,
int *is_symmetric, int *m, int *n, int *nnz,
bool one_based_CSR /*=false*/, bool force_symmetric /*=false*/)
{
// Read into a COO array (stored statically insded mm_read)
int sizes[] = {0, 0, 0, 0};
load_matrix_market_step1(file, sizes, force_symmetric, false /*no transpose*/);
*is_symmetric = sizes[0];
*m = sizes[1];
*n = sizes[2];
*nnz = sizes[3];
// Allocate space for the CSR array
*rowptr = (int *)_mm_malloc(sizeof(int)*(*m+1), 64);
*colidx = (int *)_mm_malloc(sizeof(int)*(*nnz), 64);
*values = (T *)_mm_malloc(sizeof(T)*(*nnz), 64);
// Convert COO to CSR
load_matrix_market_step2(file, *rowptr, *colidx, *values, sizes, one_based_CSR);
}
void load_vector_matrix_market(const char *fileName, double **v, int *m, int *n)
{
SpMP::loadVectorMatrixMarket(fileName, v, m, n);
}
void store_matrix_market(char *file, int m, int n, int *colptr, int *rowval, double *nzval)
{
CSR A(m, n, colptr, rowval, nzval);
A.storeMatrixMarket(file);
}
} // extern "C"
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkChart.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkChart.h"
#include "vtkAxis.h"
#include "vtkBrush.h"
#include "vtkTransform2D.h"
#include "vtkContextMouseEvent.h"
#include "vtkAnnotationLink.h"
#include "vtkContextScene.h"
#include "vtkTextProperty.h"
#include "vtkObjectFactory.h"
//-----------------------------------------------------------------------------
vtkChart::MouseActions::MouseActions()
{
this->Data[0] = vtkContextMouseEvent::LEFT_BUTTON;
this->Data[1] = vtkContextMouseEvent::MIDDLE_BUTTON;
this->Data[2] = vtkContextMouseEvent::RIGHT_BUTTON;
}
//-----------------------------------------------------------------------------
vtkChart::MouseClickActions::MouseClickActions()
{
this->Data[0] = vtkContextMouseEvent::LEFT_BUTTON;
this->Data[1] = vtkContextMouseEvent::RIGHT_BUTTON;
}
//-----------------------------------------------------------------------------
vtkCxxSetObjectMacro(vtkChart, AnnotationLink, vtkAnnotationLink);
//-----------------------------------------------------------------------------
vtkChart::vtkChart()
{
this->Geometry[0] = 0;
this->Geometry[1] = 0;
this->Point1[0] = 0;
this->Point1[1] = 0;
this->Point2[0] = 0;
this->Point2[1] = 0;
this->Size.Set(0, 0, 0, 0);
this->ShowLegend = false;
this->TitleProperties = vtkTextProperty::New();
this->TitleProperties->SetJustificationToCentered();
this->TitleProperties->SetColor(0.0, 0.0, 0.0);
this->TitleProperties->SetFontSize(12);
this->TitleProperties->SetFontFamilyToArial();
this->AnnotationLink = NULL;
this->LayoutStrategy = vtkChart::FILL_SCENE;
this->RenderEmpty = false;
this->BackgroundBrush = vtkSmartPointer<vtkBrush>::New();
this->BackgroundBrush->SetColorF(1, 1, 1, 0);
this->SelectionMode = vtkContextScene::SELECTION_NONE;
}
//-----------------------------------------------------------------------------
vtkChart::~vtkChart()
{
for(int i=0; i < 4; i++)
{
if(this->GetAxis(i))
{
this->GetAxis(i)->RemoveObservers(vtkChart::UpdateRange);
}
}
this->TitleProperties->Delete();
if (this->AnnotationLink)
{
this->AnnotationLink->Delete();
}
}
//-----------------------------------------------------------------------------
vtkPlot * vtkChart::AddPlot(int)
{
return NULL;
}
//-----------------------------------------------------------------------------
vtkIdType vtkChart::AddPlot(vtkPlot*)
{
return -1;
}
//-----------------------------------------------------------------------------
bool vtkChart::RemovePlot(vtkIdType)
{
return false;
}
//-----------------------------------------------------------------------------
bool vtkChart::RemovePlotInstance(vtkPlot* plot)
{
if (plot)
{
vtkIdType numberOfPlots = this->GetNumberOfPlots();
for (vtkIdType i = 0; i < numberOfPlots; ++i)
{
if (this->GetPlot(i) == plot)
{
return this->RemovePlot(i);
}
}
}
return false;
}
//-----------------------------------------------------------------------------
void vtkChart::ClearPlots()
{
}
//-----------------------------------------------------------------------------
vtkPlot* vtkChart::GetPlot(vtkIdType)
{
return NULL;
}
//-----------------------------------------------------------------------------
vtkIdType vtkChart::GetNumberOfPlots()
{
return 0;
}
//-----------------------------------------------------------------------------
vtkAxis* vtkChart::GetAxis(int)
{
return NULL;
}
//-----------------------------------------------------------------------------
vtkIdType vtkChart::GetNumberOfAxes()
{
return 0;
}
//-----------------------------------------------------------------------------
void vtkChart::RecalculateBounds()
{
return;
}
//-----------------------------------------------------------------------------
void vtkChart::SetShowLegend(bool visible)
{
if (this->ShowLegend != visible)
{
this->ShowLegend = visible;
this->Modified();
}
}
//-----------------------------------------------------------------------------
bool vtkChart::GetShowLegend()
{
return this->ShowLegend;
}
vtkChartLegend * vtkChart::GetLegend()
{
return 0;
}
//-----------------------------------------------------------------------------
void vtkChart::SetTitle(const vtkStdString &title)
{
if (this->Title != title)
{
this->Title = title;
this->Modified();
}
}
//-----------------------------------------------------------------------------
vtkStdString vtkChart::GetTitle()
{
return this->Title;
}
//-----------------------------------------------------------------------------
bool vtkChart::CalculatePlotTransform(vtkAxis *x, vtkAxis *y,
vtkTransform2D *transform)
{
if (!x || !y || !transform)
{
vtkWarningMacro("Called with null arguments.");
return false;
}
// Get the scale for the plot area from the x and y axes
float *min = x->GetPoint1();
float *max = x->GetPoint2();
if (fabs(max[0] - min[0]) == 0.0f)
{
return false;
}
float xScale = (x->GetMaximum() - x->GetMinimum()) / (max[0] - min[0]);
// Now the y axis
min = y->GetPoint1();
max = y->GetPoint2();
if (fabs(max[1] - min[1]) == 0.0f)
{
return false;
}
float yScale = (y->GetMaximum() - y->GetMinimum()) / (max[1] - min[1]);
transform->Identity();
transform->Translate(this->Point1[0], this->Point1[1]);
// Get the scale for the plot area from the x and y axes
transform->Scale(1.0 / xScale, 1.0 / yScale);
transform->Translate(-x->GetMinimum(), -y->GetMinimum());
return true;
}
//-----------------------------------------------------------------------------
void vtkChart::SetBottomBorder(int border)
{
this->Point1[1] = border >= 0 ? border : 0;
this->Point1[1] += static_cast<int>(this->Size.Y());
}
//-----------------------------------------------------------------------------
void vtkChart::SetTopBorder(int border)
{
this->Point2[1] = border >=0 ?
this->Geometry[1] - border :
this->Geometry[1];
this->Point2[1] += static_cast<int>(this->Size.Y());
}
//-----------------------------------------------------------------------------
void vtkChart::SetLeftBorder(int border)
{
this->Point1[0] = border >= 0 ? border : 0;
this->Point1[0] += static_cast<int>(this->Size.X());
}
//-----------------------------------------------------------------------------
void vtkChart::SetRightBorder(int border)
{
this->Point2[0] = border >=0 ?
this->Geometry[0] - border :
this->Geometry[0];
this->Point2[0] += static_cast<int>(this->Size.X());
}
//-----------------------------------------------------------------------------
void vtkChart::SetBorders(int left, int bottom, int right, int top)
{
this->SetLeftBorder(left);
this->SetRightBorder(right);
this->SetTopBorder(top);
this->SetBottomBorder(bottom);
}
void vtkChart::SetSize(const vtkRectf &rect)
{
this->Size = rect;
this->Geometry[0] = static_cast<int>(rect.Width());
this->Geometry[1] = static_cast<int>(rect.Height());
}
vtkRectf vtkChart::GetSize()
{
return this->Size;
}
void vtkChart::SetActionToButton(int action, int button)
{
if (action < -1 || action >= MouseActions::MaxAction)
{
vtkErrorMacro("Error, invalid action value supplied: " << action)
return;
}
this->Actions[action] = button;
for (int i = 0; i < MouseActions::MaxAction; ++i)
{
if (this->Actions[i] == button && i != action)
{
this->Actions[i] = -1;
}
}
}
int vtkChart::GetActionToButton(int action)
{
return this->Actions[action];
}
void vtkChart::SetClickActionToButton(int action, int button)
{
if (action < vtkChart::SELECT || action > vtkChart::NOTIFY)
{
vtkErrorMacro("Error, invalid action value supplied: " << action)
return;
}
this->Actions[action - 2] = button;
}
int vtkChart::GetClickActionToButton(int action)
{
return this->Actions[action - 2];
}
//-----------------------------------------------------------------------------
void vtkChart::SetBackgroundBrush(vtkBrush *brush)
{
if(brush == NULL)
{
// set to transparent white if brush is null
this->BackgroundBrush->SetColorF(1, 1, 1, 0);
}
else
{
this->BackgroundBrush = brush;
}
this->Modified();
}
//-----------------------------------------------------------------------------
vtkBrush* vtkChart::GetBackgroundBrush()
{
return this->BackgroundBrush.GetPointer();
}
//-----------------------------------------------------------------------------
void vtkChart::PrintSelf(ostream &os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
// Print out the chart's geometry if it has been set
os << indent << "Point1: " << this->Point1[0] << "\t" << this->Point1[1]
<< endl;
os << indent << "Point2: " << this->Point2[0] << "\t" << this->Point2[1]
<< endl;
os << indent << "Width: " << this->Geometry[0] << endl
<< indent << "Height: " << this->Geometry[1] << endl;
os << indent << "SelectionMode: " << this->SelectionMode << endl;
}
//-----------------------------------------------------------------------------
void vtkChart::AttachAxisRangeListener(vtkAxis* axis)
{
axis->AddObserver(vtkChart::UpdateRange, this, &vtkChart::AxisRangeForwarderCallback);
}
//-----------------------------------------------------------------------------
void vtkChart::AxisRangeForwarderCallback(vtkObject*, unsigned long, void*)
{
double fullAxisRange[8];
for(int i=0; i < 4; i++)
{
this->GetAxis(i)->GetRange(&fullAxisRange[i*2]);
}
this->InvokeEvent(vtkChart::UpdateRange, fullAxisRange);
}
//-----------------------------------------------------------------------------
void vtkChart::SetSelectionMode(int selMode)
{
if (this->SelectionMode == selMode ||
selMode < vtkContextScene::SELECTION_NONE ||
selMode > vtkContextScene::SELECTION_TOGGLE)
{
return;
}
this->SelectionMode = selMode;
if(this->SelectionMode == vtkContextScene::SELECTION_NONE)
{
this->SetActionToButton(vtkChart::PAN, vtkContextMouseEvent::LEFT_BUTTON);
this->SetActionToButton(vtkChart::SELECT, vtkContextMouseEvent::RIGHT_BUTTON);
}
else
{
this->SetActionToButton(vtkChart::SELECT, vtkContextMouseEvent::LEFT_BUTTON);
}
this->Modified();
}
<commit_msg>Initialize the polygon selection to NO_BUTTON<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkChart.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkChart.h"
#include "vtkAxis.h"
#include "vtkBrush.h"
#include "vtkTransform2D.h"
#include "vtkContextMouseEvent.h"
#include "vtkAnnotationLink.h"
#include "vtkContextScene.h"
#include "vtkTextProperty.h"
#include "vtkObjectFactory.h"
//-----------------------------------------------------------------------------
vtkChart::MouseActions::MouseActions()
{
this->Data[0] = vtkContextMouseEvent::LEFT_BUTTON;
this->Data[1] = vtkContextMouseEvent::MIDDLE_BUTTON;
this->Data[2] = vtkContextMouseEvent::RIGHT_BUTTON;
this->Data[3] = vtkContextMouseEvent::NO_BUTTON;
}
//-----------------------------------------------------------------------------
vtkChart::MouseClickActions::MouseClickActions()
{
this->Data[0] = vtkContextMouseEvent::LEFT_BUTTON;
this->Data[1] = vtkContextMouseEvent::RIGHT_BUTTON;
}
//-----------------------------------------------------------------------------
vtkCxxSetObjectMacro(vtkChart, AnnotationLink, vtkAnnotationLink);
//-----------------------------------------------------------------------------
vtkChart::vtkChart()
{
this->Geometry[0] = 0;
this->Geometry[1] = 0;
this->Point1[0] = 0;
this->Point1[1] = 0;
this->Point2[0] = 0;
this->Point2[1] = 0;
this->Size.Set(0, 0, 0, 0);
this->ShowLegend = false;
this->TitleProperties = vtkTextProperty::New();
this->TitleProperties->SetJustificationToCentered();
this->TitleProperties->SetColor(0.0, 0.0, 0.0);
this->TitleProperties->SetFontSize(12);
this->TitleProperties->SetFontFamilyToArial();
this->AnnotationLink = NULL;
this->LayoutStrategy = vtkChart::FILL_SCENE;
this->RenderEmpty = false;
this->BackgroundBrush = vtkSmartPointer<vtkBrush>::New();
this->BackgroundBrush->SetColorF(1, 1, 1, 0);
this->SelectionMode = vtkContextScene::SELECTION_NONE;
}
//-----------------------------------------------------------------------------
vtkChart::~vtkChart()
{
for(int i=0; i < 4; i++)
{
if(this->GetAxis(i))
{
this->GetAxis(i)->RemoveObservers(vtkChart::UpdateRange);
}
}
this->TitleProperties->Delete();
if (this->AnnotationLink)
{
this->AnnotationLink->Delete();
}
}
//-----------------------------------------------------------------------------
vtkPlot * vtkChart::AddPlot(int)
{
return NULL;
}
//-----------------------------------------------------------------------------
vtkIdType vtkChart::AddPlot(vtkPlot*)
{
return -1;
}
//-----------------------------------------------------------------------------
bool vtkChart::RemovePlot(vtkIdType)
{
return false;
}
//-----------------------------------------------------------------------------
bool vtkChart::RemovePlotInstance(vtkPlot* plot)
{
if (plot)
{
vtkIdType numberOfPlots = this->GetNumberOfPlots();
for (vtkIdType i = 0; i < numberOfPlots; ++i)
{
if (this->GetPlot(i) == plot)
{
return this->RemovePlot(i);
}
}
}
return false;
}
//-----------------------------------------------------------------------------
void vtkChart::ClearPlots()
{
}
//-----------------------------------------------------------------------------
vtkPlot* vtkChart::GetPlot(vtkIdType)
{
return NULL;
}
//-----------------------------------------------------------------------------
vtkIdType vtkChart::GetNumberOfPlots()
{
return 0;
}
//-----------------------------------------------------------------------------
vtkAxis* vtkChart::GetAxis(int)
{
return NULL;
}
//-----------------------------------------------------------------------------
vtkIdType vtkChart::GetNumberOfAxes()
{
return 0;
}
//-----------------------------------------------------------------------------
void vtkChart::RecalculateBounds()
{
return;
}
//-----------------------------------------------------------------------------
void vtkChart::SetShowLegend(bool visible)
{
if (this->ShowLegend != visible)
{
this->ShowLegend = visible;
this->Modified();
}
}
//-----------------------------------------------------------------------------
bool vtkChart::GetShowLegend()
{
return this->ShowLegend;
}
vtkChartLegend * vtkChart::GetLegend()
{
return 0;
}
//-----------------------------------------------------------------------------
void vtkChart::SetTitle(const vtkStdString &title)
{
if (this->Title != title)
{
this->Title = title;
this->Modified();
}
}
//-----------------------------------------------------------------------------
vtkStdString vtkChart::GetTitle()
{
return this->Title;
}
//-----------------------------------------------------------------------------
bool vtkChart::CalculatePlotTransform(vtkAxis *x, vtkAxis *y,
vtkTransform2D *transform)
{
if (!x || !y || !transform)
{
vtkWarningMacro("Called with null arguments.");
return false;
}
// Get the scale for the plot area from the x and y axes
float *min = x->GetPoint1();
float *max = x->GetPoint2();
if (fabs(max[0] - min[0]) == 0.0f)
{
return false;
}
float xScale = (x->GetMaximum() - x->GetMinimum()) / (max[0] - min[0]);
// Now the y axis
min = y->GetPoint1();
max = y->GetPoint2();
if (fabs(max[1] - min[1]) == 0.0f)
{
return false;
}
float yScale = (y->GetMaximum() - y->GetMinimum()) / (max[1] - min[1]);
transform->Identity();
transform->Translate(this->Point1[0], this->Point1[1]);
// Get the scale for the plot area from the x and y axes
transform->Scale(1.0 / xScale, 1.0 / yScale);
transform->Translate(-x->GetMinimum(), -y->GetMinimum());
return true;
}
//-----------------------------------------------------------------------------
void vtkChart::SetBottomBorder(int border)
{
this->Point1[1] = border >= 0 ? border : 0;
this->Point1[1] += static_cast<int>(this->Size.Y());
}
//-----------------------------------------------------------------------------
void vtkChart::SetTopBorder(int border)
{
this->Point2[1] = border >=0 ?
this->Geometry[1] - border :
this->Geometry[1];
this->Point2[1] += static_cast<int>(this->Size.Y());
}
//-----------------------------------------------------------------------------
void vtkChart::SetLeftBorder(int border)
{
this->Point1[0] = border >= 0 ? border : 0;
this->Point1[0] += static_cast<int>(this->Size.X());
}
//-----------------------------------------------------------------------------
void vtkChart::SetRightBorder(int border)
{
this->Point2[0] = border >=0 ?
this->Geometry[0] - border :
this->Geometry[0];
this->Point2[0] += static_cast<int>(this->Size.X());
}
//-----------------------------------------------------------------------------
void vtkChart::SetBorders(int left, int bottom, int right, int top)
{
this->SetLeftBorder(left);
this->SetRightBorder(right);
this->SetTopBorder(top);
this->SetBottomBorder(bottom);
}
void vtkChart::SetSize(const vtkRectf &rect)
{
this->Size = rect;
this->Geometry[0] = static_cast<int>(rect.Width());
this->Geometry[1] = static_cast<int>(rect.Height());
}
vtkRectf vtkChart::GetSize()
{
return this->Size;
}
void vtkChart::SetActionToButton(int action, int button)
{
if (action < -1 || action >= MouseActions::MaxAction)
{
vtkErrorMacro("Error, invalid action value supplied: " << action)
return;
}
this->Actions[action] = button;
for (int i = 0; i < MouseActions::MaxAction; ++i)
{
if (this->Actions[i] == button && i != action)
{
this->Actions[i] = -1;
}
}
}
int vtkChart::GetActionToButton(int action)
{
return this->Actions[action];
}
void vtkChart::SetClickActionToButton(int action, int button)
{
if (action < vtkChart::SELECT || action > vtkChart::NOTIFY)
{
vtkErrorMacro("Error, invalid action value supplied: " << action)
return;
}
this->Actions[action - 2] = button;
}
int vtkChart::GetClickActionToButton(int action)
{
return this->Actions[action - 2];
}
//-----------------------------------------------------------------------------
void vtkChart::SetBackgroundBrush(vtkBrush *brush)
{
if(brush == NULL)
{
// set to transparent white if brush is null
this->BackgroundBrush->SetColorF(1, 1, 1, 0);
}
else
{
this->BackgroundBrush = brush;
}
this->Modified();
}
//-----------------------------------------------------------------------------
vtkBrush* vtkChart::GetBackgroundBrush()
{
return this->BackgroundBrush.GetPointer();
}
//-----------------------------------------------------------------------------
void vtkChart::PrintSelf(ostream &os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
// Print out the chart's geometry if it has been set
os << indent << "Point1: " << this->Point1[0] << "\t" << this->Point1[1]
<< endl;
os << indent << "Point2: " << this->Point2[0] << "\t" << this->Point2[1]
<< endl;
os << indent << "Width: " << this->Geometry[0] << endl
<< indent << "Height: " << this->Geometry[1] << endl;
os << indent << "SelectionMode: " << this->SelectionMode << endl;
}
//-----------------------------------------------------------------------------
void vtkChart::AttachAxisRangeListener(vtkAxis* axis)
{
axis->AddObserver(vtkChart::UpdateRange, this, &vtkChart::AxisRangeForwarderCallback);
}
//-----------------------------------------------------------------------------
void vtkChart::AxisRangeForwarderCallback(vtkObject*, unsigned long, void*)
{
double fullAxisRange[8];
for(int i=0; i < 4; i++)
{
this->GetAxis(i)->GetRange(&fullAxisRange[i*2]);
}
this->InvokeEvent(vtkChart::UpdateRange, fullAxisRange);
}
//-----------------------------------------------------------------------------
void vtkChart::SetSelectionMode(int selMode)
{
if (this->SelectionMode == selMode ||
selMode < vtkContextScene::SELECTION_NONE ||
selMode > vtkContextScene::SELECTION_TOGGLE)
{
return;
}
this->SelectionMode = selMode;
if(this->SelectionMode == vtkContextScene::SELECTION_NONE)
{
this->SetActionToButton(vtkChart::PAN, vtkContextMouseEvent::LEFT_BUTTON);
this->SetActionToButton(vtkChart::SELECT, vtkContextMouseEvent::RIGHT_BUTTON);
}
else
{
this->SetActionToButton(vtkChart::SELECT, vtkContextMouseEvent::LEFT_BUTTON);
}
this->Modified();
}
<|endoftext|> |
<commit_before>#include "positiontrackeradapter.h"
#include "ui_positiontrackeradapter.h"
#include <QPainter>
#include <cmath>
PositionTrackerAdapter::PositionTrackerAdapter(std::shared_ptr<PositionTracker> src, QWidget *parent) :
QWidget(parent),
ui(new Ui::PositionTrackerAdapter),
posTracker(src),
minx(-0.5),
maxx( 0.5),
miny(-0.5),
maxy( 0.5)
{
ui->setupUi(this);
if(posTracker.get() != nullptr)
{
connect(posTracker.get(), SIGNAL(onNewPosition(RobotPosition)), this, SLOT(onNewPosition(RobotPosition)));
connect(posTracker.get(), SIGNAL(onOriginPercentage(int)), this, SLOT(onOriginPercentage(int)));
}
connect(this, SIGNAL(updateBecauseOfData()), this, SLOT(update()));
connect(this, SIGNAL(setProgress(int)), ui->progressBar, SLOT(setValue(int)));
}
PositionTrackerAdapter::~PositionTrackerAdapter()
{
if(posTracker.get() != nullptr)
{
disconnect(posTracker.get(), SIGNAL(onNewPosition(RobotPosition)), this, SLOT(onNewPosition(RobotPosition)));
disconnect(posTracker.get(), SIGNAL(onOriginPercentage(int)), this, SLOT(onOriginPercentage(int)));
}
positions.clear();
delete ui;
}
void PositionTrackerAdapter::paintEvent(QPaintEvent *)
{
double scale = 100 * ( (maxx-minx) / this->width() );
ui->scaleLabel->setText(tr("%1 m").arg(scale,1));
QPainter painter(this);
painter.setPen(Qt::blue);
int scaleLineLength = 100;
painter.drawLine(ui->scaleLabel->x() + (ui->scaleLabel->width()/2) - scaleLineLength/2,
ui->scaleLabel->y() ,
ui->scaleLabel->x() + (ui->scaleLabel->width()/2) + scaleLineLength/2,
ui->scaleLabel->y() );
painter.drawLine(ui->scaleLabel->x() + (ui->scaleLabel->width()/2) - scaleLineLength/2,
ui->scaleLabel->y() - 2,
ui->scaleLabel->x() + (ui->scaleLabel->width()/2) - scaleLineLength/2,
ui->scaleLabel->y() + 2);
painter.drawLine(ui->scaleLabel->x() + (ui->scaleLabel->width()/2) + scaleLineLength/2,
ui->scaleLabel->y() - 2,
ui->scaleLabel->x() + (ui->scaleLabel->width()/2) + scaleLineLength/2,
ui->scaleLabel->y() + 2);
if(positions.size() > 0)
{
QPen pen(Qt::black);
pen.setWidth(5);
painter.setPen(pen);
int margin = 4;
int w = this->width() - margin*2;
int h = this->height() - margin*2;
double xscale = w / (maxx - minx);
double yscale = h / (maxy - miny);
int lastx = ( positions[0].X - minx ) * xscale;
int lasty = h - ( ( positions[0].Y - miny ) * yscale );
for(uint i = 1; i < positions.size(); i++)
{
RobotPosition p = positions[i];
int x = ( p.X - minx ) * xscale;
int y = h - ( ( p.Y - miny ) * yscale );
painter.drawLine(lastx+margin, lasty+margin, x+margin, y+margin);
lastx = x;
lasty = y;
}
}
painter.end();
}
void PositionTrackerAdapter::onNewPosition(RobotPosition pos)
{
positions.push_back(pos);
minx = std::min(pos.X, minx);
maxx = std::max(pos.X, maxx);
miny = std::min(pos.Y, miny);
maxy = std::max(pos.Y, maxy);
updateBecauseOfData();
}
void PositionTrackerAdapter::onOriginPercentage(int percent)
{
setProgress(percent);
if(percent == 100)
ui->progressBar->hide();
}
void PositionTrackerAdapter::on_resetButton_clicked()
{
on_clearButton_clicked();
posTracker->Reset();
ui->progressBar->show();
}
void PositionTrackerAdapter::on_clearButton_clicked()
{
positions.clear();
minx = -0.5;
maxx = 0.5;
miny = -0.5;
maxy = 0.5;
updateBecauseOfData();
}
<commit_msg>Adds colors to PositionTrackerAdapter! Yay colors!<commit_after>#include "positiontrackeradapter.h"
#include "ui_positiontrackeradapter.h"
#include <QPainter>
#include <cmath>
#include <algorithm>
PositionTrackerAdapter::PositionTrackerAdapter(std::shared_ptr<PositionTracker> src, QWidget *parent) :
QWidget(parent),
ui(new Ui::PositionTrackerAdapter),
posTracker(src),
minx(-0.5),
maxx( 0.5),
miny(-0.5),
maxy( 0.5)
{
ui->setupUi(this);
if(posTracker.get() != nullptr)
{
connect(posTracker.get(), SIGNAL(onNewPosition(RobotPosition)), this, SLOT(onNewPosition(RobotPosition)));
connect(posTracker.get(), SIGNAL(onOriginPercentage(int)), this, SLOT(onOriginPercentage(int)));
}
connect(this, SIGNAL(updateBecauseOfData()), this, SLOT(update()));
connect(this, SIGNAL(setProgress(int)), ui->progressBar, SLOT(setValue(int)));
}
PositionTrackerAdapter::~PositionTrackerAdapter()
{
if(posTracker.get() != nullptr)
{
disconnect(posTracker.get(), SIGNAL(onNewPosition(RobotPosition)), this, SLOT(onNewPosition(RobotPosition)));
disconnect(posTracker.get(), SIGNAL(onOriginPercentage(int)), this, SLOT(onOriginPercentage(int)));
}
positions.clear();
delete ui;
}
void PositionTrackerAdapter::paintEvent(QPaintEvent *)
{
double scale = 100 * ( (maxx-minx) / this->width() );
ui->scaleLabel->setText(tr("%1 m").arg(scale,1));
QPainter painter(this);
painter.setPen(Qt::blue);
int scaleLineLength = 100;
painter.drawLine(ui->scaleLabel->x() + (ui->scaleLabel->width()/2) - scaleLineLength/2,
ui->scaleLabel->y() ,
ui->scaleLabel->x() + (ui->scaleLabel->width()/2) + scaleLineLength/2,
ui->scaleLabel->y() );
painter.drawLine(ui->scaleLabel->x() + (ui->scaleLabel->width()/2) - scaleLineLength/2,
ui->scaleLabel->y() - 2,
ui->scaleLabel->x() + (ui->scaleLabel->width()/2) - scaleLineLength/2,
ui->scaleLabel->y() + 2);
painter.drawLine(ui->scaleLabel->x() + (ui->scaleLabel->width()/2) + scaleLineLength/2,
ui->scaleLabel->y() - 2,
ui->scaleLabel->x() + (ui->scaleLabel->width()/2) + scaleLineLength/2,
ui->scaleLabel->y() + 2);
if(positions.size() > 0)
{
QPen pen(Qt::black);
pen.setWidth(5);
painter.setPen(pen);
int margin = 4;
int w = this->width() - margin*2;
int h = this->height() - margin*2;
double xscale = w / (maxx - minx);
double yscale = h / (maxy - miny);
int lastx = ( positions[0].X - minx ) * xscale;
int lasty = h - ( ( positions[0].Y - miny ) * yscale );
for(uint i = 1; i < positions.size(); i++)
{
RobotPosition p = positions[i];
int x = ( p.X - minx ) * xscale;
int y = h - ( ( p.Y - miny ) * yscale );
auto percentage = (double)i / (double)positions.size();
auto brightness = std::max((int)(percentage*255),25);
std::cout << brightness << std::endl;
pen.setColor(QColor(0, 0, 0, brightness));
painter.setPen(pen);
painter.drawLine(lastx+margin, lasty+margin, x+margin, y+margin);
lastx = x;
lasty = y;
}
}
painter.end();
}
void PositionTrackerAdapter::onNewPosition(RobotPosition pos)
{
positions.push_back(pos);
minx = std::min(pos.X, minx);
maxx = std::max(pos.X, maxx);
miny = std::min(pos.Y, miny);
maxy = std::max(pos.Y, maxy);
updateBecauseOfData();
}
void PositionTrackerAdapter::onOriginPercentage(int percent)
{
setProgress(percent);
if(percent == 100)
ui->progressBar->hide();
}
void PositionTrackerAdapter::on_resetButton_clicked()
{
on_clearButton_clicked();
posTracker->Reset();
ui->progressBar->show();
}
void PositionTrackerAdapter::on_clearButton_clicked()
{
positions.clear();
minx = -0.5;
maxx = 0.5;
miny = -0.5;
maxy = 0.5;
updateBecauseOfData();
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://www.qtsoftware.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qgraphicssystemfactory_p.h"
#include "qgraphicssystemplugin_p.h"
#include "private/qfactoryloader_p.h"
#include "qmutex.h"
#include "qapplication.h"
#include "qgraphicssystem_raster_p.h"
#include "qdebug.h"
QT_BEGIN_NAMESPACE
#if !defined(QT_NO_LIBRARY) && !defined(QT_NO_SETTINGS)
Q_GLOBAL_STATIC_WITH_ARGS(QFactoryLoader, loader,
(QGraphicsSystemFactoryInterface_iid, QLatin1String("/graphicssystems"), Qt::CaseInsensitive))
#endif
QGraphicsSystem *QGraphicsSystemFactory::create(const QString& key)
{
QGraphicsSystem *ret = 0;
QString system = key.toLower();
#if defined (QT_GRAPHICSSYSTEM_OPENGL)
if (system.isEmpty()) {
system = QLatin1String("opengl");
}
#elif defined (QT_GRAPHICSSYSTEM_RASTER) && !defined(Q_WS_WIN) && !defined(Q_WS_S60)
if (system.isEmpty()) {
system = QLatin1String("raster");
}
#endif
if (system == QLatin1String("raster"))
return new QRasterGraphicsSystem;
else if (system.isEmpty() || system == QLatin1String("native"))
return 0;
#if !defined(QT_NO_LIBRARY) && !defined(QT_NO_SETTINGS)
if (!ret) {
if (QGraphicsSystemFactoryInterface *factory = qobject_cast<QGraphicsSystemFactoryInterface*>(loader()->instance(system)))
ret = factory->create(system);
}
#endif
if (!ret)
qWarning() << "Unable to load graphicssystem" << system;
return ret;
}
/*!
Returns the list of valid keys, i.e. the keys this factory can
create styles for.
\sa create()
*/
QStringList QGraphicsSystemFactory::keys()
{
#if !defined(QT_NO_LIBRARY) && !defined(QT_NO_SETTINGS)
QStringList list = loader()->keys();
#else
QStringList list;
#endif
if (!list.contains(QLatin1String("Raster")))
list << QLatin1String("raster");
return list;
}
QT_END_NAMESPACE
<commit_msg>Use OpenVG graphics system by default if Qt is configured to do so.<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://www.qtsoftware.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qgraphicssystemfactory_p.h"
#include "qgraphicssystemplugin_p.h"
#include "private/qfactoryloader_p.h"
#include "qmutex.h"
#include "qapplication.h"
#include "qgraphicssystem_raster_p.h"
#include "qdebug.h"
QT_BEGIN_NAMESPACE
#if !defined(QT_NO_LIBRARY) && !defined(QT_NO_SETTINGS)
Q_GLOBAL_STATIC_WITH_ARGS(QFactoryLoader, loader,
(QGraphicsSystemFactoryInterface_iid, QLatin1String("/graphicssystems"), Qt::CaseInsensitive))
#endif
QGraphicsSystem *QGraphicsSystemFactory::create(const QString& key)
{
QGraphicsSystem *ret = 0;
QString system = key.toLower();
#if defined (QT_GRAPHICSSYSTEM_OPENGL)
if (system.isEmpty()) {
system = QLatin1String("opengl");
}
#elif defined (QT_GRAPHICSSYSTEM_OPENVG)
if (system.isEmpty()) {
system = QLatin1String("openvg");
}
#elif defined (QT_GRAPHICSSYSTEM_RASTER) && !defined(Q_WS_WIN) && !defined(Q_WS_S60)
if (system.isEmpty()) {
system = QLatin1String("raster");
}
#endif
if (system == QLatin1String("raster"))
return new QRasterGraphicsSystem;
else if (system.isEmpty() || system == QLatin1String("native"))
return 0;
#if !defined(QT_NO_LIBRARY) && !defined(QT_NO_SETTINGS)
if (!ret) {
if (QGraphicsSystemFactoryInterface *factory = qobject_cast<QGraphicsSystemFactoryInterface*>(loader()->instance(system)))
ret = factory->create(system);
}
#endif
if (!ret)
qWarning() << "Unable to load graphicssystem" << system;
return ret;
}
/*!
Returns the list of valid keys, i.e. the keys this factory can
create styles for.
\sa create()
*/
QStringList QGraphicsSystemFactory::keys()
{
#if !defined(QT_NO_LIBRARY) && !defined(QT_NO_SETTINGS)
QStringList list = loader()->keys();
#else
QStringList list;
#endif
if (!list.contains(QLatin1String("Raster")))
list << QLatin1String("raster");
return list;
}
QT_END_NAMESPACE
<|endoftext|> |
<commit_before>/**
* @copyright Copyright 2018 The J-PET Framework 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 find a copy of the License in the LICENCE file.
*
* 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 JPetManagerTest.cpp
*/
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE JPetManagerTest
#include <boost/test/unit_test.hpp>
#include "./JPetManager/JPetManager.h"
#include <cstdio> //for std::remove
BOOST_AUTO_TEST_SUITE(FirstSuite)
BOOST_AUTO_TEST_CASE(create_unique_manager)
{
JPetManager& manager = JPetManager::getManager();
JPetManager* pManager = &manager;
JPetManager& manager2 = JPetManager::getManager();
JPetManager* pManager2 = &manager2;
BOOST_REQUIRE_EQUAL(pManager, pManager2);
}
BOOST_AUTO_TEST_CASE(threadsEnabled)
{
JPetManager& manager = JPetManager::getManager();
BOOST_REQUIRE(!manager.areThreadsEnabled());
manager.setThreadsEnabled(true);
BOOST_REQUIRE(manager.areThreadsEnabled());
manager.setThreadsEnabled(false);
BOOST_REQUIRE(!manager.areThreadsEnabled());
}
BOOST_AUTO_TEST_CASE(emptyRun)
{
JPetManager& manager = JPetManager::getManager();
BOOST_CHECK_THROW(manager.run(0, nullptr), std::exception);
}
BOOST_AUTO_TEST_CASE(goodRootRun)
{
JPetManager& manager = JPetManager::getManager();
const char* args[7] = {
"test/Path",
"--file",
"unitTestData/JPetManagerTest/goodRootFile.root",
"--type",
"root",
"-p",
"conf_trb3.xml"
};
BOOST_REQUIRE_NO_THROW(manager.run(7, args));
}
BOOST_AUTO_TEST_CASE(goodZipRun)
{
std::remove("unitTestData/JPetManagerTest/xx14099113231.hld");
JPetManager& manager = JPetManager::getManager();
const char* args[14] = {"test/Path", "--file", "unitTestData/JPetManagerTest/xx14099113231.hld.xz", "--type", "zip", "-p", "unitTestData/JPetManagerTest/conf_trb3.xml", "-r", "0", "10", "-l", "unitTestData/JPetManagerTest/large_barrel.json", "-i", "44"};
BOOST_REQUIRE_NO_THROW(manager.run(14, args));
}
BOOST_AUTO_TEST_CASE(goodMCRun)
{
JPetManager &manager = JPetManager::getManager();
manager.clearRegisteredTasks();
const char* args[11] = {
"test/Path",
"--file",
"unitTestData/JPetManagerTest/goodMCFile.mcGeant.root",
"--type",
"mcGeant",
"-p",
"conf_trb3.xml",
"-l",
"unitTestData/JPetManagerTest/large_barrel.json",
"-i",
"44"
};
BOOST_REQUIRE(manager.run(11, args));
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Adapt UT to new error handling<commit_after>/**
* @copyright Copyright 2018 The J-PET Framework 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 find a copy of the License in the LICENCE file.
*
* 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 JPetManagerTest.cpp
*/
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE JPetManagerTest
#include <boost/test/unit_test.hpp>
#include "./JPetManager/JPetManager.h"
#include <cstdio> //for std::remove
BOOST_AUTO_TEST_SUITE(FirstSuite)
BOOST_AUTO_TEST_CASE(create_unique_manager)
{
JPetManager& manager = JPetManager::getManager();
JPetManager* pManager = &manager;
JPetManager& manager2 = JPetManager::getManager();
JPetManager* pManager2 = &manager2;
BOOST_REQUIRE_EQUAL(pManager, pManager2);
}
BOOST_AUTO_TEST_CASE(threadsEnabled)
{
JPetManager& manager = JPetManager::getManager();
BOOST_REQUIRE(!manager.areThreadsEnabled());
manager.setThreadsEnabled(true);
BOOST_REQUIRE(manager.areThreadsEnabled());
manager.setThreadsEnabled(false);
BOOST_REQUIRE(!manager.areThreadsEnabled());
}
BOOST_AUTO_TEST_CASE(emptyRun)
{
JPetManager& manager = JPetManager::getManager();
BOOST_CHECK_THROW(manager.run(0, nullptr), std::exception);
}
BOOST_AUTO_TEST_CASE(goodRootRun)
{
JPetManager& manager = JPetManager::getManager();
const char* args[7] = {
"test/Path",
"--file",
"unitTestData/JPetManagerTest/goodRootFile.root",
"--type",
"root",
"-p",
"conf_trb3.xml"
};
BOOST_REQUIRE_NO_THROW(manager.run(7, args));
}
BOOST_AUTO_TEST_CASE(goodZipRun)
{
std::remove("unitTestData/JPetManagerTest/xx14099113231.hld");
JPetManager& manager = JPetManager::getManager();
const char* args[14] = {"test/Path", "--file", "unitTestData/JPetManagerTest/xx14099113231.hld.xz", "--type", "zip", "-p", "unitTestData/JPetManagerTest/conf_trb3.xml", "-r", "0", "10", "-l", "unitTestData/JPetManagerTest/large_barrel.json", "-i", "44"};
BOOST_REQUIRE_NO_THROW(manager.run(14, args));
}
BOOST_AUTO_TEST_CASE(goodMCRun)
{
JPetManager &manager = JPetManager::getManager();
const char* args[11] = {
"test/Path",
"--file",
"unitTestData/JPetManagerTest/goodMCFile.mcGeant.root",
"--type",
"mcGeant",
"-p",
"conf_trb3.xml",
"-l",
"unitTestData/JPetManagerTest/large_barrel.json",
"-i",
"44"
};
BOOST_REQUIRE_NO_THROW(manager.run(11, args));
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|> |
<commit_before>/*
* A auto-growing buffer you can write to.
*
* author: Max Kellermann <mk@cm4all.com>
*/
#include "growing_buffer.hxx"
#include "pool.hxx"
#include "util/ConstBuffer.hxx"
#include "util/WritableBuffer.hxx"
#include <assert.h>
#include <string.h>
struct buffer {
struct buffer *next;
size_t length;
char data[sizeof(size_t)];
};
struct GrowingBuffer {
struct pool *pool;
#ifndef NDEBUG
size_t initial_size;
#endif
size_t size;
struct buffer *current, *tail, first;
void AppendBuffer(struct buffer &buffer);
void CopyTo(void *dest) const;
};
GrowingBuffer *gcc_malloc
growing_buffer_new(struct pool *pool, size_t initial_size)
{
GrowingBuffer *gb = (GrowingBuffer *)
p_malloc(pool, sizeof(*gb) - sizeof(gb->first.data) + initial_size);
gb->pool = pool;
#ifndef NDEBUG
gb->initial_size = initial_size;
#endif
gb->size = initial_size;
gb->current = &gb->first;
gb->tail = &gb->first;
gb->first.next = nullptr;
gb->first.length = 0;
return gb;
}
void
GrowingBuffer::AppendBuffer(struct buffer &buffer)
{
assert(buffer.next == nullptr);
tail->next = &buffer;
tail = &buffer;
}
void *
growing_buffer_write(GrowingBuffer *gb, size_t length)
{
struct buffer *buffer = gb->tail;
void *ret;
assert(gb->size > 0);
if (buffer->length + length > gb->size) {
if (gb->size < length)
gb->size = length; /* XXX round up? */
buffer = (struct buffer *)
p_malloc(gb->pool,
sizeof(*buffer) - sizeof(buffer->data) + gb->size);
buffer->next = nullptr;
buffer->length = 0;
gb->AppendBuffer(*buffer);
}
assert(buffer->length + length <= gb->size);
ret = buffer->data + buffer->length;
buffer->length += length;
return ret;
}
void
growing_buffer_write_buffer(GrowingBuffer *gb, const void *p, size_t length)
{
memcpy(growing_buffer_write(gb, length), p, length);
}
void
growing_buffer_write_string(GrowingBuffer *gb, const char *p)
{
growing_buffer_write_buffer(gb, p, strlen(p));
}
void
growing_buffer_cat(GrowingBuffer *dest, GrowingBuffer *src)
{
dest->tail->next = &src->first;
dest->tail = src->tail;
dest->size = src->size;
}
size_t
growing_buffer_size(const GrowingBuffer *gb)
{
size_t size = 0;
for (const struct buffer *buffer = &gb->first;
buffer != nullptr; buffer = buffer->next)
size += buffer->length;
return size;
}
GrowingBufferReader::GrowingBufferReader(const GrowingBuffer &gb)
#ifndef NDEBUG
:growing_buffer(&gb)
#endif
{
assert(gb.first.length > 0 || gb.first.next == nullptr ||
(gb.first.next != nullptr &&
gb.size > gb.initial_size &&
gb.first.next->length > gb.initial_size));
buffer = &gb.first;
if (buffer->length == 0 && buffer->next != nullptr)
buffer = buffer->next;
position = 0;
}
void
GrowingBufferReader::Update()
{
assert(buffer != nullptr);
assert(position <= buffer->length);
if (position == buffer->length &&
buffer->next != nullptr) {
/* the reader was at the end of all buffers, but then a new
buffer was appended */
buffer = buffer->next;
position = 0;
}
}
bool
GrowingBufferReader::IsEOF() const
{
assert(buffer != nullptr);
assert(position <= buffer->length);
return position == buffer->length;
}
size_t
GrowingBufferReader::Available() const
{
assert(buffer != nullptr);
assert(position <= buffer->length);
size_t available = buffer->length - position;
for (const struct buffer *b = buffer->next; b != nullptr; b = b->next) {
assert(b->length > 0);
available += b->length;
}
return available;
}
ConstBuffer<void>
GrowingBufferReader::Read() const
{
assert(buffer != nullptr);
const struct buffer *b = buffer;
if (b->length == 0 && b->next != nullptr) {
/* skip the empty first buffer that was too small */
assert(b == &growing_buffer->first);
assert(position == 0);
b = b->next;
}
if (position >= b->length) {
assert(position == b->length);
assert(buffer->next == nullptr);
return nullptr;
}
return { b->data + position, b->length - position };
}
void
GrowingBufferReader::Consume(size_t length)
{
assert(buffer != nullptr);
if (length == 0)
return;
if (buffer->length == 0 && buffer->next != nullptr) {
/* skip the empty first buffer that was too small */
assert(buffer == &growing_buffer->first);
assert(position == 0);
buffer = buffer->next;
}
position += length;
assert(position <= buffer->length);
if (position >= buffer->length) {
if (buffer->next == nullptr)
return;
buffer = buffer->next;
position = 0;
}
}
ConstBuffer<void>
GrowingBufferReader::PeekNext() const
{
assert(buffer != nullptr);
const struct buffer *b = buffer;
if (b->length == 0 && b->next != nullptr) {
/* skip the empty first buffer that was too small */
assert(b == &growing_buffer->first);
assert(position == 0);
b = b->next;
}
b = b->next;
if (b == nullptr)
return nullptr;
return { b->data, b->length };
}
void
GrowingBufferReader::Skip(size_t length)
{
assert(buffer != nullptr);
while (length > 0) {
size_t remaining = buffer->length - position;
if (length < remaining ||
(length == remaining && buffer->next == nullptr)) {
position += length;
return;
}
length -= remaining;
if (buffer->next == nullptr) {
assert(position + remaining == length);
position = length;
return;
}
assert(buffer->next != nullptr);
buffer = buffer->next;
position = 0;
}
}
void
GrowingBuffer::CopyTo(void *_dest) const
{
unsigned char *dest = (unsigned char *)_dest;
for (const struct buffer *buffer = &first; buffer != nullptr;
buffer = buffer->next) {
memcpy(dest, buffer->data, buffer->length);
dest += buffer->length;
}
}
WritableBuffer<void>
growing_buffer_dup(const GrowingBuffer *gb, struct pool *pool)
{
size_t length;
length = growing_buffer_size(gb);
if (length == 0)
return nullptr;
void *dest = p_malloc(pool, length);
gb->CopyTo(dest);
return { dest, length };
}
<commit_msg>growing_buffer: use mempcpy()<commit_after>/*
* A auto-growing buffer you can write to.
*
* author: Max Kellermann <mk@cm4all.com>
*/
#include "growing_buffer.hxx"
#include "pool.hxx"
#include "util/ConstBuffer.hxx"
#include "util/WritableBuffer.hxx"
#include <assert.h>
#include <string.h>
struct buffer {
struct buffer *next;
size_t length;
char data[sizeof(size_t)];
};
struct GrowingBuffer {
struct pool *pool;
#ifndef NDEBUG
size_t initial_size;
#endif
size_t size;
struct buffer *current, *tail, first;
void AppendBuffer(struct buffer &buffer);
void CopyTo(void *dest) const;
};
GrowingBuffer *gcc_malloc
growing_buffer_new(struct pool *pool, size_t initial_size)
{
GrowingBuffer *gb = (GrowingBuffer *)
p_malloc(pool, sizeof(*gb) - sizeof(gb->first.data) + initial_size);
gb->pool = pool;
#ifndef NDEBUG
gb->initial_size = initial_size;
#endif
gb->size = initial_size;
gb->current = &gb->first;
gb->tail = &gb->first;
gb->first.next = nullptr;
gb->first.length = 0;
return gb;
}
void
GrowingBuffer::AppendBuffer(struct buffer &buffer)
{
assert(buffer.next == nullptr);
tail->next = &buffer;
tail = &buffer;
}
void *
growing_buffer_write(GrowingBuffer *gb, size_t length)
{
struct buffer *buffer = gb->tail;
void *ret;
assert(gb->size > 0);
if (buffer->length + length > gb->size) {
if (gb->size < length)
gb->size = length; /* XXX round up? */
buffer = (struct buffer *)
p_malloc(gb->pool,
sizeof(*buffer) - sizeof(buffer->data) + gb->size);
buffer->next = nullptr;
buffer->length = 0;
gb->AppendBuffer(*buffer);
}
assert(buffer->length + length <= gb->size);
ret = buffer->data + buffer->length;
buffer->length += length;
return ret;
}
void
growing_buffer_write_buffer(GrowingBuffer *gb, const void *p, size_t length)
{
memcpy(growing_buffer_write(gb, length), p, length);
}
void
growing_buffer_write_string(GrowingBuffer *gb, const char *p)
{
growing_buffer_write_buffer(gb, p, strlen(p));
}
void
growing_buffer_cat(GrowingBuffer *dest, GrowingBuffer *src)
{
dest->tail->next = &src->first;
dest->tail = src->tail;
dest->size = src->size;
}
size_t
growing_buffer_size(const GrowingBuffer *gb)
{
size_t size = 0;
for (const struct buffer *buffer = &gb->first;
buffer != nullptr; buffer = buffer->next)
size += buffer->length;
return size;
}
GrowingBufferReader::GrowingBufferReader(const GrowingBuffer &gb)
#ifndef NDEBUG
:growing_buffer(&gb)
#endif
{
assert(gb.first.length > 0 || gb.first.next == nullptr ||
(gb.first.next != nullptr &&
gb.size > gb.initial_size &&
gb.first.next->length > gb.initial_size));
buffer = &gb.first;
if (buffer->length == 0 && buffer->next != nullptr)
buffer = buffer->next;
position = 0;
}
void
GrowingBufferReader::Update()
{
assert(buffer != nullptr);
assert(position <= buffer->length);
if (position == buffer->length &&
buffer->next != nullptr) {
/* the reader was at the end of all buffers, but then a new
buffer was appended */
buffer = buffer->next;
position = 0;
}
}
bool
GrowingBufferReader::IsEOF() const
{
assert(buffer != nullptr);
assert(position <= buffer->length);
return position == buffer->length;
}
size_t
GrowingBufferReader::Available() const
{
assert(buffer != nullptr);
assert(position <= buffer->length);
size_t available = buffer->length - position;
for (const struct buffer *b = buffer->next; b != nullptr; b = b->next) {
assert(b->length > 0);
available += b->length;
}
return available;
}
ConstBuffer<void>
GrowingBufferReader::Read() const
{
assert(buffer != nullptr);
const struct buffer *b = buffer;
if (b->length == 0 && b->next != nullptr) {
/* skip the empty first buffer that was too small */
assert(b == &growing_buffer->first);
assert(position == 0);
b = b->next;
}
if (position >= b->length) {
assert(position == b->length);
assert(buffer->next == nullptr);
return nullptr;
}
return { b->data + position, b->length - position };
}
void
GrowingBufferReader::Consume(size_t length)
{
assert(buffer != nullptr);
if (length == 0)
return;
if (buffer->length == 0 && buffer->next != nullptr) {
/* skip the empty first buffer that was too small */
assert(buffer == &growing_buffer->first);
assert(position == 0);
buffer = buffer->next;
}
position += length;
assert(position <= buffer->length);
if (position >= buffer->length) {
if (buffer->next == nullptr)
return;
buffer = buffer->next;
position = 0;
}
}
ConstBuffer<void>
GrowingBufferReader::PeekNext() const
{
assert(buffer != nullptr);
const struct buffer *b = buffer;
if (b->length == 0 && b->next != nullptr) {
/* skip the empty first buffer that was too small */
assert(b == &growing_buffer->first);
assert(position == 0);
b = b->next;
}
b = b->next;
if (b == nullptr)
return nullptr;
return { b->data, b->length };
}
void
GrowingBufferReader::Skip(size_t length)
{
assert(buffer != nullptr);
while (length > 0) {
size_t remaining = buffer->length - position;
if (length < remaining ||
(length == remaining && buffer->next == nullptr)) {
position += length;
return;
}
length -= remaining;
if (buffer->next == nullptr) {
assert(position + remaining == length);
position = length;
return;
}
assert(buffer->next != nullptr);
buffer = buffer->next;
position = 0;
}
}
void
GrowingBuffer::CopyTo(void *dest) const
{
for (const struct buffer *buffer = &first; buffer != nullptr;
buffer = buffer->next)
dest = mempcpy(dest, buffer->data, buffer->length);
}
WritableBuffer<void>
growing_buffer_dup(const GrowingBuffer *gb, struct pool *pool)
{
size_t length;
length = growing_buffer_size(gb);
if (length == 0)
return nullptr;
void *dest = p_malloc(pool, length);
gb->CopyTo(dest);
return { dest, length };
}
<|endoftext|> |
<commit_before>#include "SocketServer.h"
asio::io_service* SocketServer::io_service_ = new asio::io_service;
//TcpConnection::~TcpConnection()
//{
// std::cout << "delete";
// delete_from_parent();
//}
TcpConnection::pointer TcpConnection::create(asio::io_service& io_service, SocketServer* parent)
{
return pointer(new TcpConnection(io_service, parent));
}
tcp::socket& TcpConnection::socket()
{
return socket_;
}
void TcpConnection::start()
{
asio::async_read(socket_,
asio::buffer(read_msg_.data(), socket_message::header_length),
std::bind(&TcpConnection::handle_read_header, this,
std::placeholders::_1));
}
void TcpConnection::write_data(std::string s)
{
if (error_flag_) return;
socket_message msg;
if (s.size() == 0)
{
s = std::string("\0");
msg.body_length(1);
}
else
msg.body_length(s.size());
memcpy(msg.body(), &s[0u], msg.body_length());
msg.encode_header();
asio::write(socket_,
asio::buffer(msg.data(), msg.length()));
}
std::string TcpConnection::read_data()
{
std::unique_lock<std::mutex> lk{mut_};
while (read_msg_deque_.empty())
data_cond_.wait(lk);
auto read_msg = read_msg_deque_.front();
read_msg_deque_.pop_front();
lk.unlock();
auto ret = std::string(read_msg.body(), read_msg.body_length());
return ret;
}
void TcpConnection::do_close()
{
try {
error_flag_ = true;
socket_message empty_msg;
memcpy(empty_msg.data(), "0001\0", 5);
read_msg_deque_.push_back(empty_msg);
data_cond_.notify_one();
asio::error_code ec;
socket_.shutdown(asio::ip::tcp::socket::shutdown_both, ec);
if (!ec)
throw asio::system_error(ec);
socket_.close();
}
catch (std::exception&e)
{
e.what();
}
delete_from_parent();
}
void TcpConnection::handle_read_header(const asio::error_code& error)
{
if (!error && read_msg_.decode_header())
{
std::cout << "here\n";
asio::async_read(socket_,
asio::buffer(read_msg_.body(), read_msg_.body_length()),
std::bind(&TcpConnection::handle_read_body, this,
std::placeholders::_1));
}
else
{
do_close();
}
}
void TcpConnection::handle_read_body(const asio::error_code& error)
{
if (!error)
{
std::lock_guard<std::mutex> lk{mut_};
read_msg_deque_.push_back(read_msg_);
data_cond_.notify_one();
asio::async_read(socket_,
asio::buffer(read_msg_.data(), socket_message::header_length),
std::bind(&TcpConnection::handle_read_header, this,
std::placeholders::_1));
}
else
{
do_close();
}
}
TcpConnection::TcpConnection(asio::io_service& io_service, SocketServer* parent):
socket_(io_service), parent(parent)
{
std::cout << "new tcp" << std::endl;
}
void TcpConnection::delete_from_parent()
{
if (parent)
shared_from_this()->parent->remove_connection(shared_from_this());
parent = nullptr;
}
SocketServer* SocketServer::create(int port)
{
// io_service_ = new asio::io_service;
auto s = new SocketServer(port);
s->thread_ = new std::thread(
std::bind(static_cast<std::size_t(asio::io_service::*)()>(&asio::io_service::run),
io_service_));
return s;
}
void SocketServer::button_start()
{
using namespace std; // For sprintf and memcpy.
char total[4 + 1] = "";
sprintf(total, "%4d", static_cast<int>(connections_.size()));
for (auto i = 0; i < connections_.size(); i++)
connections_[i]->write_data("PLAYER" + std::string(total) + std::to_string(i + 1));
connection_num_ = connections_.size();
this->button_thread_ = new std::thread(std::bind(&SocketServer::loop_process, this));
button_thread_->detach();
}
SocketServer::SocketServer(int port):
acceptor_(*io_service_, tcp::endpoint(tcp::v4(), port))
{
start_accept();
}
void SocketServer::loop_process()
{
while (true)
{
if (connections_.size() != connection_num_)
{
error_flag_ = true;
break;
}
// throw std::exception{"lost connection"};
// std::unique_lock<std::mutex> lock(delete_mutex_);
std::vector<std::string> ret;
for (auto r : connections_)
{
if (r->error())
// break;
error_flag_ |= r->error();
ret.push_back(r->read_data());
}
auto game_msg = GameMessageWrap::combine_message(ret);
for (auto r : connections_)
r->write_data(game_msg);
}
}
std::vector<TcpConnection::pointer> SocketServer::get_connection() const
{
return connections_;
}
void SocketServer::remove_connection(TcpConnection::pointer p)
{
// connections_.erase(std::remove(connections_.begin(), connections_.end(), p), connections_.end());
std::unique_lock<std::mutex> lock(delete_mutex_);
auto position = std::find(connections_.begin(), connections_.end(), p);
if (position == connections_.end())
std::cout << "delete not succ\n";
else
connections_.erase(position);
std::cout << "delete succ\n";
}
void SocketServer::start_accept()
{
TcpConnection::pointer new_connection =
TcpConnection::create(acceptor_.get_io_service(), this);
acceptor_.async_accept(new_connection->socket(),
std::bind(&SocketServer::handle_accept, this, new_connection,
std::placeholders::_1));
std::cout << "start accept " << std::endl;
}
void SocketServer::handle_accept(TcpConnection::pointer new_connection, const asio::error_code& error)
{
std::cout << "handle_accept\n";
if (!error)
{
connections_.push_back(new_connection);
std::cout << new_connection->socket().remote_endpoint().address()
<< ":" << new_connection->socket().remote_endpoint().port() << std::endl;
new_connection->start();
}
start_accept();
// std::cout << "handle accept\n";
}
<commit_msg>Fix in server<commit_after>#include "SocketServer.h"
asio::io_service* SocketServer::io_service_ = new asio::io_service;
//TcpConnection::~TcpConnection()
//{
// std::cout << "delete";
// delete_from_parent();
//}
TcpConnection::pointer TcpConnection::create(asio::io_service& io_service, SocketServer* parent)
{
return pointer(new TcpConnection(io_service, parent));
}
tcp::socket& TcpConnection::socket()
{
return socket_;
}
void TcpConnection::start()
{
asio::async_read(socket_,
asio::buffer(read_msg_.data(), socket_message::header_length),
std::bind(&TcpConnection::handle_read_header, this,
std::placeholders::_1));
}
void TcpConnection::write_data(std::string s)
{
if (error_flag_) return;
socket_message msg;
if (s.size() == 0)
{
s = std::string("\0");
msg.body_length(1);
}
else
msg.body_length(s.size());
memcpy(msg.body(), &s[0u], msg.body_length());
msg.encode_header();
asio::write(socket_,
asio::buffer(msg.data(), msg.length()));
}
std::string TcpConnection::read_data()
{
if (error_flag_)
return "";
std::unique_lock<std::mutex> lk{mut_};
while (read_msg_deque_.empty())
data_cond_.wait(lk);
auto read_msg = read_msg_deque_.front();
read_msg_deque_.pop_front();
lk.unlock();
auto ret = std::string(read_msg.body(), read_msg.body_length());
return ret;
}
void TcpConnection::do_close()
{
try {
error_flag_ = true;
socket_message empty_msg;
memcpy(empty_msg.data(), "0001\0", 5);
read_msg_deque_.push_back(empty_msg);
data_cond_.notify_one();
asio::error_code ec;
socket_.shutdown(asio::ip::tcp::socket::shutdown_both, ec);
if (!ec)
throw asio::system_error(ec);
socket_.close();
}
catch (std::exception&e)
{
e.what();
}
delete_from_parent();
}
void TcpConnection::handle_read_header(const asio::error_code& error)
{
if (!error && read_msg_.decode_header())
{
std::cout << "here\n";
asio::async_read(socket_,
asio::buffer(read_msg_.body(), read_msg_.body_length()),
std::bind(&TcpConnection::handle_read_body, this,
std::placeholders::_1));
}
else
{
do_close();
}
}
void TcpConnection::handle_read_body(const asio::error_code& error)
{
if (!error)
{
std::lock_guard<std::mutex> lk{mut_};
read_msg_deque_.push_back(read_msg_);
data_cond_.notify_one();
asio::async_read(socket_,
asio::buffer(read_msg_.data(), socket_message::header_length),
std::bind(&TcpConnection::handle_read_header, this,
std::placeholders::_1));
}
else
{
do_close();
}
}
TcpConnection::TcpConnection(asio::io_service& io_service, SocketServer* parent):
socket_(io_service), parent(parent)
{
std::cout << "new tcp" << std::endl;
}
void TcpConnection::delete_from_parent()
{
if (parent)
shared_from_this()->parent->remove_connection(shared_from_this());
parent = nullptr;
}
SocketServer* SocketServer::create(int port)
{
// io_service_ = new asio::io_service;
auto s = new SocketServer(port);
s->thread_ = new std::thread(
std::bind(static_cast<std::size_t(asio::io_service::*)()>(&asio::io_service::run),
io_service_));
return s;
}
void SocketServer::button_start()
{
using namespace std; // For sprintf and memcpy.
char total[4 + 1] = "";
sprintf(total, "%4d", static_cast<int>(connections_.size()));
for (auto i = 0; i < connections_.size(); i++)
connections_[i]->write_data("PLAYER" + std::string(total) + std::to_string(i + 1));
connection_num_ = connections_.size();
this->button_thread_ = new std::thread(std::bind(&SocketServer::loop_process, this));
button_thread_->detach();
}
SocketServer::SocketServer(int port):
acceptor_(*io_service_, tcp::endpoint(tcp::v4(), port))
{
start_accept();
}
void SocketServer::loop_process()
{
while (true)
{
if (connections_.size() != connection_num_)
{
error_flag_ = true;
break;
}
// throw std::exception{"lost connection"};
std::unique_lock<std::mutex> lock(delete_mutex_);
std::vector<std::string> ret;
for (auto r : connections_)
{
if (r->error())
// break;
error_flag_ |= r->error();
ret.push_back(r->read_data());
}
auto game_msg = GameMessageWrap::combine_message(ret);
for (auto r : connections_)
r->write_data(game_msg);
}
}
std::vector<TcpConnection::pointer> SocketServer::get_connection() const
{
return connections_;
}
void SocketServer::remove_connection(TcpConnection::pointer p)
{
// connections_.erase(std::remove(connections_.begin(), connections_.end(), p), connections_.end());
std::unique_lock<std::mutex> lock(delete_mutex_);
auto position = std::find(connections_.begin(), connections_.end(), p);
if (position == connections_.end())
std::cout << "delete not succ\n";
else
connections_.erase(position);
std::cout << "delete succ\n";
}
void SocketServer::start_accept()
{
TcpConnection::pointer new_connection =
TcpConnection::create(acceptor_.get_io_service(), this);
acceptor_.async_accept(new_connection->socket(),
std::bind(&SocketServer::handle_accept, this, new_connection,
std::placeholders::_1));
std::cout << "start accept " << std::endl;
}
void SocketServer::handle_accept(TcpConnection::pointer new_connection, const asio::error_code& error)
{
std::cout << "handle_accept\n";
if (!error)
{
connections_.push_back(new_connection);
std::cout << new_connection->socket().remote_endpoint().address()
<< ":" << new_connection->socket().remote_endpoint().port() << std::endl;
new_connection->start();
}
start_accept();
// std::cout << "handle accept\n";
}
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/scoped_ptr.h"
#include "net/base/net_errors.h"
#include "net/http/http_auth_handler.h"
#include "net/http/http_auth_handler_factory.h"
#include "net/http/url_security_manager.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace net {
namespace {
class MockHttpAuthHandlerFactory : public HttpAuthHandlerFactory {
public:
explicit MockHttpAuthHandlerFactory(int return_code) :
return_code_(return_code) {}
virtual ~MockHttpAuthHandlerFactory() {}
virtual int CreateAuthHandler(HttpAuth::ChallengeTokenizer* challenge,
HttpAuth::Target target,
const GURL& origin,
CreateReason reason,
int nonce_count,
const BoundNetLog& net_log,
scoped_ptr<HttpAuthHandler>* handler) {
handler->reset();
return return_code_;
}
private:
int return_code_;
};
} // namespace
TEST(HttpAuthHandlerFactoryTest, RegistryFactory) {
HttpAuthHandlerRegistryFactory registry_factory;
GURL gurl("www.google.com");
const int kBasicReturnCode = ERR_INVALID_SPDY_STREAM;
MockHttpAuthHandlerFactory* mock_factory_basic =
new MockHttpAuthHandlerFactory(kBasicReturnCode);
const int kDigestReturnCode = ERR_PAC_SCRIPT_FAILED;
MockHttpAuthHandlerFactory* mock_factory_digest =
new MockHttpAuthHandlerFactory(kDigestReturnCode);
const int kDigestReturnCodeReplace = ERR_SYN_REPLY_NOT_RECEIVED;
MockHttpAuthHandlerFactory* mock_factory_digest_replace =
new MockHttpAuthHandlerFactory(kDigestReturnCodeReplace);
scoped_ptr<HttpAuthHandler> handler;
// No schemes should be supported in the beginning.
EXPECT_EQ(ERR_UNSUPPORTED_AUTH_SCHEME,
registry_factory.CreateAuthHandlerFromString(
"Basic", HttpAuth::AUTH_SERVER, gurl, BoundNetLog(), &handler));
// Test what happens with a single scheme.
registry_factory.RegisterSchemeFactory("Basic", mock_factory_basic);
EXPECT_EQ(kBasicReturnCode,
registry_factory.CreateAuthHandlerFromString(
"Basic", HttpAuth::AUTH_SERVER, gurl, BoundNetLog(), &handler));
EXPECT_EQ(ERR_UNSUPPORTED_AUTH_SCHEME,
registry_factory.CreateAuthHandlerFromString(
"Digest", HttpAuth::AUTH_SERVER, gurl, BoundNetLog(),
&handler));
// Test multiple schemes
registry_factory.RegisterSchemeFactory("Digest", mock_factory_digest);
EXPECT_EQ(kBasicReturnCode,
registry_factory.CreateAuthHandlerFromString(
"Basic", HttpAuth::AUTH_SERVER, gurl, BoundNetLog(), &handler));
EXPECT_EQ(kDigestReturnCode,
registry_factory.CreateAuthHandlerFromString(
"Digest", HttpAuth::AUTH_SERVER, gurl, BoundNetLog(),
&handler));
// Test case-insensitivity
EXPECT_EQ(kBasicReturnCode,
registry_factory.CreateAuthHandlerFromString(
"basic", HttpAuth::AUTH_SERVER, gurl, BoundNetLog(), &handler));
// Test replacement of existing auth scheme
registry_factory.RegisterSchemeFactory("Digest", mock_factory_digest_replace);
EXPECT_EQ(kBasicReturnCode,
registry_factory.CreateAuthHandlerFromString(
"Basic", HttpAuth::AUTH_SERVER, gurl, BoundNetLog(), &handler));
EXPECT_EQ(kDigestReturnCodeReplace,
registry_factory.CreateAuthHandlerFromString(
"Digest", HttpAuth::AUTH_SERVER, gurl, BoundNetLog(),
&handler));
}
TEST(HttpAuthHandlerFactoryTest, DefaultFactory) {
URLSecurityManagerAllow url_security_manager;
scoped_ptr<HttpAuthHandlerRegistryFactory> http_auth_handler_factory(
HttpAuthHandlerFactory::CreateDefault());
http_auth_handler_factory->SetURLSecurityManager(
"negotiate", &url_security_manager);
GURL server_origin("http://www.example.com");
GURL proxy_origin("http://cache.example.com:3128");
{
scoped_ptr<HttpAuthHandler> handler;
int rv = http_auth_handler_factory->CreateAuthHandlerFromString(
"Basic realm=\"FooBar\"",
HttpAuth::AUTH_SERVER,
server_origin,
BoundNetLog(),
&handler);
EXPECT_EQ(OK, rv);
EXPECT_FALSE(handler.get() == NULL);
EXPECT_STREQ("basic", handler->scheme().c_str());
EXPECT_STREQ("FooBar", handler->realm().c_str());
EXPECT_EQ(HttpAuth::AUTH_SERVER, handler->target());
EXPECT_FALSE(handler->encrypts_identity());
EXPECT_FALSE(handler->is_connection_based());
}
{
scoped_ptr<HttpAuthHandler> handler;
int rv = http_auth_handler_factory->CreateAuthHandlerFromString(
"UNSUPPORTED realm=\"FooBar\"",
HttpAuth::AUTH_SERVER,
server_origin,
BoundNetLog(),
&handler);
EXPECT_EQ(ERR_UNSUPPORTED_AUTH_SCHEME, rv);
EXPECT_TRUE(handler.get() == NULL);
}
{
scoped_ptr<HttpAuthHandler> handler;
int rv = http_auth_handler_factory->CreateAuthHandlerFromString(
"Digest realm=\"FooBar\", nonce=\"xyz\"",
HttpAuth::AUTH_PROXY,
proxy_origin,
BoundNetLog(),
&handler);
EXPECT_EQ(OK, rv);
EXPECT_FALSE(handler.get() == NULL);
EXPECT_STREQ("digest", handler->scheme().c_str());
EXPECT_STREQ("FooBar", handler->realm().c_str());
EXPECT_EQ(HttpAuth::AUTH_PROXY, handler->target());
EXPECT_TRUE(handler->encrypts_identity());
EXPECT_FALSE(handler->is_connection_based());
}
{
scoped_ptr<HttpAuthHandler> handler;
int rv = http_auth_handler_factory->CreateAuthHandlerFromString(
"NTLM",
HttpAuth::AUTH_SERVER,
server_origin,
BoundNetLog(),
&handler);
EXPECT_EQ(OK, rv);
ASSERT_FALSE(handler.get() == NULL);
EXPECT_STREQ("ntlm", handler->scheme().c_str());
EXPECT_STREQ("", handler->realm().c_str());
EXPECT_EQ(HttpAuth::AUTH_SERVER, handler->target());
EXPECT_TRUE(handler->encrypts_identity());
EXPECT_TRUE(handler->is_connection_based());
}
{
scoped_ptr<HttpAuthHandler> handler;
int rv = http_auth_handler_factory->CreateAuthHandlerFromString(
"Negotiate",
HttpAuth::AUTH_SERVER,
server_origin,
BoundNetLog(),
&handler);
EXPECT_EQ(OK, rv);
EXPECT_FALSE(handler.get() == NULL);
EXPECT_STREQ("negotiate", handler->scheme().c_str());
EXPECT_STREQ("", handler->realm().c_str());
EXPECT_EQ(HttpAuth::AUTH_SERVER, handler->target());
EXPECT_TRUE(handler->encrypts_identity());
EXPECT_TRUE(handler->is_connection_based());
}
}
} // namespace net
<commit_msg>Change some EXPECT's to ASSERT's in http_auth_handler_factory_unittest.cc<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/scoped_ptr.h"
#include "net/base/net_errors.h"
#include "net/http/http_auth_handler.h"
#include "net/http/http_auth_handler_factory.h"
#include "net/http/url_security_manager.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace net {
namespace {
class MockHttpAuthHandlerFactory : public HttpAuthHandlerFactory {
public:
explicit MockHttpAuthHandlerFactory(int return_code) :
return_code_(return_code) {}
virtual ~MockHttpAuthHandlerFactory() {}
virtual int CreateAuthHandler(HttpAuth::ChallengeTokenizer* challenge,
HttpAuth::Target target,
const GURL& origin,
CreateReason reason,
int nonce_count,
const BoundNetLog& net_log,
scoped_ptr<HttpAuthHandler>* handler) {
handler->reset();
return return_code_;
}
private:
int return_code_;
};
} // namespace
TEST(HttpAuthHandlerFactoryTest, RegistryFactory) {
HttpAuthHandlerRegistryFactory registry_factory;
GURL gurl("www.google.com");
const int kBasicReturnCode = ERR_INVALID_SPDY_STREAM;
MockHttpAuthHandlerFactory* mock_factory_basic =
new MockHttpAuthHandlerFactory(kBasicReturnCode);
const int kDigestReturnCode = ERR_PAC_SCRIPT_FAILED;
MockHttpAuthHandlerFactory* mock_factory_digest =
new MockHttpAuthHandlerFactory(kDigestReturnCode);
const int kDigestReturnCodeReplace = ERR_SYN_REPLY_NOT_RECEIVED;
MockHttpAuthHandlerFactory* mock_factory_digest_replace =
new MockHttpAuthHandlerFactory(kDigestReturnCodeReplace);
scoped_ptr<HttpAuthHandler> handler;
// No schemes should be supported in the beginning.
EXPECT_EQ(ERR_UNSUPPORTED_AUTH_SCHEME,
registry_factory.CreateAuthHandlerFromString(
"Basic", HttpAuth::AUTH_SERVER, gurl, BoundNetLog(), &handler));
// Test what happens with a single scheme.
registry_factory.RegisterSchemeFactory("Basic", mock_factory_basic);
EXPECT_EQ(kBasicReturnCode,
registry_factory.CreateAuthHandlerFromString(
"Basic", HttpAuth::AUTH_SERVER, gurl, BoundNetLog(), &handler));
EXPECT_EQ(ERR_UNSUPPORTED_AUTH_SCHEME,
registry_factory.CreateAuthHandlerFromString(
"Digest", HttpAuth::AUTH_SERVER, gurl, BoundNetLog(),
&handler));
// Test multiple schemes
registry_factory.RegisterSchemeFactory("Digest", mock_factory_digest);
EXPECT_EQ(kBasicReturnCode,
registry_factory.CreateAuthHandlerFromString(
"Basic", HttpAuth::AUTH_SERVER, gurl, BoundNetLog(), &handler));
EXPECT_EQ(kDigestReturnCode,
registry_factory.CreateAuthHandlerFromString(
"Digest", HttpAuth::AUTH_SERVER, gurl, BoundNetLog(),
&handler));
// Test case-insensitivity
EXPECT_EQ(kBasicReturnCode,
registry_factory.CreateAuthHandlerFromString(
"basic", HttpAuth::AUTH_SERVER, gurl, BoundNetLog(), &handler));
// Test replacement of existing auth scheme
registry_factory.RegisterSchemeFactory("Digest", mock_factory_digest_replace);
EXPECT_EQ(kBasicReturnCode,
registry_factory.CreateAuthHandlerFromString(
"Basic", HttpAuth::AUTH_SERVER, gurl, BoundNetLog(), &handler));
EXPECT_EQ(kDigestReturnCodeReplace,
registry_factory.CreateAuthHandlerFromString(
"Digest", HttpAuth::AUTH_SERVER, gurl, BoundNetLog(),
&handler));
}
TEST(HttpAuthHandlerFactoryTest, DefaultFactory) {
URLSecurityManagerAllow url_security_manager;
scoped_ptr<HttpAuthHandlerRegistryFactory> http_auth_handler_factory(
HttpAuthHandlerFactory::CreateDefault());
http_auth_handler_factory->SetURLSecurityManager(
"negotiate", &url_security_manager);
GURL server_origin("http://www.example.com");
GURL proxy_origin("http://cache.example.com:3128");
{
scoped_ptr<HttpAuthHandler> handler;
int rv = http_auth_handler_factory->CreateAuthHandlerFromString(
"Basic realm=\"FooBar\"",
HttpAuth::AUTH_SERVER,
server_origin,
BoundNetLog(),
&handler);
EXPECT_EQ(OK, rv);
ASSERT_FALSE(handler.get() == NULL);
EXPECT_STREQ("basic", handler->scheme().c_str());
EXPECT_STREQ("FooBar", handler->realm().c_str());
EXPECT_EQ(HttpAuth::AUTH_SERVER, handler->target());
EXPECT_FALSE(handler->encrypts_identity());
EXPECT_FALSE(handler->is_connection_based());
}
{
scoped_ptr<HttpAuthHandler> handler;
int rv = http_auth_handler_factory->CreateAuthHandlerFromString(
"UNSUPPORTED realm=\"FooBar\"",
HttpAuth::AUTH_SERVER,
server_origin,
BoundNetLog(),
&handler);
EXPECT_EQ(ERR_UNSUPPORTED_AUTH_SCHEME, rv);
EXPECT_TRUE(handler.get() == NULL);
}
{
scoped_ptr<HttpAuthHandler> handler;
int rv = http_auth_handler_factory->CreateAuthHandlerFromString(
"Digest realm=\"FooBar\", nonce=\"xyz\"",
HttpAuth::AUTH_PROXY,
proxy_origin,
BoundNetLog(),
&handler);
EXPECT_EQ(OK, rv);
ASSERT_FALSE(handler.get() == NULL);
EXPECT_STREQ("digest", handler->scheme().c_str());
EXPECT_STREQ("FooBar", handler->realm().c_str());
EXPECT_EQ(HttpAuth::AUTH_PROXY, handler->target());
EXPECT_TRUE(handler->encrypts_identity());
EXPECT_FALSE(handler->is_connection_based());
}
{
scoped_ptr<HttpAuthHandler> handler;
int rv = http_auth_handler_factory->CreateAuthHandlerFromString(
"NTLM",
HttpAuth::AUTH_SERVER,
server_origin,
BoundNetLog(),
&handler);
EXPECT_EQ(OK, rv);
ASSERT_FALSE(handler.get() == NULL);
EXPECT_STREQ("ntlm", handler->scheme().c_str());
EXPECT_STREQ("", handler->realm().c_str());
EXPECT_EQ(HttpAuth::AUTH_SERVER, handler->target());
EXPECT_TRUE(handler->encrypts_identity());
EXPECT_TRUE(handler->is_connection_based());
}
{
scoped_ptr<HttpAuthHandler> handler;
int rv = http_auth_handler_factory->CreateAuthHandlerFromString(
"Negotiate",
HttpAuth::AUTH_SERVER,
server_origin,
BoundNetLog(),
&handler);
EXPECT_EQ(OK, rv);
ASSERT_FALSE(handler.get() == NULL);
EXPECT_STREQ("negotiate", handler->scheme().c_str());
EXPECT_STREQ("", handler->realm().c_str());
EXPECT_EQ(HttpAuth::AUTH_SERVER, handler->target());
EXPECT_TRUE(handler->encrypts_identity());
EXPECT_TRUE(handler->is_connection_based());
}
}
} // namespace net
<|endoftext|> |
<commit_before>// @(#)root/mathmore:$Id: Integrator.cxx 19826 2007-09-19 19:56:11Z rdm $
// Authors: L. Moneta, M. Slawinska 10/2007
/**********************************************************************
* *
* Copyright (c) 2004 ROOT Foundation, CERN/PH-SFT *
* *
* *
**********************************************************************/
#include "Math/IFunction.h"
#include "Math/VirtualIntegrator.h"
#include "Math/Integrator.h"
#include "Math/IntegratorMultiDim.h"
#include "Math/AdaptiveIntegratorMultiDim.h"
#include "Math/GaussIntegrator.h"
#include "Math/OneDimFunctionAdapter.h"
#include "RConfigure.h"
// #ifndef ROOTINCDIR
// #define MATH_NO_PLUGIN_MANAGER
// #endif
#ifndef MATH_NO_PLUGIN_MANAGER
#include "TROOT.h"
#include "TPluginManager.h"
#else // case no plugin manager is available
#ifdef R__HAS_MATHMORE
#include "Math/GSLIntegrator.h"
#include "Math/GSLMCIntegrator.h"
#endif
#endif
#include <cassert>
namespace ROOT {
namespace Math {
void IntegratorOneDim::SetFunction(const IMultiGenFunction &f, unsigned int icoord , const double * x ) {
// set function from a multi-dim function
// pass also x in case of multi-dim function express the other dimensions (which are fixed)
unsigned int ndim = f.NDim();
assert (icoord < ndim);
ROOT::Math::OneDimMultiFunctionAdapter<> adapter(f,ndim,icoord);
// case I pass a vector x which is needed (for example to compute I(y) = Integral( f(x,y) dx) ) need to setCX
if (x != 0) adapter.SetX(x, x+ ndim);
SetFunction(adapter,true); // need to copy this object
}
// methods to create integrators
VirtualIntegratorOneDim * IntegratorOneDim::CreateIntegrator(IntegrationOneDim::Type type , double absTol, double relTol, unsigned int size, int rule) {
// create the concrete class for one-dimensional integration. Use the plug-in manager if needed
if (type == IntegrationOneDim::kGAUSS)
return new GaussIntegrator();
VirtualIntegratorOneDim * ig = 0;
#ifdef MATH_NO_PLUGIN_MANAGER // no PM available
#ifdef R__HAS_MATHMORE
ig = new GSLIntegrator(type, absTol, relTol, size);
#else
MATH_ERROR_MSG("IntegratorOneDim::CreateIntegrator","Integrator type is not available in MathCore");
#endif
#else // case of using Plugin Manager
TPluginHandler *h;
//gDebug = 3;
if ((h = gROOT->GetPluginManager()->FindHandler("ROOT::Math::VirtualIntegrator", "GSLIntegrator"))) {
if (h->LoadPlugin() == -1) {
MATH_ERROR_MSG("IntegratorOneDim::CreateIntegrator","Error loading one dimensional GSL integrator");
return 0;
}
std::string typeName = "ADAPTIVE";
if (type == IntegrationOneDim::kADAPTIVESINGULAR)
typeName = "ADAPTIVESINGULAR";
if (type == IntegrationOneDim::kNONADAPTIVE)
typeName = "NONADAPTIVE";
ig = reinterpret_cast<ROOT::Math::VirtualIntegratorOneDim *>( h->ExecPlugin(5,typeName.c_str(), rule, absTol, relTol, size ) );
assert(ig != 0);
#ifdef DEBUG
std::cout << "Loaded Integrator " << typeid(*ig).name() << std::endl;
#endif
}
#endif
return ig;
}
VirtualIntegratorMultiDim * IntegratorMultiDim::CreateIntegrator(IntegrationMultiDim::Type type , double absTol, double relTol, unsigned int ncall) {
// create concrete class for multidimensional integration
// no need for PM in the adaptive case using Genz method (class is in MathCore)
if (type == IntegrationMultiDim::kADAPTIVE)
return new AdaptiveIntegratorMultiDim(absTol, relTol, ncall);
VirtualIntegratorMultiDim * ig = 0;
#ifdef MATH_NO_PLUGIN_MANAGER // no PM available
#ifdef R__HAS_MATHMORE
ig = new GSLMCIntegrator(type, absTol, relTol, ncall);
#else
MATH_ERROR_MSG("IntegratorMultiDim::CreateIntegrator","Integrator type is not available in MathCore");
#endif
#else // use ROOT PM
TPluginHandler *h;
//gDebug = 3;
if ((h = gROOT->GetPluginManager()->FindHandler("ROOT::Math::VirtualIntegrator", "GSLMCIntegrator"))) {
if (h->LoadPlugin() == -1) {
MATH_ERROR_MSG("IntegratorMultiDim::CreateIntegrator","Error loading multidim integrator");
return 0;
}
std::string typeName = "VEGAS";
if (type == IntegrationMultiDim::kMISER)
typeName = "MISER";
if (type == IntegrationMultiDim::kPLAIN)
typeName = "PLAIN";
ig = reinterpret_cast<ROOT::Math::VirtualIntegratorMultiDim *>( h->ExecPlugin(4,typeName.c_str(), absTol, relTol, ncall ) );
assert(ig != 0);
#ifdef DEBUG
std::cout << "Loaded Integrator " << typeid(*ig).name() << std::endl;
#endif
}
#endif
return ig;
}
} // namespace Math
} // namespace ROOT
<commit_msg>- fix integration method when mathmore is not built and when the plug-in manager fails to load it<commit_after>// @(#)root/mathmore:$Id: Integrator.cxx 19826 2007-09-19 19:56:11Z rdm $
// Authors: L. Moneta, M. Slawinska 10/2007
/**********************************************************************
* *
* Copyright (c) 2004 ROOT Foundation, CERN/PH-SFT *
* *
* *
**********************************************************************/
#include "Math/IFunction.h"
#include "Math/VirtualIntegrator.h"
#include "Math/Integrator.h"
#include "Math/IntegratorMultiDim.h"
#include "Math/AdaptiveIntegratorMultiDim.h"
#include "Math/GaussIntegrator.h"
#include "Math/OneDimFunctionAdapter.h"
#include "RConfigure.h"
// #ifndef ROOTINCDIR
// #define MATH_NO_PLUGIN_MANAGER
// #endif
#ifndef MATH_NO_PLUGIN_MANAGER
#include "TROOT.h"
#include "TPluginManager.h"
#else // case no plugin manager is available
#ifdef R__HAS_MATHMORE
#include "Math/GSLIntegrator.h"
#include "Math/GSLMCIntegrator.h"
#endif
#endif
#include <cassert>
namespace ROOT {
namespace Math {
void IntegratorOneDim::SetFunction(const IMultiGenFunction &f, unsigned int icoord , const double * x ) {
// set function from a multi-dim function
// pass also x in case of multi-dim function express the other dimensions (which are fixed)
unsigned int ndim = f.NDim();
assert (icoord < ndim);
ROOT::Math::OneDimMultiFunctionAdapter<> adapter(f,ndim,icoord);
// case I pass a vector x which is needed (for example to compute I(y) = Integral( f(x,y) dx) ) need to setCX
if (x != 0) adapter.SetX(x, x+ ndim);
SetFunction(adapter,true); // need to copy this object
}
// methods to create integrators
VirtualIntegratorOneDim * IntegratorOneDim::CreateIntegrator(IntegrationOneDim::Type type , double absTol, double relTol, unsigned int size, int rule) {
// create the concrete class for one-dimensional integration. Use the plug-in manager if needed
#ifndef R__HAS_MATHMORE
// default type is GAUSS when Mathmore is not built
type = IntegrationOneDim::kGAUSS;
#endif
if (type == IntegrationOneDim::kGAUSS)
return new GaussIntegrator();
VirtualIntegratorOneDim * ig = 0;
#ifdef MATH_NO_PLUGIN_MANAGER // no PM available
#ifdef R__HAS_MATHMORE
ig = new GSLIntegrator(type, absTol, relTol, size);
#else
MATH_ERROR_MSG("IntegratorOneDim::CreateIntegrator","Integrator type is not available in MathCore");
#endif
#else // case of using Plugin Manager
TPluginHandler *h;
//gDebug = 3;
if ((h = gROOT->GetPluginManager()->FindHandler("ROOT::Math::VirtualIntegrator", "GSLIntegrator"))) {
if (h->LoadPlugin() == -1) {
MATH_WARN_MSG("IntegratorOneDim::CreateIntegrator","Error loading one dimensional GSL integrator - use Gauss integrator");
return new GaussIntegrator();
}
std::string typeName = "ADAPTIVE";
if (type == IntegrationOneDim::kADAPTIVESINGULAR)
typeName = "ADAPTIVESINGULAR";
if (type == IntegrationOneDim::kNONADAPTIVE)
typeName = "NONADAPTIVE";
ig = reinterpret_cast<ROOT::Math::VirtualIntegratorOneDim *>( h->ExecPlugin(5,typeName.c_str(), rule, absTol, relTol, size ) );
assert(ig != 0);
#ifdef DEBUG
std::cout << "Loaded Integrator " << typeid(*ig).name() << std::endl;
#endif
}
#endif
return ig;
}
VirtualIntegratorMultiDim * IntegratorMultiDim::CreateIntegrator(IntegrationMultiDim::Type type , double absTol, double relTol, unsigned int ncall) {
// create concrete class for multidimensional integration
#ifndef R__HAS_MATHMORE
// default type is Adaptive when Mathmore is not built
type = IntegrationMultiDim::kADAPTIVE;
#endif
// no need for PM in the adaptive case using Genz method (class is in MathCore)
if (type == IntegrationMultiDim::kADAPTIVE)
return new AdaptiveIntegratorMultiDim(absTol, relTol, ncall);
VirtualIntegratorMultiDim * ig = 0;
#ifdef MATH_NO_PLUGIN_MANAGER // no PM available
#ifdef R__HAS_MATHMORE
ig = new GSLMCIntegrator(type, absTol, relTol, ncall);
#else
MATH_ERROR_MSG("IntegratorMultiDim::CreateIntegrator","Integrator type is not available in MathCore");
#endif
#else // use ROOT PM
TPluginHandler *h;
//gDebug = 3;
if ((h = gROOT->GetPluginManager()->FindHandler("ROOT::Math::VirtualIntegrator", "GSLMCIntegrator"))) {
if (h->LoadPlugin() == -1) {
MATH_WARN_MSG("IntegratorMultiDim::CreateIntegrator","Error loading GSL MC multidim integrator - use adaptive method");
return new AdaptiveIntegratorMultiDim(absTol, relTol, ncall);
}
std::string typeName = "VEGAS";
if (type == IntegrationMultiDim::kMISER)
typeName = "MISER";
if (type == IntegrationMultiDim::kPLAIN)
typeName = "PLAIN";
ig = reinterpret_cast<ROOT::Math::VirtualIntegratorMultiDim *>( h->ExecPlugin(4,typeName.c_str(), absTol, relTol, ncall ) );
assert(ig != 0);
#ifdef DEBUG
std::cout << "Loaded Integrator " << typeid(*ig).name() << std::endl;
#endif
}
#endif
return ig;
}
} // namespace Math
} // namespace ROOT
<|endoftext|> |
<commit_before>/******************************************************************************/
/* */
/* X r d S y s P r i v . c c */
/* */
/* (c) 2006 G. Ganis (CERN) */
/* All Rights Reserved. See XrdInfo.cc for complete License Terms */
/******************************************************************************/
// $Id$
//////////////////////////////////////////////////////////////////////////
// //
// XrdSysPriv //
// //
// Author: G. Ganis, CERN, 2006 //
// //
// Implementation of a privileges handling API following the paper //
// "Setuid Demystified" by H.Chen, D.Wagner, D.Dean //
// also quoted in "Secure programming Cookbook" by J.Viega & M.Messier. //
// //
//////////////////////////////////////////////////////////////////////////
#include "XrdSys/XrdSysPriv.hh"
#if !defined(WINDOWS)
#include <stdio.h>
#include "XrdSys/XrdSysHeaders.hh"
#include <unistd.h>
#include <pwd.h>
#include <errno.h>
#define NOUC ((uid_t)(-1))
#define NOGC ((gid_t)(-1))
#define XSPERR(x) ((x == 0) ? -1 : -x)
// Some machine specific stuff
#if defined(__sgi) && !defined(__GNUG__) && (SGI_REL<62)
extern "C" {
int seteuid(int euid);
int setegid(int egid);
int geteuid();
int getegid();
}
#endif
#if defined(_AIX)
extern "C" {
int seteuid(uid_t euid);
int setegid(gid_t egid);
uid_t geteuid();
gid_t getegid();
}
#endif
#if !defined(__hpux) && !defined(linux) && !defined(__FreeBSD__) && \
!defined(__OpenBSD__)
static int setresgid(gid_t r, gid_t e, gid_t)
{
if (r != NOGC && setgid(r) == -1)
return XSPERR(errno);
return ((e != NOGC) ? setegid(e) : 0);
}
static int setresuid(uid_t r, uid_t e, uid_t)
{
if (r != NOUC && setuid(r) == -1)
return XSPERR(errno);
return ((e != NOUC) ? seteuid(e) : 0);
}
static int getresgid(gid_t *r, gid_t *e, gid_t *)
{
*r = getgid();
*e = getegid();
return 0;
}
static int getresuid(uid_t *r, uid_t *e, uid_t *)
{
*r = getuid();
*e = geteuid();
return 0;
}
#else
#if (defined(__linux__) || \
(defined(__CYGWIN__) && defined(__GNUC__))) && !defined(linux)
# define linux
#endif
#if defined(linux) && !defined(HAVE_SETRESUID)
extern "C" {
int setresgid(gid_t r, gid_t e, gid_t s);
int setresuid(uid_t r, uid_t e, uid_t s);
int getresgid(gid_t *r, gid_t *e, gid_t *s);
int getresuid(uid_t *r, uid_t *e, uid_t *s);
}
#endif
#endif
#endif // not WINDOWS
bool XrdSysPriv::fDebug = 0; // debug switch
// Gloval mutex
XrdSysRecMutex XrdSysPriv::fgMutex;
//______________________________________________________________________________
int XrdSysPriv::Restore(bool saved)
{
// Restore the 'saved' (saved = TRUE) or 'real' entity as effective.
// Return 0 on success, < 0 (== -errno) if any error occurs.
#if !defined(WINDOWS)
// Get the UIDs
uid_t ruid = 0, euid = 0, suid = 0;
if (getresuid(&ruid, &euid, &suid) != 0)
return XSPERR(errno);
// Set the wanted value
uid_t uid = saved ? suid : ruid;
// Act only if a change is needed
if (euid != uid) {
// Set uid as effective
if (setresuid(NOUC, uid, NOUC) != 0)
return XSPERR(errno);
// Make sure the new effective UID is the one wanted
if (geteuid() != uid)
return XSPERR(errno);
}
// Get the GIDs
uid_t rgid = 0, egid = 0, sgid = 0;
if (getresgid(&rgid, &egid, &sgid) != 0)
return XSPERR(errno);
// Set the wanted value
gid_t gid = saved ? sgid : rgid;
// Act only if a change is needed
if (egid != gid) {
// Set newuid as effective, saving the current effective GID
if (setresgid(NOGC, gid, NOGC) != 0)
return XSPERR(errno);
// Make sure the new effective GID is the one wanted
if (getegid() != gid)
return XSPERR(errno);
}
#endif
// Done
return 0;
}
//______________________________________________________________________________
int XrdSysPriv::ChangeTo(uid_t newuid, gid_t newgid)
{
// Change effective to entity newuid. Current entity is saved.
// Real entity is not touched. Use RestoreSaved to go back to
// previous settings.
// Return 0 on success, < 0 (== -errno) if any error occurs.
#if !defined(WINDOWS)
// Current UGID
uid_t oeuid = geteuid();
gid_t oegid = getegid();
// Restore privileges, if needed
if (oeuid && XrdSysPriv::Restore(0) != 0)
return XSPERR(errno);
// Act only if a change is needed
if (newgid != oegid) {
// Set newgid as effective, saving the current effective GID
if (setresgid(NOGC, newgid, oegid) != 0)
return XSPERR(errno);
// Get the GIDs
uid_t rgid = 0, egid = 0, sgid = 0;
if (getresgid(&rgid, &egid, &sgid) != 0)
return XSPERR(errno);
// Make sure the new effective GID is the one wanted
if (egid != newgid)
return XSPERR(errno);
}
// Act only if a change is needed
if (newuid != oeuid) {
// Set newuid as effective, saving the current effective UID
if (setresuid(NOUC, newuid, oeuid) != 0)
return XSPERR(errno);
// Get the UIDs
uid_t ruid = 0, euid = 0, suid = 0;
if (getresuid(&ruid, &euid, &suid) != 0)
return XSPERR(errno);
// Make sure the new effective UID is the one wanted
if (euid != newuid)
return XSPERR(errno);
}
#endif
// Done
return 0;
}
//______________________________________________________________________________
int XrdSysPriv::ChangePerm(uid_t newuid, gid_t newgid)
{
// Change permanently to entity newuid. Requires super-userprivileges.
// Provides a way to drop permanently su privileges.
// Return 0 on success, < 0 (== -errno) if any error occurs.
// Atomic action
XrdSysPriv::fgMutex.Lock();
#if !defined(WINDOWS)
// Get UIDs
uid_t cruid = 0, ceuid = 0, csuid = 0;
if (getresuid(&cruid, &ceuid, &csuid) != 0) {
XrdSysPriv::fgMutex.UnLock();
return XSPERR(errno);
}
// Get GIDs
uid_t crgid = 0, cegid = 0, csgid = 0;
if (getresgid(&crgid, &cegid, &csgid) != 0) {
XrdSysPriv::fgMutex.UnLock();
return XSPERR(errno);
}
// Restore privileges, if needed
if (ceuid && XrdSysPriv::Restore(0) != 0) {
XrdSysPriv::fgMutex.UnLock();
return XSPERR(errno);
}
// Act only if needed
if (newgid != cegid || newgid != crgid) {
// Set newgid as GID, all levels
if (setresgid(newgid, newgid, newgid) != 0) {
XrdSysPriv::fgMutex.UnLock();
return XSPERR(errno);
}
// Get GIDs
uid_t rgid = 0, egid = 0, sgid = 0;
if (getresgid(&rgid, &egid, &sgid) != 0) {
XrdSysPriv::fgMutex.UnLock();
return XSPERR(errno);
}
// Make sure the new GIDs are all equal to the one asked
if (rgid != newgid || egid != newgid) {
XrdSysPriv::fgMutex.UnLock();
return XSPERR(errno);
}
}
// Act only if needed
if (newuid != ceuid || newuid != cruid) {
// Set newuid as UID, all levels
if (setresuid(newuid, newuid, newuid) != 0) {
XrdSysPriv::fgMutex.UnLock();
return XSPERR(errno);
}
// Get UIDs
uid_t ruid = 0, euid = 0, suid = 0;
if (getresuid(&ruid, &euid, &suid) != 0) {
XrdSysPriv::fgMutex.UnLock();
return XSPERR(errno);
}
// Make sure the new UIDs are all equal to the one asked
if (ruid != newuid || euid != newuid) {
XrdSysPriv::fgMutex.UnLock();
return XSPERR(errno);
}
}
#endif
// Release the mutex
XrdSysPriv::fgMutex.UnLock();
// Done
return 0;
}
//______________________________________________________________________________
void XrdSysPriv::DumpUGID(const char *msg)
{
// Dump current entity
#if !defined(WINDOWS)
XrdSysPriv::fgMutex.Lock();
// Get the UIDs
uid_t ruid = 0, euid = 0, suid = 0;
if (getresuid(&ruid, &euid, &suid) != 0)
return;
// Get the GIDs
uid_t rgid = 0, egid = 0, sgid = 0;
if (getresgid(&rgid, &egid, &sgid) != 0)
return;
cout << "XrdSysPriv: " << endl;
cout << "XrdSysPriv: dump values: " << (msg ? msg : "") << endl;
cout << "XrdSysPriv: " << endl;
cout << "XrdSysPriv: real = (" << ruid <<","<< rgid <<")" << endl;
cout << "XrdSysPriv: effective = (" << euid <<","<< egid <<")" << endl;
cout << "XrdSysPriv: saved = (" << suid <<","<< sgid <<")" << endl;
cout << "XrdSysPriv: " << endl;
XrdSysPriv::fgMutex.UnLock();
#endif
}
//
// Guard class
//______________________________________________________________________________
XrdSysPrivGuard::XrdSysPrivGuard(uid_t uid, gid_t gid)
{
// Constructor. Create a guard object for temporarly change to privileges
// of {'uid', 'gid'}
dum = 1;
valid = 0;
Init(uid, gid);
}
//______________________________________________________________________________
XrdSysPrivGuard::XrdSysPrivGuard(const char *usr)
{
// Constructor. Create a guard object for temporarly change to privileges
// of 'usr'
dum = 1;
valid = 0;
#if !defined(WINDOWS)
if (usr && strlen(usr) > 0) {
struct passwd *pw = getpwnam(usr);
if (pw)
Init(pw->pw_uid, pw->pw_gid);
}
#else
if (usr) { }
#endif
}
//______________________________________________________________________________
XrdSysPrivGuard::~XrdSysPrivGuard()
{
// Destructor. Restore state and unlock the global mutex.
if (!dum) {
XrdSysPriv::Restore();
XrdSysPriv::fgMutex.UnLock();
}
}
//______________________________________________________________________________
void XrdSysPrivGuard::Init(uid_t uid, gid_t gid)
{
// Init a change of privileges guard. Act only if superuser.
// The result of initialization can be tested with the Valid() method.
dum = 1;
valid = 1;
// Debug hook
if (XrdSysPriv::fDebug)
XrdSysPriv::DumpUGID("before Init()");
#if !defined(WINDOWS)
XrdSysPriv::fgMutex.Lock();
uid_t ruid = 0, euid = 0, suid = 0;
gid_t rgid = 0, egid = 0, sgid = 0;
if (getresuid(&ruid, &euid, &suid) == 0 &&
getresgid(&rgid, &egid, &sgid) == 0) {
if ((euid != uid) || (egid != gid)) {
if (!ruid) {
// Change temporarly identity
if (XrdSysPriv::ChangeTo(uid, gid) != 0)
valid = 0;
dum = 0;
} else {
// Change requested but not enough privileges
valid = 0;
}
}
} else {
// Something bad happened: memory corruption?
valid = 0;
}
// Unlock if no action
if (dum)
XrdSysPriv::fgMutex.UnLock();
#endif
// Debug hook
if (XrdSysPriv::fDebug)
XrdSysPriv::DumpUGID("after Init()");
}
<commit_msg> Import fix for ICC warnings<commit_after>/******************************************************************************/
/* */
/* X r d S y s P r i v . c c */
/* */
/* (c) 2006 G. Ganis (CERN) */
/* All Rights Reserved. See XrdInfo.cc for complete License Terms */
/******************************************************************************/
// $Id$
//////////////////////////////////////////////////////////////////////////
// //
// XrdSysPriv //
// //
// Author: G. Ganis, CERN, 2006 //
// //
// Implementation of a privileges handling API following the paper //
// "Setuid Demystified" by H.Chen, D.Wagner, D.Dean //
// also quoted in "Secure programming Cookbook" by J.Viega & M.Messier. //
// //
//////////////////////////////////////////////////////////////////////////
#include "XrdSys/XrdSysPriv.hh"
#if !defined(WINDOWS)
#include <stdio.h>
#include "XrdSys/XrdSysHeaders.hh"
#include <unistd.h>
#include <pwd.h>
#include <errno.h>
#define NOUC ((uid_t)(-1))
#define NOGC ((gid_t)(-1))
#define XSPERR(x) ((x == 0) ? -1 : -x)
// Some machine specific stuff
#if defined(__sgi) && !defined(__GNUG__) && (SGI_REL<62)
extern "C" {
int seteuid(int euid);
int setegid(int egid);
int geteuid();
int getegid();
}
#endif
#if defined(_AIX)
extern "C" {
int seteuid(uid_t euid);
int setegid(gid_t egid);
uid_t geteuid();
gid_t getegid();
}
#endif
#if !defined(HAVE_SETRESUID)
static int setresgid(gid_t r, gid_t e, gid_t)
{
if (r != NOGC && setgid(r) == -1)
return XSPERR(errno);
return ((e != NOGC) ? setegid(e) : 0);
}
static int setresuid(uid_t r, uid_t e, uid_t)
{
if (r != NOUC && setuid(r) == -1)
return XSPERR(errno);
return ((e != NOUC) ? seteuid(e) : 0);
}
static int getresgid(gid_t *r, gid_t *e, gid_t *)
{
*r = getgid();
*e = getegid();
return 0;
}
static int getresuid(uid_t *r, uid_t *e, uid_t *)
{
*r = getuid();
*e = geteuid();
return 0;
}
#else
#if (defined(__linux__) || \
(defined(__CYGWIN__) && defined(__GNUC__))) && !defined(linux)
# define linux
#endif
#if defined(linux) && !defined(HAVE_SETRESUID)
extern "C" {
int setresgid(gid_t r, gid_t e, gid_t s);
int setresuid(uid_t r, uid_t e, uid_t s);
int getresgid(gid_t *r, gid_t *e, gid_t *s);
int getresuid(uid_t *r, uid_t *e, uid_t *s);
}
#endif
#endif
#endif // not WINDOWS
bool XrdSysPriv::fDebug = 0; // debug switch
// Gloval mutex
XrdSysRecMutex XrdSysPriv::fgMutex;
//______________________________________________________________________________
int XrdSysPriv::Restore(bool saved)
{
// Restore the 'saved' (saved = TRUE) or 'real' entity as effective.
// Return 0 on success, < 0 (== -errno) if any error occurs.
#if !defined(WINDOWS)
// Get the UIDs
uid_t ruid = 0, euid = 0, suid = 0;
if (getresuid(&ruid, &euid, &suid) != 0)
return XSPERR(errno);
// Set the wanted value
uid_t uid = saved ? suid : ruid;
// Act only if a change is needed
if (euid != uid) {
// Set uid as effective
if (setresuid(NOUC, uid, NOUC) != 0)
return XSPERR(errno);
// Make sure the new effective UID is the one wanted
if (geteuid() != uid)
return XSPERR(errno);
}
// Get the GIDs
uid_t rgid = 0, egid = 0, sgid = 0;
if (getresgid(&rgid, &egid, &sgid) != 0)
return XSPERR(errno);
// Set the wanted value
gid_t gid = saved ? sgid : rgid;
// Act only if a change is needed
if (egid != gid) {
// Set newuid as effective, saving the current effective GID
if (setresgid(NOGC, gid, NOGC) != 0)
return XSPERR(errno);
// Make sure the new effective GID is the one wanted
if (getegid() != gid)
return XSPERR(errno);
}
#endif
// Done
return 0;
}
//______________________________________________________________________________
int XrdSysPriv::ChangeTo(uid_t newuid, gid_t newgid)
{
// Change effective to entity newuid. Current entity is saved.
// Real entity is not touched. Use RestoreSaved to go back to
// previous settings.
// Return 0 on success, < 0 (== -errno) if any error occurs.
#if !defined(WINDOWS)
// Current UGID
uid_t oeuid = geteuid();
gid_t oegid = getegid();
// Restore privileges, if needed
if (oeuid && XrdSysPriv::Restore(0) != 0)
return XSPERR(errno);
// Act only if a change is needed
if (newgid != oegid) {
// Set newgid as effective, saving the current effective GID
if (setresgid(NOGC, newgid, oegid) != 0)
return XSPERR(errno);
// Get the GIDs
uid_t rgid = 0, egid = 0, sgid = 0;
if (getresgid(&rgid, &egid, &sgid) != 0)
return XSPERR(errno);
// Make sure the new effective GID is the one wanted
if (egid != newgid)
return XSPERR(errno);
}
// Act only if a change is needed
if (newuid != oeuid) {
// Set newuid as effective, saving the current effective UID
if (setresuid(NOUC, newuid, oeuid) != 0)
return XSPERR(errno);
// Get the UIDs
uid_t ruid = 0, euid = 0, suid = 0;
if (getresuid(&ruid, &euid, &suid) != 0)
return XSPERR(errno);
// Make sure the new effective UID is the one wanted
if (euid != newuid)
return XSPERR(errno);
}
#endif
// Done
return 0;
}
//______________________________________________________________________________
int XrdSysPriv::ChangePerm(uid_t newuid, gid_t newgid)
{
// Change permanently to entity newuid. Requires super-userprivileges.
// Provides a way to drop permanently su privileges.
// Return 0 on success, < 0 (== -errno) if any error occurs.
// Atomic action
XrdSysPriv::fgMutex.Lock();
#if !defined(WINDOWS)
// Get UIDs
uid_t cruid = 0, ceuid = 0, csuid = 0;
if (getresuid(&cruid, &ceuid, &csuid) != 0) {
XrdSysPriv::fgMutex.UnLock();
return XSPERR(errno);
}
// Get GIDs
uid_t crgid = 0, cegid = 0, csgid = 0;
if (getresgid(&crgid, &cegid, &csgid) != 0) {
XrdSysPriv::fgMutex.UnLock();
return XSPERR(errno);
}
// Restore privileges, if needed
if (ceuid && XrdSysPriv::Restore(0) != 0) {
XrdSysPriv::fgMutex.UnLock();
return XSPERR(errno);
}
// Act only if needed
if (newgid != cegid || newgid != crgid) {
// Set newgid as GID, all levels
if (setresgid(newgid, newgid, newgid) != 0) {
XrdSysPriv::fgMutex.UnLock();
return XSPERR(errno);
}
// Get GIDs
uid_t rgid = 0, egid = 0, sgid = 0;
if (getresgid(&rgid, &egid, &sgid) != 0) {
XrdSysPriv::fgMutex.UnLock();
return XSPERR(errno);
}
// Make sure the new GIDs are all equal to the one asked
if (rgid != newgid || egid != newgid) {
XrdSysPriv::fgMutex.UnLock();
return XSPERR(errno);
}
}
// Act only if needed
if (newuid != ceuid || newuid != cruid) {
// Set newuid as UID, all levels
if (setresuid(newuid, newuid, newuid) != 0) {
XrdSysPriv::fgMutex.UnLock();
return XSPERR(errno);
}
// Get UIDs
uid_t ruid = 0, euid = 0, suid = 0;
if (getresuid(&ruid, &euid, &suid) != 0) {
XrdSysPriv::fgMutex.UnLock();
return XSPERR(errno);
}
// Make sure the new UIDs are all equal to the one asked
if (ruid != newuid || euid != newuid) {
XrdSysPriv::fgMutex.UnLock();
return XSPERR(errno);
}
}
#endif
// Release the mutex
XrdSysPriv::fgMutex.UnLock();
// Done
return 0;
}
//______________________________________________________________________________
void XrdSysPriv::DumpUGID(const char *msg)
{
// Dump current entity
#if !defined(WINDOWS)
XrdSysPriv::fgMutex.Lock();
// Get the UIDs
uid_t ruid = 0, euid = 0, suid = 0;
if (getresuid(&ruid, &euid, &suid) != 0)
return;
// Get the GIDs
uid_t rgid = 0, egid = 0, sgid = 0;
if (getresgid(&rgid, &egid, &sgid) != 0)
return;
cout << "XrdSysPriv: " << endl;
cout << "XrdSysPriv: dump values: " << (msg ? msg : "") << endl;
cout << "XrdSysPriv: " << endl;
cout << "XrdSysPriv: real = (" << ruid <<","<< rgid <<")" << endl;
cout << "XrdSysPriv: effective = (" << euid <<","<< egid <<")" << endl;
cout << "XrdSysPriv: saved = (" << suid <<","<< sgid <<")" << endl;
cout << "XrdSysPriv: " << endl;
XrdSysPriv::fgMutex.UnLock();
#endif
}
//
// Guard class
//______________________________________________________________________________
XrdSysPrivGuard::XrdSysPrivGuard(uid_t uid, gid_t gid)
{
// Constructor. Create a guard object for temporarly change to privileges
// of {'uid', 'gid'}
dum = 1;
valid = 0;
Init(uid, gid);
}
//______________________________________________________________________________
XrdSysPrivGuard::XrdSysPrivGuard(const char *usr)
{
// Constructor. Create a guard object for temporarly change to privileges
// of 'usr'
dum = 1;
valid = 0;
#if !defined(WINDOWS)
if (usr && strlen(usr) > 0) {
struct passwd *pw = getpwnam(usr);
if (pw)
Init(pw->pw_uid, pw->pw_gid);
}
#else
if (usr) { }
#endif
}
//______________________________________________________________________________
XrdSysPrivGuard::~XrdSysPrivGuard()
{
// Destructor. Restore state and unlock the global mutex.
if (!dum) {
XrdSysPriv::Restore();
XrdSysPriv::fgMutex.UnLock();
}
}
//______________________________________________________________________________
void XrdSysPrivGuard::Init(uid_t uid, gid_t gid)
{
// Init a change of privileges guard. Act only if superuser.
// The result of initialization can be tested with the Valid() method.
dum = 1;
valid = 1;
// Debug hook
if (XrdSysPriv::fDebug)
XrdSysPriv::DumpUGID("before Init()");
#if !defined(WINDOWS)
XrdSysPriv::fgMutex.Lock();
uid_t ruid = 0, euid = 0, suid = 0;
gid_t rgid = 0, egid = 0, sgid = 0;
if (getresuid(&ruid, &euid, &suid) == 0 &&
getresgid(&rgid, &egid, &sgid) == 0) {
if ((euid != uid) || (egid != gid)) {
if (!ruid) {
// Change temporarly identity
if (XrdSysPriv::ChangeTo(uid, gid) != 0)
valid = 0;
dum = 0;
} else {
// Change requested but not enough privileges
valid = 0;
}
}
} else {
// Something bad happened: memory corruption?
valid = 0;
}
// Unlock if no action
if (dum)
XrdSysPriv::fgMutex.UnLock();
#endif
// Debug hook
if (XrdSysPriv::fDebug)
XrdSysPriv::DumpUGID("after Init()");
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: gconfbackend.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: obo $ $Date: 2006-03-22 09:34:06 $
*
* 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 GCONFBACKEND_HXX_
#define GCONFBACKEND_HXX_
#ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XSCHEMASUPPLIER_HPP_
#include <com/sun/star/configuration/backend/XSingleLayerStratum.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif // _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_
#include <com/sun/star/uno/XComponentContext.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif // _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
//#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
//#include <com/sun/star/lang/XMultiServiceFactory.hpp>
//#endif // _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#ifndef _COM_SUN_STAR_CONFIGURATION_INVALIDBOOTSTRAPFILEEXCEPTION_HPP_
#include <com/sun/star/configuration/InvalidBootstrapFileException.hpp>
#endif
#ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_CANNOTCONNECTEXCEPTION_HPP_
#include <com/sun/star/configuration/backend/CannotConnectException.hpp>
#endif
#ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XBACKENDCHANGESNOTIFIER_HPP_
#include <com/sun/star/configuration/backend/XBackendChangesNotifier.hpp>
#endif
#ifndef _CPPUHELPER_COMPBASE3_HXX_
#include <cppuhelper/compbase3.hxx>
#endif // _CPPUHELPER_COMPBASE3_HXX_
#ifndef INCLUDED_MAP
#include <map>
#define INCLUDED_MAP
#endif
//#ifndef _VOS_THREAD_HXX_
//#include <vos/thread.hxx>
//#endif
#include <gconf/gconf-client.h>
namespace css = com::sun::star ;
namespace uno = css::uno ;
namespace lang = css::lang ;
namespace backend = css::configuration::backend ;
/** Structure containing the mapping between OOffice and Gconf keys.
AlOO specifies whether the key is protected, if key is protected it
can not be over riden in subsequent higher layers
*/
struct keyMapping
{
keyMapping(){};
rtl::OUString mOOName;
rtl::OUString mOOType;
rtl::OUString mGconfName;
sal_Bool mbProtected;
};
typedef keyMapping KeyMappingInfo;
typedef std::multimap<rtl::OUString, KeyMappingInfo> KeyMappingTable;
/*Time Stamp mapping table used to store timestamps of updated components
when a notification is recieved. It is needed as you cannot access gconf key
timestamps via the Gconf api */
typedef std::multimap<rtl::OUString, rtl::OUString> TSMappingTable;
//------------------------------------------------------------------------------
/*
class ONotificationThread: public vos::OThread
{
public:
ONotificationThread()
{}
~ONotificationThread()
{
g_main_loop_quit(mLoop);
}
private:
virtual void SAL_CALL onTerminated()
{
delete this;
}
virtual void SAL_CALL run();
GMainLoop* mLoop;
};
*/
//------------------------------------------------------------------------------
typedef cppu::WeakComponentImplHelper3<backend::XSingleLayerStratum,
backend::XBackendChangesNotifier,
lang::XServiceInfo> BackendBase ;
/**
Implements the SingleLayerStratum service for gconf access.
*/
class GconfBackend : public BackendBase {
public :
static GconfBackend* createInstance(const uno::Reference<uno::XComponentContext>& xContext);
// XServiceInfo
virtual rtl::OUString SAL_CALL getImplementationName( )
throw (uno::RuntimeException) ;
virtual sal_Bool SAL_CALL supportsService( const rtl::OUString& aServiceName )
throw (uno::RuntimeException) ;
virtual uno::Sequence<rtl::OUString> SAL_CALL getSupportedServiceNames( )
throw (uno::RuntimeException) ;
/**
Provides the implementation name.
@return implementation name
*/
static rtl::OUString SAL_CALL getBackendName(void) ;
/**
Provides the supported services names
@return service names
*/
static uno::Sequence<rtl::OUString> SAL_CALL getBackendServiceNames(void) ;
/**
Provides the supported component nodes
@return supported component nodes
*/
static uno::Sequence<rtl::OUString> SAL_CALL getSupportedComponents(void) ;
/* returns a GconfClient */
static GConfClient* getGconfClient();
//XSingleLayerStratum
virtual uno::Reference<backend::XLayer> SAL_CALL
getLayer( const rtl::OUString& aLayerId, const rtl::OUString& aTimestamp )
throw (backend::BackendAccessException, lang::IllegalArgumentException) ;
virtual uno::Reference<backend::XUpdatableLayer> SAL_CALL
getUpdatableLayer( const rtl::OUString& aLayerId )
throw (backend::BackendAccessException, lang::NoSupportException,
lang::IllegalArgumentException) ;
// XBackendChangesNotifier
virtual void SAL_CALL addChangesListener(
const uno::Reference<backend::XBackendChangesListener>& xListener,
const rtl::OUString& aComponent)
throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL removeChangesListener(
const uno::Reference<backend::XBackendChangesListener>& xListener,
const rtl::OUString& aComponent)
throw (::com::sun::star::uno::RuntimeException);
//Notify all listener of component change
void notifyListeners(const rtl::OUString& aGconfKey);
protected:
/**
Service constructor from a service factory.
@param xContext component context
*/
GconfBackend(const uno::Reference<uno::XComponentContext>& xContext)
throw (backend::BackendAccessException);
/** Destructor */
~GconfBackend(void) ;
private:
typedef uno::Reference<backend::XBackendChangesListener> ListenerRef;
typedef std::multimap<rtl::OUString,ListenerRef> ListenerList;
/** Build Gconf/OO mapping table */
void initializeMappingTable ();
/** The component context */
uno::Reference<uno::XComponentContext> m_xContext;
/** Mutex for reOOurces protection */
osl::Mutex mMutex ;
KeyMappingTable mKeyMap;
/** List of component TimeStamps */
TSMappingTable mTSMap;
static GconfBackend* mInstance;
/** List of listener */
ListenerList mListenerList;
/**Connection to Gconf */
static GConfClient* mClient;
// ONotificationThread* mNotificationThread;
} ;
#endif // CONFIGMGR_LOCALBE_LOCALSINGLESTRATUM_HXX_
<commit_msg>INTEGRATION: CWS kdesettings3 (1.6.46); FILE MERGED 2006/07/21 12:53:49 kendy 1.6.46.1: #i66204# Don't link with KDE libraries in Gnome (and v.v.)<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: gconfbackend.hxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: ihi $ $Date: 2006-08-04 12:29:03 $
*
* 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 GCONFBACKEND_HXX_
#define GCONFBACKEND_HXX_
#ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XSCHEMASUPPLIER_HPP_
#include <com/sun/star/configuration/backend/XSingleLayerStratum.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif // _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_
#include <com/sun/star/uno/XComponentContext.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif // _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
//#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
//#include <com/sun/star/lang/XMultiServiceFactory.hpp>
//#endif // _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#ifndef _COM_SUN_STAR_CONFIGURATION_INVALIDBOOTSTRAPFILEEXCEPTION_HPP_
#include <com/sun/star/configuration/InvalidBootstrapFileException.hpp>
#endif
#ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_CANNOTCONNECTEXCEPTION_HPP_
#include <com/sun/star/configuration/backend/CannotConnectException.hpp>
#endif
#ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XBACKENDCHANGESNOTIFIER_HPP_
#include <com/sun/star/configuration/backend/XBackendChangesNotifier.hpp>
#endif
#ifndef _CPPUHELPER_COMPBASE3_HXX_
#include <cppuhelper/compbase3.hxx>
#endif // _CPPUHELPER_COMPBASE3_HXX_
#ifndef INCLUDED_MAP
#include <map>
#define INCLUDED_MAP
#endif
//#ifndef _VOS_THREAD_HXX_
//#include <vos/thread.hxx>
//#endif
#include <gconf/gconf-client.h>
namespace css = com::sun::star ;
namespace uno = css::uno ;
namespace lang = css::lang ;
namespace backend = css::configuration::backend ;
/** Structure containing the mapping between OOffice and Gconf keys.
AlOO specifies whether the key is protected, if key is protected it
can not be over riden in subsequent higher layers
*/
struct keyMapping
{
keyMapping(){};
rtl::OUString mOOName;
rtl::OUString mOOType;
rtl::OUString mGconfName;
sal_Bool mbProtected;
};
typedef keyMapping KeyMappingInfo;
typedef std::multimap<rtl::OUString, KeyMappingInfo> KeyMappingTable;
/*Time Stamp mapping table used to store timestamps of updated components
when a notification is recieved. It is needed as you cannot access gconf key
timestamps via the Gconf api */
typedef std::multimap<rtl::OUString, rtl::OUString> TSMappingTable;
//------------------------------------------------------------------------------
/*
class ONotificationThread: public vos::OThread
{
public:
ONotificationThread()
{}
~ONotificationThread()
{
g_main_loop_quit(mLoop);
}
private:
virtual void SAL_CALL onTerminated()
{
delete this;
}
virtual void SAL_CALL run();
GMainLoop* mLoop;
};
*/
//------------------------------------------------------------------------------
typedef cppu::WeakComponentImplHelper3<backend::XSingleLayerStratum,
backend::XBackendChangesNotifier,
lang::XServiceInfo> BackendBase ;
/**
Implements the SingleLayerStratum service for gconf access.
*/
class GconfBackend : public BackendBase {
public :
static GconfBackend* createInstance(const uno::Reference<uno::XComponentContext>& xContext);
// XServiceInfo
virtual rtl::OUString SAL_CALL getImplementationName( )
throw (uno::RuntimeException) ;
virtual sal_Bool SAL_CALL supportsService( const rtl::OUString& aServiceName )
throw (uno::RuntimeException) ;
virtual uno::Sequence<rtl::OUString> SAL_CALL getSupportedServiceNames( )
throw (uno::RuntimeException) ;
/**
Provides the implementation name.
@return implementation name
*/
static rtl::OUString SAL_CALL getBackendName(void) ;
/**
Provides the supported services names
@return service names
*/
static uno::Sequence<rtl::OUString> SAL_CALL getBackendServiceNames(void) ;
/* returns a GconfClient */
static GConfClient* getGconfClient();
//XSingleLayerStratum
virtual uno::Reference<backend::XLayer> SAL_CALL
getLayer( const rtl::OUString& aLayerId, const rtl::OUString& aTimestamp )
throw (backend::BackendAccessException, lang::IllegalArgumentException) ;
virtual uno::Reference<backend::XUpdatableLayer> SAL_CALL
getUpdatableLayer( const rtl::OUString& aLayerId )
throw (backend::BackendAccessException, lang::NoSupportException,
lang::IllegalArgumentException) ;
// XBackendChangesNotifier
virtual void SAL_CALL addChangesListener(
const uno::Reference<backend::XBackendChangesListener>& xListener,
const rtl::OUString& aComponent)
throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL removeChangesListener(
const uno::Reference<backend::XBackendChangesListener>& xListener,
const rtl::OUString& aComponent)
throw (::com::sun::star::uno::RuntimeException);
//Notify all listener of component change
void notifyListeners(const rtl::OUString& aGconfKey);
protected:
/**
Service constructor from a service factory.
@param xContext component context
*/
GconfBackend(const uno::Reference<uno::XComponentContext>& xContext)
throw (backend::BackendAccessException);
/** Destructor */
~GconfBackend(void) ;
private:
typedef uno::Reference<backend::XBackendChangesListener> ListenerRef;
typedef std::multimap<rtl::OUString,ListenerRef> ListenerList;
/** Build Gconf/OO mapping table */
void initializeMappingTable ();
/** The component context */
uno::Reference<uno::XComponentContext> m_xContext;
/** Mutex for reOOurces protection */
osl::Mutex mMutex ;
KeyMappingTable mKeyMap;
/** List of component TimeStamps */
TSMappingTable mTSMap;
static GconfBackend* mInstance;
/** List of listener */
ListenerList mListenerList;
/**Connection to Gconf */
static GConfClient* mClient;
// ONotificationThread* mNotificationThread;
} ;
#endif // CONFIGMGR_LOCALBE_LOCALSINGLESTRATUM_HXX_
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2014 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
//------------------------------------------------------------------------------
//
//
//------------------------------------------------------------------------------
#include "dali.h"
#include <dali-toolkit/dali-toolkit.h>
#include <dali-toolkit/public-api/builder/builder.h>
#include <dali-toolkit/public-api/builder/tree-node.h>
#include <dali-toolkit/public-api/builder/json-parser.h>
#include <map>
#include <string>
#include <fstream>
#include <streambuf>
#include <sstream>
#include <boost/scoped_ptr.hpp>
#include <dirent.h>
#include <stdio.h>
//#include <boost/regex.hpp>
#include "sys/stat.h"
#include <ctime>
#include <dali/integration-api/debug.h>
#include "../shared/view.h"
#define TOKEN_STRING(x) #x
using namespace Dali;
using namespace Dali::Toolkit;
namespace
{
const char* BACKGROUND_IMAGE( "" );
const char* TOOLBAR_IMAGE( DALI_IMAGE_DIR "top-bar.png" );
const char* EDIT_IMAGE( DALI_IMAGE_DIR "icon-change.png" );
std::string USER_DIRECTORY;
std::string JSON_BROKEN(" \
{ \
'stage': \
[ \
{ \
'type':'TextView', \
'size': [50,50,1], \
'parent-origin': 'CENTER', \
'text':'COULD NOT LOAD JSON FILE' \
} \
] \
} \
");
std::string ReplaceQuotes(const std::string &single_quoted)
{
std::string s(single_quoted);
// wrong as no embedded quote but had regex link problems
std::replace(s.begin(), s.end(), '\'', '"');
return s;
}
std::string GetFileContents(const std::string &fn)
{
std::ifstream t(fn.c_str());
return std::string((std::istreambuf_iterator<char>(t)),
std::istreambuf_iterator<char>());
};
typedef std::vector<std::string> FileList;
void DirectoryFileList(const std::string& directory, FileList& files)
{
DIR *d;
struct dirent *dir;
d = opendir(directory.c_str());
if (d)
{
while ((dir = readdir(d)) != NULL)
{
if (dir->d_type == DT_REG)
{
files.push_back( directory + std::string(dir->d_name) );
}
}
closedir(d);
}
}
void DirectoryFilesByType(const std::string& dir, const std::string& fileType /* ie "json" */, FileList& files)
{
typedef FileList Collection;
typedef FileList::iterator Iter;
Collection allFiles;
DirectoryFileList(dir, allFiles);
for(Iter iter = allFiles.begin(); iter != allFiles.end(); ++iter)
{
size_t pos = (*iter).rfind( '.' );
if( pos != std::string::npos )
{
if( (*iter).substr( pos+1 ) == fileType )
{
files.push_back( (*iter) );
}
}
}
}
const std::string ShortName( const std::string& name )
{
size_t pos = name.rfind( '/' );
if( pos != std::string::npos )
{
return name.substr( pos );
}
else
{
return name;
}
}
static Vector3 SetItemSize(unsigned int numberOfColumns, float layoutWidth, float sideMargin, float columnSpacing)
{
return Vector3(layoutWidth, 50, 1);
}
//------------------------------------------------------------------------------
//
//
//
//------------------------------------------------------------------------------
class FileWatcher
{
public:
FileWatcher(void);
~FileWatcher(void);
explicit FileWatcher(const std::string &fn) { SetFilename(fn) ; };
void SetFilename(const std::string &fn);
std::string GetFilename() const;
bool FileHasChanged(void);
std::string GetFileContents(void) const { return ::GetFileContents(mstringPath) ; };
private:
// compiler does
// FileWatcher(const FileWatcher&);
// FileWatcher &operator=(const FileWatcher &);
std::time_t mLastTime;
std::string mstringPath;
};
FileWatcher::FileWatcher(void) : mLastTime(0)
{
}
bool FileWatcher::FileHasChanged(void)
{
struct stat buf;
if(0 != stat(mstringPath.c_str(), &buf))
{
return false;
}
else
{
if(buf.st_mtime > mLastTime)
{
mLastTime = buf.st_mtime;
return true;
}
else
{
mLastTime = buf.st_mtime;
return false;
}
}
return false;
}
FileWatcher::~FileWatcher()
{
}
void FileWatcher::SetFilename(const std::string &fn)
{
mstringPath = fn;
FileHasChanged(); // update last time
}
std::string FileWatcher::GetFilename(void) const
{
return mstringPath;
}
} // anon namespace
//------------------------------------------------------------------------------
//
//
//
//------------------------------------------------------------------------------
class ExampleApp : public ConnectionTracker, public Toolkit::ItemFactory
{
public:
ExampleApp(Application &app) : mApp(app)
{
app.InitSignal().Connect(this, &ExampleApp::Create);
}
~ExampleApp() {}
public:
void SetTitle(const std::string& title)
{
if(!mTitleActor)
{
mTitleActor = TextView::New();
// Add title to the tool bar.
mToolBar.AddControl( mTitleActor, DemoHelper::DEFAULT_VIEW_STYLE.mToolBarTitlePercentage, Alignment::HorizontalCenter );
}
Font font = Font::New();
mTitleActor.SetText( title );
mTitleActor.SetSize( font.MeasureText( title ) );
mTitleActor.SetStyleToCurrentText(DemoHelper::GetDefaultTextStyle());
}
bool OnToolSelectLayout( Toolkit::Button button )
{
bool on = mItemView.IsVisible();
if( on )
{
LeaveSelection();
}
else
{
EnterSelection();
}
return true;
}
void LeaveSelection()
{
}
void EnterSelection()
{
Stage stage = Stage::GetCurrent();
if( mItemView )
{
stage.Remove( mItemView );
}
mFiles.clear();
mItemView = ItemView::New(*this);
stage.Add( mItemView );
mItemView.SetParentOrigin(ParentOrigin::CENTER);
mItemView.SetAnchorPoint(AnchorPoint::CENTER);
mGridLayout = GridLayout::New();
mGridLayout->SetNumberOfColumns(1);
mGridLayout->SetItemSizeFunction(SetItemSize);
mGridLayout->SetTopMargin(DemoHelper::DEFAULT_VIEW_STYLE.mToolBarHeight);
mItemView.AddLayout(*mGridLayout);
Vector3 size(stage.GetSize());
mItemView.ActivateLayout(0, size, 0.0f/*immediate*/);
mItemView.SetKeyboardFocusable( true );
mFiles.clear();
FileList files;
if( USER_DIRECTORY.size() )
{
DirectoryFilesByType( USER_DIRECTORY, "json", files );
}
else
{
DirectoryFilesByType( DALI_SCRIPT_DIR, "json", files );
}
std::sort(files.begin(), files.end());
ItemId itemId = 0;
for(FileList::iterator iter = files.begin(); iter != files.end(); ++iter)
{
JsonParser parser = JsonParser::New();
std::string data( GetFileContents( *iter ) );
parser.Parse( data );
if( parser.ParseError() )
{
std::cout << "Parser Error:" << *iter << std::endl;
std::cout << parser.GetErrorLineNumber() << "(" << parser.GetErrorColumn() << "):" << parser.GetErrorDescription() << std::endl;
exit(1);
}
if( parser.GetRoot() )
{
if( const TreeNode* node = parser.GetRoot()->Find("stage") )
{
// only those with a stage section
if( node->Size() )
{
mFiles.push_back( *iter );
mItemView.InsertItem( Item(itemId,
MenuItem( ShortName( *iter ) ) ),
0.5f );
itemId++;
}
else
{
std::cout << "Ignored file (stage has no nodes?):" << *iter << std::endl;
}
}
else
{
std::cout << "Ignored file (no stage section):" << *iter << std::endl;
}
}
}
mTapDetector = TapGestureDetector::New();
for( unsigned int i = 0u; i < mItemView.GetChildCount(); ++i )
{
mTapDetector.Attach( mItemView.GetChildAt(i) );
}
mTapDetector.DetectedSignal().Connect( this, &ExampleApp::OnTap );
// Display item view on the stage
stage.Add( mItemView );
mItemView.SetVisible( true );
mBuilderLayer.SetVisible( false );
SetTitle("Select");
// Itemview renderes the previous items unless its scrolled. Not sure why at the moment so we force a scroll
mItemView.ScrollToItem(0, 0);
}
void ExitSelection()
{
mTapDetector.Reset();
mItemView.SetVisible( false );
mBuilderLayer.SetVisible( true );
SetTitle("View");
}
void OnTap( Actor actor, TapGesture tap )
{
ItemId id = mItemView.GetItemId( actor );
LoadFromFileList( id );
}
Actor MenuItem(const std::string& text)
{
TextView t = TextView::New();
t.SetMarkupProcessingEnabled(true);
int size = static_cast<int>(DemoHelper::ScalePointSize(6));
std::ostringstream fontString;
fontString << "<font size="<< size <<">"<< ShortName( text ) << "</font>";
t.SetText( fontString.str() );
t.SetTextAlignment( Alignment::HorizontalLeft );
return t;
}
bool OnTimer()
{
if( mFileWatcher.FileHasChanged() )
{
LoadFromFile( mFileWatcher.GetFilename() );
}
return true;
}
void ReloadJsonFile(const std::string& filename, Builder& builder, Layer& layer)
{
Stage stage = Stage::GetCurrent();
builder = Builder::New();
PropertyValueMap defaultDirs;
defaultDirs[ TOKEN_STRING(DALI_IMAGE_DIR) ] = DALI_IMAGE_DIR;
defaultDirs[ TOKEN_STRING(DALI_MODEL_DIR) ] = DALI_MODEL_DIR;
defaultDirs[ TOKEN_STRING(DALI_SCRIPT_DIR) ] = DALI_SCRIPT_DIR;
builder.AddConstants( defaultDirs );
// render tasks may have been setup last load so remove them
RenderTaskList taskList = stage.GetRenderTaskList();
if( taskList.GetTaskCount() > 1 )
{
typedef std::vector<RenderTask> Collection;
typedef Collection::iterator ColIter;
Collection tasks;
for(unsigned int i = 1; i < taskList.GetTaskCount(); ++i)
{
tasks.push_back( taskList.GetTask(i) );
}
for(ColIter iter = tasks.begin(); iter != tasks.end(); ++iter)
{
taskList.RemoveTask(*iter);
}
RenderTask defaultTask = taskList.GetTask(0);
defaultTask.SetSourceActor( stage.GetRootLayer() );
defaultTask.SetTargetFrameBuffer( FrameBufferImage() );
}
unsigned int numChildren = layer.GetChildCount();
for(unsigned int i=0; i<numChildren; ++i)
{
layer.Remove( layer.GetChildAt(0) );
}
std::string data(GetFileContents(filename));
try
{
builder.LoadFromString(data);
}
catch(...)
{
builder.LoadFromString(ReplaceQuotes(JSON_BROKEN));
}
builder.AddActors( layer );
}
void LoadFromFileList( size_t index )
{
if( index < mFiles.size())
{
const std::string& name = mFiles[index];
mFileWatcher.SetFilename( name );
LoadFromFile( name );
}
}
void LoadFromFile( const std::string& name )
{
ReloadJsonFile( name, mBuilder, mBuilderLayer );
// do this here as GetCurrentSize()
mBuilderLayer.SetParentOrigin(ParentOrigin::CENTER);
mBuilderLayer.SetAnchorPoint(AnchorPoint::CENTER);
Dali::Vector3 size = Stage::GetCurrent().GetRootLayer().GetCurrentSize();
size.y -= DemoHelper::DEFAULT_VIEW_STYLE.mToolBarHeight;
mBuilderLayer.SetSize( size );
mBuilderLayer.LowerToBottom();
Stage::GetCurrent().GetRootLayer().RaiseToTop();
ExitSelection();
}
void Create(Application& app)
{
Stage stage = Stage::GetCurrent();
Stage::GetCurrent().KeyEventSignal().Connect(this, &ExampleApp::OnKeyEvent);
Layer contents = DemoHelper::CreateView( app,
mView,
mToolBar,
BACKGROUND_IMAGE,
TOOLBAR_IMAGE,
"" );
SetTitle("Builder");
mBuilderLayer = Layer::New();
stage.GetRootLayer().Add(mBuilderLayer);
// Create an edit mode button. (left of toolbar)
Toolkit::PushButton editButton = Toolkit::PushButton::New();
editButton.SetBackgroundImage( Image::New( EDIT_IMAGE ) );
editButton.ClickedSignal().Connect( this, &ExampleApp::OnToolSelectLayout);
editButton.SetLeaveRequired( true );
mToolBar.AddControl( editButton, DemoHelper::DEFAULT_VIEW_STYLE.mToolBarButtonPercentage, Toolkit::Alignment::HorizontalLeft, DemoHelper::DEFAULT_MODE_SWITCH_PADDING );
EnterSelection();
mTimer = Timer::New( 500 ); // ms
mTimer.TickSignal().Connect( this, &ExampleApp::OnTimer);
mTimer.Start();
} // Create(app)
virtual unsigned int GetNumberOfItems()
{
return mFiles.size();
}
virtual Actor NewItem(unsigned int itemId)
{
DALI_ASSERT_DEBUG( itemId < mFiles.size() );
return MenuItem( ShortName( mFiles[itemId] ) );
}
/**
* Main key event handler
*/
void OnKeyEvent(const KeyEvent& event)
{
if(event.state == KeyEvent::Down)
{
if( IsKey( event, Dali::DALI_KEY_ESCAPE) || IsKey( event, Dali::DALI_KEY_BACK) )
{
mApp.Quit();
}
}
}
private:
Application& mApp;
GridLayoutPtr mGridLayout;
ItemView mItemView;
Toolkit::View mView;
unsigned int mOrientation;
Toolkit::ToolBar mToolBar;
TextView mTitleActor; ///< The Toolbar's Title.
Layer mBuilderLayer;
Toolkit::Popup mMenu;
TapGestureDetector mTapDetector;
// builder
Builder mBuilder;
FileList mFiles;
FileWatcher mFileWatcher;
Timer mTimer;
};
//------------------------------------------------------------------------------
//
//
//
//------------------------------------------------------------------------------
int main(int argc, char **argv)
{
if(argc > 2)
{
if(strcmp(argv[1], "-f") == 0)
{
USER_DIRECTORY = argv[2];
}
}
Application app = Application::New(&argc, &argv);
ExampleApp dali_app(app);
app.MainLoop();
return 0;
}
<commit_msg>(Builder) Back button goes back to main menu rather than exit<commit_after>/*
* Copyright (c) 2014 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
//------------------------------------------------------------------------------
//
//
//------------------------------------------------------------------------------
#include "dali.h"
#include <dali-toolkit/dali-toolkit.h>
#include <dali-toolkit/public-api/builder/builder.h>
#include <dali-toolkit/public-api/builder/tree-node.h>
#include <dali-toolkit/public-api/builder/json-parser.h>
#include <map>
#include <string>
#include <fstream>
#include <streambuf>
#include <sstream>
#include <boost/scoped_ptr.hpp>
#include <dirent.h>
#include <stdio.h>
//#include <boost/regex.hpp>
#include "sys/stat.h"
#include <ctime>
#include <dali/integration-api/debug.h>
#include "../shared/view.h"
#define TOKEN_STRING(x) #x
using namespace Dali;
using namespace Dali::Toolkit;
namespace
{
const char* BACKGROUND_IMAGE( "" );
const char* TOOLBAR_IMAGE( DALI_IMAGE_DIR "top-bar.png" );
const char* EDIT_IMAGE( DALI_IMAGE_DIR "icon-change.png" );
std::string USER_DIRECTORY;
std::string JSON_BROKEN(" \
{ \
'stage': \
[ \
{ \
'type':'TextView', \
'size': [50,50,1], \
'parent-origin': 'CENTER', \
'text':'COULD NOT LOAD JSON FILE' \
} \
] \
} \
");
std::string ReplaceQuotes(const std::string &single_quoted)
{
std::string s(single_quoted);
// wrong as no embedded quote but had regex link problems
std::replace(s.begin(), s.end(), '\'', '"');
return s;
}
std::string GetFileContents(const std::string &fn)
{
std::ifstream t(fn.c_str());
return std::string((std::istreambuf_iterator<char>(t)),
std::istreambuf_iterator<char>());
};
typedef std::vector<std::string> FileList;
void DirectoryFileList(const std::string& directory, FileList& files)
{
DIR *d;
struct dirent *dir;
d = opendir(directory.c_str());
if (d)
{
while ((dir = readdir(d)) != NULL)
{
if (dir->d_type == DT_REG)
{
files.push_back( directory + std::string(dir->d_name) );
}
}
closedir(d);
}
}
void DirectoryFilesByType(const std::string& dir, const std::string& fileType /* ie "json" */, FileList& files)
{
typedef FileList Collection;
typedef FileList::iterator Iter;
Collection allFiles;
DirectoryFileList(dir, allFiles);
for(Iter iter = allFiles.begin(); iter != allFiles.end(); ++iter)
{
size_t pos = (*iter).rfind( '.' );
if( pos != std::string::npos )
{
if( (*iter).substr( pos+1 ) == fileType )
{
files.push_back( (*iter) );
}
}
}
}
const std::string ShortName( const std::string& name )
{
size_t pos = name.rfind( '/' );
if( pos != std::string::npos )
{
return name.substr( pos );
}
else
{
return name;
}
}
static Vector3 SetItemSize(unsigned int numberOfColumns, float layoutWidth, float sideMargin, float columnSpacing)
{
return Vector3(layoutWidth, 50, 1);
}
//------------------------------------------------------------------------------
//
//
//
//------------------------------------------------------------------------------
class FileWatcher
{
public:
FileWatcher(void);
~FileWatcher(void);
explicit FileWatcher(const std::string &fn) { SetFilename(fn) ; };
void SetFilename(const std::string &fn);
std::string GetFilename() const;
bool FileHasChanged(void);
std::string GetFileContents(void) const { return ::GetFileContents(mstringPath) ; };
private:
// compiler does
// FileWatcher(const FileWatcher&);
// FileWatcher &operator=(const FileWatcher &);
std::time_t mLastTime;
std::string mstringPath;
};
FileWatcher::FileWatcher(void) : mLastTime(0)
{
}
bool FileWatcher::FileHasChanged(void)
{
struct stat buf;
if(0 != stat(mstringPath.c_str(), &buf))
{
return false;
}
else
{
if(buf.st_mtime > mLastTime)
{
mLastTime = buf.st_mtime;
return true;
}
else
{
mLastTime = buf.st_mtime;
return false;
}
}
return false;
}
FileWatcher::~FileWatcher()
{
}
void FileWatcher::SetFilename(const std::string &fn)
{
mstringPath = fn;
FileHasChanged(); // update last time
}
std::string FileWatcher::GetFilename(void) const
{
return mstringPath;
}
} // anon namespace
//------------------------------------------------------------------------------
//
//
//
//------------------------------------------------------------------------------
class ExampleApp : public ConnectionTracker, public Toolkit::ItemFactory
{
public:
ExampleApp(Application &app) : mApp(app)
{
app.InitSignal().Connect(this, &ExampleApp::Create);
}
~ExampleApp() {}
public:
void SetTitle(const std::string& title)
{
if(!mTitleActor)
{
mTitleActor = TextView::New();
// Add title to the tool bar.
mToolBar.AddControl( mTitleActor, DemoHelper::DEFAULT_VIEW_STYLE.mToolBarTitlePercentage, Alignment::HorizontalCenter );
}
Font font = Font::New();
mTitleActor.SetText( title );
mTitleActor.SetSize( font.MeasureText( title ) );
mTitleActor.SetStyleToCurrentText(DemoHelper::GetDefaultTextStyle());
}
bool OnToolSelectLayout( Toolkit::Button button )
{
bool on = mItemView.IsVisible();
if( on )
{
LeaveSelection();
}
else
{
EnterSelection();
}
return true;
}
void LeaveSelection()
{
}
void EnterSelection()
{
Stage stage = Stage::GetCurrent();
if( mItemView )
{
stage.Remove( mItemView );
}
mFiles.clear();
mItemView = ItemView::New(*this);
stage.Add( mItemView );
mItemView.SetParentOrigin(ParentOrigin::CENTER);
mItemView.SetAnchorPoint(AnchorPoint::CENTER);
mGridLayout = GridLayout::New();
mGridLayout->SetNumberOfColumns(1);
mGridLayout->SetItemSizeFunction(SetItemSize);
mGridLayout->SetTopMargin(DemoHelper::DEFAULT_VIEW_STYLE.mToolBarHeight);
mItemView.AddLayout(*mGridLayout);
Vector3 size(stage.GetSize());
mItemView.ActivateLayout(0, size, 0.0f/*immediate*/);
mItemView.SetKeyboardFocusable( true );
mFiles.clear();
FileList files;
if( USER_DIRECTORY.size() )
{
DirectoryFilesByType( USER_DIRECTORY, "json", files );
}
else
{
DirectoryFilesByType( DALI_SCRIPT_DIR, "json", files );
}
std::sort(files.begin(), files.end());
ItemId itemId = 0;
for(FileList::iterator iter = files.begin(); iter != files.end(); ++iter)
{
JsonParser parser = JsonParser::New();
std::string data( GetFileContents( *iter ) );
parser.Parse( data );
if( parser.ParseError() )
{
std::cout << "Parser Error:" << *iter << std::endl;
std::cout << parser.GetErrorLineNumber() << "(" << parser.GetErrorColumn() << "):" << parser.GetErrorDescription() << std::endl;
exit(1);
}
if( parser.GetRoot() )
{
if( const TreeNode* node = parser.GetRoot()->Find("stage") )
{
// only those with a stage section
if( node->Size() )
{
mFiles.push_back( *iter );
mItemView.InsertItem( Item(itemId,
MenuItem( ShortName( *iter ) ) ),
0.5f );
itemId++;
}
else
{
std::cout << "Ignored file (stage has no nodes?):" << *iter << std::endl;
}
}
else
{
std::cout << "Ignored file (no stage section):" << *iter << std::endl;
}
}
}
mTapDetector = TapGestureDetector::New();
for( unsigned int i = 0u; i < mItemView.GetChildCount(); ++i )
{
mTapDetector.Attach( mItemView.GetChildAt(i) );
}
mTapDetector.DetectedSignal().Connect( this, &ExampleApp::OnTap );
// Display item view on the stage
stage.Add( mItemView );
mItemView.SetVisible( true );
mBuilderLayer.SetVisible( false );
SetTitle("Select");
// Itemview renderes the previous items unless its scrolled. Not sure why at the moment so we force a scroll
mItemView.ScrollToItem(0, 0);
}
void ExitSelection()
{
mTapDetector.Reset();
mItemView.SetVisible( false );
mBuilderLayer.SetVisible( true );
SetTitle("View");
}
void OnTap( Actor actor, TapGesture tap )
{
ItemId id = mItemView.GetItemId( actor );
LoadFromFileList( id );
}
Actor MenuItem(const std::string& text)
{
TextView t = TextView::New();
t.SetMarkupProcessingEnabled(true);
int size = static_cast<int>(DemoHelper::ScalePointSize(6));
std::ostringstream fontString;
fontString << "<font size="<< size <<">"<< ShortName( text ) << "</font>";
t.SetText( fontString.str() );
t.SetTextAlignment( Alignment::HorizontalLeft );
return t;
}
bool OnTimer()
{
if( mFileWatcher.FileHasChanged() )
{
LoadFromFile( mFileWatcher.GetFilename() );
}
return true;
}
void ReloadJsonFile(const std::string& filename, Builder& builder, Layer& layer)
{
Stage stage = Stage::GetCurrent();
builder = Builder::New();
PropertyValueMap defaultDirs;
defaultDirs[ TOKEN_STRING(DALI_IMAGE_DIR) ] = DALI_IMAGE_DIR;
defaultDirs[ TOKEN_STRING(DALI_MODEL_DIR) ] = DALI_MODEL_DIR;
defaultDirs[ TOKEN_STRING(DALI_SCRIPT_DIR) ] = DALI_SCRIPT_DIR;
builder.AddConstants( defaultDirs );
// render tasks may have been setup last load so remove them
RenderTaskList taskList = stage.GetRenderTaskList();
if( taskList.GetTaskCount() > 1 )
{
typedef std::vector<RenderTask> Collection;
typedef Collection::iterator ColIter;
Collection tasks;
for(unsigned int i = 1; i < taskList.GetTaskCount(); ++i)
{
tasks.push_back( taskList.GetTask(i) );
}
for(ColIter iter = tasks.begin(); iter != tasks.end(); ++iter)
{
taskList.RemoveTask(*iter);
}
RenderTask defaultTask = taskList.GetTask(0);
defaultTask.SetSourceActor( stage.GetRootLayer() );
defaultTask.SetTargetFrameBuffer( FrameBufferImage() );
}
unsigned int numChildren = layer.GetChildCount();
for(unsigned int i=0; i<numChildren; ++i)
{
layer.Remove( layer.GetChildAt(0) );
}
std::string data(GetFileContents(filename));
try
{
builder.LoadFromString(data);
}
catch(...)
{
builder.LoadFromString(ReplaceQuotes(JSON_BROKEN));
}
builder.AddActors( layer );
}
void LoadFromFileList( size_t index )
{
if( index < mFiles.size())
{
const std::string& name = mFiles[index];
mFileWatcher.SetFilename( name );
LoadFromFile( name );
}
}
void LoadFromFile( const std::string& name )
{
ReloadJsonFile( name, mBuilder, mBuilderLayer );
// do this here as GetCurrentSize()
mBuilderLayer.SetParentOrigin(ParentOrigin::CENTER);
mBuilderLayer.SetAnchorPoint(AnchorPoint::CENTER);
Dali::Vector3 size = Stage::GetCurrent().GetRootLayer().GetCurrentSize();
size.y -= DemoHelper::DEFAULT_VIEW_STYLE.mToolBarHeight;
mBuilderLayer.SetSize( size );
mBuilderLayer.LowerToBottom();
Stage::GetCurrent().GetRootLayer().RaiseToTop();
ExitSelection();
}
void Create(Application& app)
{
Stage stage = Stage::GetCurrent();
Stage::GetCurrent().KeyEventSignal().Connect(this, &ExampleApp::OnKeyEvent);
Layer contents = DemoHelper::CreateView( app,
mView,
mToolBar,
BACKGROUND_IMAGE,
TOOLBAR_IMAGE,
"" );
SetTitle("Builder");
mBuilderLayer = Layer::New();
stage.GetRootLayer().Add(mBuilderLayer);
// Create an edit mode button. (left of toolbar)
Toolkit::PushButton editButton = Toolkit::PushButton::New();
editButton.SetBackgroundImage( Image::New( EDIT_IMAGE ) );
editButton.ClickedSignal().Connect( this, &ExampleApp::OnToolSelectLayout);
editButton.SetLeaveRequired( true );
mToolBar.AddControl( editButton, DemoHelper::DEFAULT_VIEW_STYLE.mToolBarButtonPercentage, Toolkit::Alignment::HorizontalLeft, DemoHelper::DEFAULT_MODE_SWITCH_PADDING );
EnterSelection();
mTimer = Timer::New( 500 ); // ms
mTimer.TickSignal().Connect( this, &ExampleApp::OnTimer);
mTimer.Start();
} // Create(app)
virtual unsigned int GetNumberOfItems()
{
return mFiles.size();
}
virtual Actor NewItem(unsigned int itemId)
{
DALI_ASSERT_DEBUG( itemId < mFiles.size() );
return MenuItem( ShortName( mFiles[itemId] ) );
}
/**
* Main key event handler
*/
void OnKeyEvent(const KeyEvent& event)
{
if(event.state == KeyEvent::Down)
{
if( IsKey( event, Dali::DALI_KEY_ESCAPE) || IsKey( event, Dali::DALI_KEY_BACK) )
{
if ( mItemView.IsVisible() )
{
mApp.Quit();
}
else
{
EnterSelection();
}
}
}
}
private:
Application& mApp;
GridLayoutPtr mGridLayout;
ItemView mItemView;
Toolkit::View mView;
unsigned int mOrientation;
Toolkit::ToolBar mToolBar;
TextView mTitleActor; ///< The Toolbar's Title.
Layer mBuilderLayer;
Toolkit::Popup mMenu;
TapGestureDetector mTapDetector;
// builder
Builder mBuilder;
FileList mFiles;
FileWatcher mFileWatcher;
Timer mTimer;
};
//------------------------------------------------------------------------------
//
//
//
//------------------------------------------------------------------------------
int main(int argc, char **argv)
{
if(argc > 2)
{
if(strcmp(argv[1], "-f") == 0)
{
USER_DIRECTORY = argv[2];
}
}
Application app = Application::New(&argc, &argv);
ExampleApp dali_app(app);
app.MainLoop();
return 0;
}
<|endoftext|> |
<commit_before>//
// Copyright (c) 2015 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// StateManagerGL.h: Defines a class for caching applied OpenGL state
#include "libANGLE/renderer/gl/StateManagerGL.h"
#include "libANGLE/Data.h"
#include "libANGLE/Framebuffer.h"
#include "libANGLE/VertexArray.h"
#include "libANGLE/renderer/gl/FramebufferGL.h"
#include "libANGLE/renderer/gl/FunctionsGL.h"
#include "libANGLE/renderer/gl/ProgramGL.h"
#include "libANGLE/renderer/gl/TextureGL.h"
#include "libANGLE/renderer/gl/VertexArrayGL.h"
namespace rx
{
StateManagerGL::StateManagerGL(const FunctionsGL *functions, const gl::Caps &rendererCaps)
: mFunctions(functions),
mProgram(0),
mVAO(0),
mBuffers(),
mTextureUnitIndex(0),
mTextures(),
mUnpackAlignment(4),
mUnpackRowLength(0),
mFramebuffers(),
mRenderbuffer(0),
mScissor(0, 0, 0, 0),
mViewport(0, 0, 0, 0),
mClearColor(0.0f, 0.0f, 0.0f, 0.0f),
mColorMaskRed(true),
mColorMaskGreen(true),
mColorMaskBlue(true),
mColorMaskAlpha(true),
mClearDepth(1.0f),
mDepthMask(true),
mClearStencil(0),
mStencilMask(static_cast<GLuint>(-1))
{
ASSERT(mFunctions);
mTextures[GL_TEXTURE_2D].resize(rendererCaps.maxCombinedTextureImageUnits);
mTextures[GL_TEXTURE_CUBE_MAP].resize(rendererCaps.maxCombinedTextureImageUnits);
mTextures[GL_TEXTURE_2D_ARRAY].resize(rendererCaps.maxCombinedTextureImageUnits);
mTextures[GL_TEXTURE_3D].resize(rendererCaps.maxCombinedTextureImageUnits);
mFramebuffers[GL_READ_FRAMEBUFFER] = 0;
mFramebuffers[GL_DRAW_FRAMEBUFFER] = 0;
}
void StateManagerGL::useProgram(GLuint program)
{
if (mProgram != program)
{
mProgram = program;
mFunctions->useProgram(mProgram);
}
}
void StateManagerGL::bindVertexArray(GLuint vao)
{
if (mVAO != vao)
{
mVAO = vao;
mFunctions->bindVertexArray(vao);
}
}
void StateManagerGL::bindBuffer(GLenum type, GLuint buffer)
{
if (mBuffers[type] != buffer)
{
mBuffers[type] = buffer;
mFunctions->bindBuffer(type, buffer);
}
}
void StateManagerGL::activeTexture(size_t unit)
{
if (mTextureUnitIndex != unit)
{
mTextureUnitIndex = unit;
mFunctions->activeTexture(GL_TEXTURE0 + mTextureUnitIndex);
}
}
void StateManagerGL::bindTexture(GLenum type, GLuint texture)
{
if (mTextures[type][mTextureUnitIndex] != texture)
{
mTextures[type][mTextureUnitIndex] = texture;
mFunctions->bindTexture(type, texture);
}
}
void StateManagerGL::setPixelUnpackState(GLint alignment, GLint rowLength)
{
if (mUnpackAlignment != alignment)
{
mUnpackAlignment = alignment;
mFunctions->pixelStorei(GL_UNPACK_ALIGNMENT, mUnpackAlignment);
}
if (mUnpackRowLength != rowLength)
{
mUnpackRowLength = rowLength;
mFunctions->pixelStorei(GL_UNPACK_ROW_LENGTH, mUnpackRowLength);
}
}
void StateManagerGL::bindFramebuffer(GLenum type, GLuint framebuffer)
{
if (mFramebuffers[type] != framebuffer)
{
mFramebuffers[type] = framebuffer;
mFunctions->bindFramebuffer(type, framebuffer);
}
}
void StateManagerGL::bindRenderbuffer(GLenum type, GLuint renderbuffer)
{
ASSERT(type == GL_RENDERBUFFER);
if (mRenderbuffer != renderbuffer)
{
mRenderbuffer = renderbuffer;
mFunctions->bindRenderbuffer(type, mRenderbuffer);
}
}
void StateManagerGL::setClearState(const gl::State &state, GLbitfield mask)
{
// Only apply the state required to do a clear
setScissor(state.getScissor());
setViewport(state.getViewport());
if ((mask & GL_COLOR_BUFFER_BIT) != 0)
{
setClearColor(state.getColorClearValue());
const gl::BlendState &blendState = state.getBlendState();
setColorMask(blendState.colorMaskRed, blendState.colorMaskGreen, blendState.colorMaskBlue, blendState.colorMaskAlpha);
}
if ((mask & GL_DEPTH_BUFFER_BIT) != 0)
{
setClearDepth(state.getDepthClearValue());
setDepthMask(state.getDepthStencilState().depthMask);
}
if ((mask & GL_STENCIL_BUFFER_BIT) != 0)
{
setClearStencil(state.getStencilClearValue());
setStencilMask(state.getDepthStencilState().stencilMask);
}
}
gl::Error StateManagerGL::setDrawArraysState(const gl::Data &data, GLint first, GLsizei count)
{
const gl::State &state = *data.state;
const gl::VertexArray *vao = state.getVertexArray();
const VertexArrayGL *vaoGL = GetImplAs<VertexArrayGL>(vao);
vaoGL->syncDrawArraysState(first, count);
bindVertexArray(vaoGL->getVertexArrayID());
return setGenericDrawState(data);
}
gl::Error StateManagerGL::setDrawElementsState(const gl::Data &data, GLsizei count, GLenum type, const GLvoid *indices,
const GLvoid **outIndices)
{
const gl::State &state = *data.state;
const gl::VertexArray *vao = state.getVertexArray();
const VertexArrayGL *vaoGL = GetImplAs<VertexArrayGL>(vao);
gl::Error error = vaoGL->syncDrawElementsState(count, type, indices, outIndices);
if (error.isError())
{
return error;
}
bindVertexArray(vaoGL->getVertexArrayID());
return setGenericDrawState(data);
}
gl::Error StateManagerGL::setGenericDrawState(const gl::Data &data)
{
const gl::State &state = *data.state;
const gl::Caps &caps = *data.caps;
const gl::Program *program = state.getProgram();
const ProgramGL *programGL = GetImplAs<ProgramGL>(program);
useProgram(programGL->getProgramID());
// TODO: Only apply textures referenced by the program.
for (auto textureTypeIter = mTextures.begin(); textureTypeIter != mTextures.end(); textureTypeIter++)
{
GLenum textureType = textureTypeIter->first;
// Determine if this texture type can exist in the source context
bool validTextureType = (textureType == GL_TEXTURE_2D || textureType == GL_TEXTURE_CUBE_MAP ||
(textureType == GL_TEXTURE_2D_ARRAY && data.clientVersion >= 3) ||
(textureType == GL_TEXTURE_3D && data.clientVersion >= 3));
const std::vector<GLuint> &textureVector = textureTypeIter->second;
for (size_t textureUnitIndex = 0; textureUnitIndex < textureVector.size(); textureUnitIndex++)
{
const gl::Texture *texture = nullptr;
bool validTextureUnit = textureUnitIndex < caps.maxCombinedTextureImageUnits;
if (validTextureType && validTextureUnit)
{
texture = state.getSamplerTexture(textureUnitIndex, textureType);
}
if (texture != nullptr)
{
const TextureGL *textureGL = GetImplAs<TextureGL>(texture);
if (mTextures[textureType][textureUnitIndex] != textureGL->getTextureID())
{
activeTexture(textureUnitIndex);
textureGL->syncSamplerState(texture->getSamplerState());
bindTexture(textureType, textureGL->getTextureID());
}
// TODO: apply sampler object if one is bound
}
else
{
if (mTextures[textureType][textureUnitIndex] != 0)
{
activeTexture(textureUnitIndex);
bindTexture(textureType, 0);
}
}
}
}
const gl::Framebuffer *framebuffer = state.getDrawFramebuffer();
const FramebufferGL *framebufferGL = GetImplAs<FramebufferGL>(framebuffer);
bindFramebuffer(GL_DRAW_FRAMEBUFFER, framebufferGL->getFramebufferID());
setScissor(state.getScissor());
setViewport(state.getViewport());
const gl::BlendState &blendState = state.getBlendState();
setColorMask(blendState.colorMaskRed, blendState.colorMaskGreen, blendState.colorMaskBlue, blendState.colorMaskAlpha);
const gl::DepthStencilState &depthStencilState = state.getDepthStencilState();
setDepthMask(depthStencilState.depthMask);
setStencilMask(depthStencilState.stencilMask);
return gl::Error(GL_NO_ERROR);
}
void StateManagerGL::setScissor(const gl::Rectangle &scissor)
{
if (scissor != mScissor)
{
mScissor = scissor;
mFunctions->scissor(mScissor.x, mScissor.y, mScissor.width, mScissor.height);
}
}
void StateManagerGL::setViewport(const gl::Rectangle &viewport)
{
if (viewport != mViewport)
{
mViewport = viewport;
mFunctions->viewport(mViewport.x, mViewport.y, mViewport.width, mViewport.height);
}
}
void StateManagerGL::setClearColor(const gl::ColorF &clearColor)
{
if (mClearColor != clearColor)
{
mClearColor = clearColor;
mFunctions->clearColor(mClearColor.red, mClearColor.green, mClearColor.blue, mClearColor.alpha);
}
}
void StateManagerGL::setColorMask(bool red, bool green, bool blue, bool alpha)
{
if (mColorMaskRed != red || mColorMaskGreen != green || mColorMaskBlue != blue || mColorMaskAlpha != alpha)
{
mColorMaskRed = red;
mColorMaskGreen = green;
mColorMaskBlue = blue;
mColorMaskAlpha = alpha;
mFunctions->colorMask(mColorMaskRed, mColorMaskGreen, mColorMaskBlue, mColorMaskAlpha);
}
}
void StateManagerGL::setClearDepth(float clearDepth)
{
if (mClearDepth != clearDepth)
{
mClearDepth = clearDepth;
mFunctions->clearDepth(mClearDepth);
}
}
void StateManagerGL::setDepthMask(bool mask)
{
if (mDepthMask != mask)
{
mDepthMask = mask;
mFunctions->depthMask(mDepthMask);
}
}
void StateManagerGL::setClearStencil(GLint clearStencil)
{
if (mClearStencil != clearStencil)
{
mClearStencil = clearStencil;
mFunctions->clearStencil(mClearStencil);
}
}
void StateManagerGL::setStencilMask(GLuint mask)
{
if (mStencilMask != mask)
{
mStencilMask = mask;
mFunctions->stencilMask(mStencilMask);
}
}
}
<commit_msg>Always sync the texture sampler state.<commit_after>//
// Copyright (c) 2015 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// StateManagerGL.h: Defines a class for caching applied OpenGL state
#include "libANGLE/renderer/gl/StateManagerGL.h"
#include "libANGLE/Data.h"
#include "libANGLE/Framebuffer.h"
#include "libANGLE/VertexArray.h"
#include "libANGLE/renderer/gl/FramebufferGL.h"
#include "libANGLE/renderer/gl/FunctionsGL.h"
#include "libANGLE/renderer/gl/ProgramGL.h"
#include "libANGLE/renderer/gl/TextureGL.h"
#include "libANGLE/renderer/gl/VertexArrayGL.h"
namespace rx
{
StateManagerGL::StateManagerGL(const FunctionsGL *functions, const gl::Caps &rendererCaps)
: mFunctions(functions),
mProgram(0),
mVAO(0),
mBuffers(),
mTextureUnitIndex(0),
mTextures(),
mUnpackAlignment(4),
mUnpackRowLength(0),
mFramebuffers(),
mRenderbuffer(0),
mScissor(0, 0, 0, 0),
mViewport(0, 0, 0, 0),
mClearColor(0.0f, 0.0f, 0.0f, 0.0f),
mColorMaskRed(true),
mColorMaskGreen(true),
mColorMaskBlue(true),
mColorMaskAlpha(true),
mClearDepth(1.0f),
mDepthMask(true),
mClearStencil(0),
mStencilMask(static_cast<GLuint>(-1))
{
ASSERT(mFunctions);
mTextures[GL_TEXTURE_2D].resize(rendererCaps.maxCombinedTextureImageUnits);
mTextures[GL_TEXTURE_CUBE_MAP].resize(rendererCaps.maxCombinedTextureImageUnits);
mTextures[GL_TEXTURE_2D_ARRAY].resize(rendererCaps.maxCombinedTextureImageUnits);
mTextures[GL_TEXTURE_3D].resize(rendererCaps.maxCombinedTextureImageUnits);
mFramebuffers[GL_READ_FRAMEBUFFER] = 0;
mFramebuffers[GL_DRAW_FRAMEBUFFER] = 0;
}
void StateManagerGL::useProgram(GLuint program)
{
if (mProgram != program)
{
mProgram = program;
mFunctions->useProgram(mProgram);
}
}
void StateManagerGL::bindVertexArray(GLuint vao)
{
if (mVAO != vao)
{
mVAO = vao;
mFunctions->bindVertexArray(vao);
}
}
void StateManagerGL::bindBuffer(GLenum type, GLuint buffer)
{
if (mBuffers[type] != buffer)
{
mBuffers[type] = buffer;
mFunctions->bindBuffer(type, buffer);
}
}
void StateManagerGL::activeTexture(size_t unit)
{
if (mTextureUnitIndex != unit)
{
mTextureUnitIndex = unit;
mFunctions->activeTexture(GL_TEXTURE0 + mTextureUnitIndex);
}
}
void StateManagerGL::bindTexture(GLenum type, GLuint texture)
{
if (mTextures[type][mTextureUnitIndex] != texture)
{
mTextures[type][mTextureUnitIndex] = texture;
mFunctions->bindTexture(type, texture);
}
}
void StateManagerGL::setPixelUnpackState(GLint alignment, GLint rowLength)
{
if (mUnpackAlignment != alignment)
{
mUnpackAlignment = alignment;
mFunctions->pixelStorei(GL_UNPACK_ALIGNMENT, mUnpackAlignment);
}
if (mUnpackRowLength != rowLength)
{
mUnpackRowLength = rowLength;
mFunctions->pixelStorei(GL_UNPACK_ROW_LENGTH, mUnpackRowLength);
}
}
void StateManagerGL::bindFramebuffer(GLenum type, GLuint framebuffer)
{
if (mFramebuffers[type] != framebuffer)
{
mFramebuffers[type] = framebuffer;
mFunctions->bindFramebuffer(type, framebuffer);
}
}
void StateManagerGL::bindRenderbuffer(GLenum type, GLuint renderbuffer)
{
ASSERT(type == GL_RENDERBUFFER);
if (mRenderbuffer != renderbuffer)
{
mRenderbuffer = renderbuffer;
mFunctions->bindRenderbuffer(type, mRenderbuffer);
}
}
void StateManagerGL::setClearState(const gl::State &state, GLbitfield mask)
{
// Only apply the state required to do a clear
setScissor(state.getScissor());
setViewport(state.getViewport());
if ((mask & GL_COLOR_BUFFER_BIT) != 0)
{
setClearColor(state.getColorClearValue());
const gl::BlendState &blendState = state.getBlendState();
setColorMask(blendState.colorMaskRed, blendState.colorMaskGreen, blendState.colorMaskBlue, blendState.colorMaskAlpha);
}
if ((mask & GL_DEPTH_BUFFER_BIT) != 0)
{
setClearDepth(state.getDepthClearValue());
setDepthMask(state.getDepthStencilState().depthMask);
}
if ((mask & GL_STENCIL_BUFFER_BIT) != 0)
{
setClearStencil(state.getStencilClearValue());
setStencilMask(state.getDepthStencilState().stencilMask);
}
}
gl::Error StateManagerGL::setDrawArraysState(const gl::Data &data, GLint first, GLsizei count)
{
const gl::State &state = *data.state;
const gl::VertexArray *vao = state.getVertexArray();
const VertexArrayGL *vaoGL = GetImplAs<VertexArrayGL>(vao);
vaoGL->syncDrawArraysState(first, count);
bindVertexArray(vaoGL->getVertexArrayID());
return setGenericDrawState(data);
}
gl::Error StateManagerGL::setDrawElementsState(const gl::Data &data, GLsizei count, GLenum type, const GLvoid *indices,
const GLvoid **outIndices)
{
const gl::State &state = *data.state;
const gl::VertexArray *vao = state.getVertexArray();
const VertexArrayGL *vaoGL = GetImplAs<VertexArrayGL>(vao);
gl::Error error = vaoGL->syncDrawElementsState(count, type, indices, outIndices);
if (error.isError())
{
return error;
}
bindVertexArray(vaoGL->getVertexArrayID());
return setGenericDrawState(data);
}
gl::Error StateManagerGL::setGenericDrawState(const gl::Data &data)
{
const gl::State &state = *data.state;
const gl::Caps &caps = *data.caps;
const gl::Program *program = state.getProgram();
const ProgramGL *programGL = GetImplAs<ProgramGL>(program);
useProgram(programGL->getProgramID());
// TODO: Only apply textures referenced by the program.
for (auto textureTypeIter = mTextures.begin(); textureTypeIter != mTextures.end(); textureTypeIter++)
{
GLenum textureType = textureTypeIter->first;
// Determine if this texture type can exist in the source context
bool validTextureType = (textureType == GL_TEXTURE_2D || textureType == GL_TEXTURE_CUBE_MAP ||
(textureType == GL_TEXTURE_2D_ARRAY && data.clientVersion >= 3) ||
(textureType == GL_TEXTURE_3D && data.clientVersion >= 3));
const std::vector<GLuint> &textureVector = textureTypeIter->second;
for (size_t textureUnitIndex = 0; textureUnitIndex < textureVector.size(); textureUnitIndex++)
{
const gl::Texture *texture = nullptr;
bool validTextureUnit = textureUnitIndex < caps.maxCombinedTextureImageUnits;
if (validTextureType && validTextureUnit)
{
texture = state.getSamplerTexture(textureUnitIndex, textureType);
}
if (texture != nullptr)
{
const TextureGL *textureGL = GetImplAs<TextureGL>(texture);
textureGL->syncSamplerState(texture->getSamplerState());
if (mTextures[textureType][textureUnitIndex] != textureGL->getTextureID())
{
activeTexture(textureUnitIndex);
bindTexture(textureType, textureGL->getTextureID());
}
// TODO: apply sampler object if one is bound
}
else
{
if (mTextures[textureType][textureUnitIndex] != 0)
{
activeTexture(textureUnitIndex);
bindTexture(textureType, 0);
}
}
}
}
const gl::Framebuffer *framebuffer = state.getDrawFramebuffer();
const FramebufferGL *framebufferGL = GetImplAs<FramebufferGL>(framebuffer);
bindFramebuffer(GL_DRAW_FRAMEBUFFER, framebufferGL->getFramebufferID());
setScissor(state.getScissor());
setViewport(state.getViewport());
const gl::BlendState &blendState = state.getBlendState();
setColorMask(blendState.colorMaskRed, blendState.colorMaskGreen, blendState.colorMaskBlue, blendState.colorMaskAlpha);
const gl::DepthStencilState &depthStencilState = state.getDepthStencilState();
setDepthMask(depthStencilState.depthMask);
setStencilMask(depthStencilState.stencilMask);
return gl::Error(GL_NO_ERROR);
}
void StateManagerGL::setScissor(const gl::Rectangle &scissor)
{
if (scissor != mScissor)
{
mScissor = scissor;
mFunctions->scissor(mScissor.x, mScissor.y, mScissor.width, mScissor.height);
}
}
void StateManagerGL::setViewport(const gl::Rectangle &viewport)
{
if (viewport != mViewport)
{
mViewport = viewport;
mFunctions->viewport(mViewport.x, mViewport.y, mViewport.width, mViewport.height);
}
}
void StateManagerGL::setClearColor(const gl::ColorF &clearColor)
{
if (mClearColor != clearColor)
{
mClearColor = clearColor;
mFunctions->clearColor(mClearColor.red, mClearColor.green, mClearColor.blue, mClearColor.alpha);
}
}
void StateManagerGL::setColorMask(bool red, bool green, bool blue, bool alpha)
{
if (mColorMaskRed != red || mColorMaskGreen != green || mColorMaskBlue != blue || mColorMaskAlpha != alpha)
{
mColorMaskRed = red;
mColorMaskGreen = green;
mColorMaskBlue = blue;
mColorMaskAlpha = alpha;
mFunctions->colorMask(mColorMaskRed, mColorMaskGreen, mColorMaskBlue, mColorMaskAlpha);
}
}
void StateManagerGL::setClearDepth(float clearDepth)
{
if (mClearDepth != clearDepth)
{
mClearDepth = clearDepth;
mFunctions->clearDepth(mClearDepth);
}
}
void StateManagerGL::setDepthMask(bool mask)
{
if (mDepthMask != mask)
{
mDepthMask = mask;
mFunctions->depthMask(mDepthMask);
}
}
void StateManagerGL::setClearStencil(GLint clearStencil)
{
if (mClearStencil != clearStencil)
{
mClearStencil = clearStencil;
mFunctions->clearStencil(mClearStencil);
}
}
void StateManagerGL::setStencilMask(GLuint mask)
{
if (mStencilMask != mask)
{
mStencilMask = mask;
mFunctions->stencilMask(mStencilMask);
}
}
}
<|endoftext|> |
<commit_before>#include "precompiled.h"
//
// Copyright (c) 2002-2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// IndexDataManager.cpp: Defines the IndexDataManager, a class that
// runs the Buffer translation process for index buffers.
#include "libGLESv2/renderer/IndexDataManager.h"
#include "libGLESv2/renderer/BufferStorage.h"
#include "libGLESv2/Buffer.h"
#include "libGLESv2/main.h"
#include "libGLESv2/renderer/IndexBuffer.h"
namespace rx
{
IndexDataManager::IndexDataManager(Renderer *renderer) : mRenderer(renderer)
{
mStreamingBufferShort = new StreamingIndexBufferInterface(mRenderer);
if (!mStreamingBufferShort->reserveBufferSpace(INITIAL_INDEX_BUFFER_SIZE, GL_UNSIGNED_SHORT))
{
delete mStreamingBufferShort;
mStreamingBufferShort = NULL;
}
mStreamingBufferInt = new StreamingIndexBufferInterface(mRenderer);
if (!mStreamingBufferInt->reserveBufferSpace(INITIAL_INDEX_BUFFER_SIZE, GL_UNSIGNED_INT))
{
delete mStreamingBufferInt;
mStreamingBufferInt = NULL;
}
if (!mStreamingBufferShort)
{
// Make sure both buffers are deleted.
delete mStreamingBufferInt;
mStreamingBufferInt = NULL;
ERR("Failed to allocate the streaming index buffer(s).");
}
mCountingBuffer = NULL;
}
IndexDataManager::~IndexDataManager()
{
delete mStreamingBufferShort;
delete mStreamingBufferInt;
delete mCountingBuffer;
}
static unsigned int indexTypeSize(GLenum type)
{
switch (type)
{
case GL_UNSIGNED_INT: return sizeof(GLuint);
case GL_UNSIGNED_SHORT: return sizeof(GLushort);
case GL_UNSIGNED_BYTE: return sizeof(GLubyte);
default: UNREACHABLE(); return sizeof(GLushort);
}
}
static void convertIndices(GLenum type, const void *input, GLsizei count, void *output)
{
if (type == GL_UNSIGNED_BYTE)
{
const GLubyte *in = static_cast<const GLubyte*>(input);
GLushort *out = static_cast<GLushort*>(output);
for (GLsizei i = 0; i < count; i++)
{
out[i] = in[i];
}
}
else if (type == GL_UNSIGNED_INT)
{
memcpy(output, input, count * sizeof(GLuint));
}
else if (type == GL_UNSIGNED_SHORT)
{
memcpy(output, input, count * sizeof(GLushort));
}
else UNREACHABLE();
}
template <class IndexType>
static void computeRange(const IndexType *indices, GLsizei count, GLuint *minIndex, GLuint *maxIndex)
{
*minIndex = indices[0];
*maxIndex = indices[0];
for (GLsizei i = 0; i < count; i++)
{
if (*minIndex > indices[i]) *minIndex = indices[i];
if (*maxIndex < indices[i]) *maxIndex = indices[i];
}
}
static void computeRange(GLenum type, const GLvoid *indices, GLsizei count, GLuint *minIndex, GLuint *maxIndex)
{
if (type == GL_UNSIGNED_BYTE)
{
computeRange(static_cast<const GLubyte*>(indices), count, minIndex, maxIndex);
}
else if (type == GL_UNSIGNED_INT)
{
computeRange(static_cast<const GLuint*>(indices), count, minIndex, maxIndex);
}
else if (type == GL_UNSIGNED_SHORT)
{
computeRange(static_cast<const GLushort*>(indices), count, minIndex, maxIndex);
}
else UNREACHABLE();
}
GLenum IndexDataManager::prepareIndexData(GLenum type, GLsizei count, gl::Buffer *buffer, const GLvoid *indices, TranslatedIndexData *translated)
{
if (!mStreamingBufferShort)
{
return GL_OUT_OF_MEMORY;
}
GLenum destinationIndexType = (type == GL_UNSIGNED_INT) ? GL_UNSIGNED_INT : GL_UNSIGNED_SHORT;
intptr_t offset = reinterpret_cast<intptr_t>(indices);
bool alignedOffset = false;
BufferStorage *storage = NULL;
if (buffer != NULL)
{
storage = buffer->getStorage();
switch (type)
{
case GL_UNSIGNED_BYTE: alignedOffset = (offset % sizeof(GLubyte) == 0); break;
case GL_UNSIGNED_SHORT: alignedOffset = (offset % sizeof(GLushort) == 0); break;
case GL_UNSIGNED_INT: alignedOffset = (offset % sizeof(GLuint) == 0); break;
default: UNREACHABLE(); alignedOffset = false;
}
if (indexTypeSize(type) * count + offset > storage->getSize())
{
return GL_INVALID_OPERATION;
}
indices = static_cast<const GLubyte*>(storage->getData()) + offset;
}
StreamingIndexBufferInterface *streamingBuffer = (type == GL_UNSIGNED_INT) ? mStreamingBufferInt : mStreamingBufferShort;
StaticIndexBufferInterface *staticBuffer = buffer ? buffer->getStaticIndexBuffer() : NULL;
IndexBufferInterface *indexBuffer = streamingBuffer;
bool directStorage = alignedOffset && storage && storage->supportsDirectBinding() &&
destinationIndexType == type;
UINT streamOffset = 0;
if (directStorage)
{
indexBuffer = streamingBuffer;
streamOffset = offset;
storage->markBufferUsage();
computeRange(type, indices, count, &translated->minIndex, &translated->maxIndex);
}
else if (staticBuffer && staticBuffer->getIndexType() == type && alignedOffset)
{
indexBuffer = staticBuffer;
streamOffset = staticBuffer->lookupRange(offset, count, &translated->minIndex, &translated->maxIndex);
if (streamOffset == -1)
{
streamOffset = (offset / indexTypeSize(type)) * indexTypeSize(destinationIndexType);
computeRange(type, indices, count, &translated->minIndex, &translated->maxIndex);
staticBuffer->addRange(offset, count, translated->minIndex, translated->maxIndex, streamOffset);
}
}
else
{
int convertCount = count;
if (staticBuffer)
{
if (staticBuffer->getBufferSize() == 0 && alignedOffset)
{
indexBuffer = staticBuffer;
convertCount = storage->getSize() / indexTypeSize(type);
}
else
{
buffer->invalidateStaticData();
staticBuffer = NULL;
}
}
if (!indexBuffer)
{
ERR("No valid index buffer.");
return GL_INVALID_OPERATION;
}
unsigned int bufferSizeRequired = convertCount * indexTypeSize(destinationIndexType);
indexBuffer->reserveBufferSpace(bufferSizeRequired, type);
void* output = NULL;
streamOffset = indexBuffer->mapBuffer(bufferSizeRequired, &output);
if (streamOffset == -1 || output == NULL)
{
ERR("Failed to map index buffer.");
return GL_OUT_OF_MEMORY;
}
convertIndices(type, staticBuffer ? storage->getData() : indices, convertCount, output);
if (!indexBuffer->unmapBuffer())
{
ERR("Failed to unmap index buffer.");
return GL_OUT_OF_MEMORY;
}
computeRange(type, indices, count, &translated->minIndex, &translated->maxIndex);
if (staticBuffer)
{
streamOffset = (offset / indexTypeSize(type)) * indexTypeSize(destinationIndexType);
staticBuffer->addRange(offset, count, translated->minIndex, translated->maxIndex, streamOffset);
}
}
translated->storage = directStorage ? storage : NULL;
translated->indexBuffer = indexBuffer->getIndexBuffer();
translated->serial = directStorage ? storage->getSerial() : indexBuffer->getSerial();
translated->startIndex = streamOffset / indexTypeSize(destinationIndexType);
translated->startOffset = streamOffset;
if (buffer)
{
buffer->promoteStaticUsage(count * indexTypeSize(type));
}
return GL_NO_ERROR;
}
StaticIndexBufferInterface *IndexDataManager::getCountingIndices(GLsizei count)
{
if (count <= 65536) // 16-bit indices
{
const unsigned int spaceNeeded = count * sizeof(unsigned short);
if (!mCountingBuffer || mCountingBuffer->getBufferSize() < spaceNeeded)
{
delete mCountingBuffer;
mCountingBuffer = new StaticIndexBufferInterface(mRenderer);
mCountingBuffer->reserveBufferSpace(spaceNeeded, GL_UNSIGNED_SHORT);
void* mappedMemory = NULL;
if (mCountingBuffer->mapBuffer(spaceNeeded, &mappedMemory) == -1 || mappedMemory == NULL)
{
ERR("Failed to map counting buffer.");
return NULL;
}
unsigned short *data = reinterpret_cast<unsigned short*>(mappedMemory);
for(int i = 0; i < count; i++)
{
data[i] = i;
}
if (!mCountingBuffer->unmapBuffer())
{
ERR("Failed to unmap counting buffer.");
return NULL;
}
}
}
else if (mStreamingBufferInt) // 32-bit indices supported
{
const unsigned int spaceNeeded = count * sizeof(unsigned int);
if (!mCountingBuffer || mCountingBuffer->getBufferSize() < spaceNeeded)
{
delete mCountingBuffer;
mCountingBuffer = new StaticIndexBufferInterface(mRenderer);
mCountingBuffer->reserveBufferSpace(spaceNeeded, GL_UNSIGNED_INT);
void* mappedMemory = NULL;
if (mCountingBuffer->mapBuffer(spaceNeeded, &mappedMemory) == -1 || mappedMemory == NULL)
{
ERR("Failed to map counting buffer.");
return NULL;
}
unsigned int *data = reinterpret_cast<unsigned int*>(mappedMemory);
for(int i = 0; i < count; i++)
{
data[i] = i;
}
if (!mCountingBuffer->unmapBuffer())
{
ERR("Failed to unmap counting buffer.");
return NULL;
}
}
}
else
{
return NULL;
}
return mCountingBuffer;
}
}
<commit_msg>Fixed a bug where a static buffer could sometimes be used if it had not had data written to it.<commit_after>#include "precompiled.h"
//
// Copyright (c) 2002-2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// IndexDataManager.cpp: Defines the IndexDataManager, a class that
// runs the Buffer translation process for index buffers.
#include "libGLESv2/renderer/IndexDataManager.h"
#include "libGLESv2/renderer/BufferStorage.h"
#include "libGLESv2/Buffer.h"
#include "libGLESv2/main.h"
#include "libGLESv2/renderer/IndexBuffer.h"
namespace rx
{
IndexDataManager::IndexDataManager(Renderer *renderer) : mRenderer(renderer)
{
mStreamingBufferShort = new StreamingIndexBufferInterface(mRenderer);
if (!mStreamingBufferShort->reserveBufferSpace(INITIAL_INDEX_BUFFER_SIZE, GL_UNSIGNED_SHORT))
{
delete mStreamingBufferShort;
mStreamingBufferShort = NULL;
}
mStreamingBufferInt = new StreamingIndexBufferInterface(mRenderer);
if (!mStreamingBufferInt->reserveBufferSpace(INITIAL_INDEX_BUFFER_SIZE, GL_UNSIGNED_INT))
{
delete mStreamingBufferInt;
mStreamingBufferInt = NULL;
}
if (!mStreamingBufferShort)
{
// Make sure both buffers are deleted.
delete mStreamingBufferInt;
mStreamingBufferInt = NULL;
ERR("Failed to allocate the streaming index buffer(s).");
}
mCountingBuffer = NULL;
}
IndexDataManager::~IndexDataManager()
{
delete mStreamingBufferShort;
delete mStreamingBufferInt;
delete mCountingBuffer;
}
static unsigned int indexTypeSize(GLenum type)
{
switch (type)
{
case GL_UNSIGNED_INT: return sizeof(GLuint);
case GL_UNSIGNED_SHORT: return sizeof(GLushort);
case GL_UNSIGNED_BYTE: return sizeof(GLubyte);
default: UNREACHABLE(); return sizeof(GLushort);
}
}
static void convertIndices(GLenum type, const void *input, GLsizei count, void *output)
{
if (type == GL_UNSIGNED_BYTE)
{
const GLubyte *in = static_cast<const GLubyte*>(input);
GLushort *out = static_cast<GLushort*>(output);
for (GLsizei i = 0; i < count; i++)
{
out[i] = in[i];
}
}
else if (type == GL_UNSIGNED_INT)
{
memcpy(output, input, count * sizeof(GLuint));
}
else if (type == GL_UNSIGNED_SHORT)
{
memcpy(output, input, count * sizeof(GLushort));
}
else UNREACHABLE();
}
template <class IndexType>
static void computeRange(const IndexType *indices, GLsizei count, GLuint *minIndex, GLuint *maxIndex)
{
*minIndex = indices[0];
*maxIndex = indices[0];
for (GLsizei i = 0; i < count; i++)
{
if (*minIndex > indices[i]) *minIndex = indices[i];
if (*maxIndex < indices[i]) *maxIndex = indices[i];
}
}
static void computeRange(GLenum type, const GLvoid *indices, GLsizei count, GLuint *minIndex, GLuint *maxIndex)
{
if (type == GL_UNSIGNED_BYTE)
{
computeRange(static_cast<const GLubyte*>(indices), count, minIndex, maxIndex);
}
else if (type == GL_UNSIGNED_INT)
{
computeRange(static_cast<const GLuint*>(indices), count, minIndex, maxIndex);
}
else if (type == GL_UNSIGNED_SHORT)
{
computeRange(static_cast<const GLushort*>(indices), count, minIndex, maxIndex);
}
else UNREACHABLE();
}
GLenum IndexDataManager::prepareIndexData(GLenum type, GLsizei count, gl::Buffer *buffer, const GLvoid *indices, TranslatedIndexData *translated)
{
if (!mStreamingBufferShort)
{
return GL_OUT_OF_MEMORY;
}
GLenum destinationIndexType = (type == GL_UNSIGNED_INT) ? GL_UNSIGNED_INT : GL_UNSIGNED_SHORT;
intptr_t offset = reinterpret_cast<intptr_t>(indices);
bool alignedOffset = false;
BufferStorage *storage = NULL;
if (buffer != NULL)
{
storage = buffer->getStorage();
switch (type)
{
case GL_UNSIGNED_BYTE: alignedOffset = (offset % sizeof(GLubyte) == 0); break;
case GL_UNSIGNED_SHORT: alignedOffset = (offset % sizeof(GLushort) == 0); break;
case GL_UNSIGNED_INT: alignedOffset = (offset % sizeof(GLuint) == 0); break;
default: UNREACHABLE(); alignedOffset = false;
}
if (indexTypeSize(type) * count + offset > storage->getSize())
{
return GL_INVALID_OPERATION;
}
indices = static_cast<const GLubyte*>(storage->getData()) + offset;
}
StreamingIndexBufferInterface *streamingBuffer = (type == GL_UNSIGNED_INT) ? mStreamingBufferInt : mStreamingBufferShort;
StaticIndexBufferInterface *staticBuffer = buffer ? buffer->getStaticIndexBuffer() : NULL;
IndexBufferInterface *indexBuffer = streamingBuffer;
bool directStorage = alignedOffset && storage && storage->supportsDirectBinding() &&
destinationIndexType == type;
UINT streamOffset = 0;
if (directStorage)
{
indexBuffer = streamingBuffer;
streamOffset = offset;
storage->markBufferUsage();
computeRange(type, indices, count, &translated->minIndex, &translated->maxIndex);
}
else if (staticBuffer && staticBuffer->getBufferSize() != 0 && staticBuffer->getIndexType() == type && alignedOffset)
{
indexBuffer = staticBuffer;
streamOffset = staticBuffer->lookupRange(offset, count, &translated->minIndex, &translated->maxIndex);
if (streamOffset == -1)
{
streamOffset = (offset / indexTypeSize(type)) * indexTypeSize(destinationIndexType);
computeRange(type, indices, count, &translated->minIndex, &translated->maxIndex);
staticBuffer->addRange(offset, count, translated->minIndex, translated->maxIndex, streamOffset);
}
}
else
{
int convertCount = count;
if (staticBuffer)
{
if (staticBuffer->getBufferSize() == 0 && alignedOffset)
{
indexBuffer = staticBuffer;
convertCount = storage->getSize() / indexTypeSize(type);
}
else
{
buffer->invalidateStaticData();
staticBuffer = NULL;
}
}
if (!indexBuffer)
{
ERR("No valid index buffer.");
return GL_INVALID_OPERATION;
}
unsigned int bufferSizeRequired = convertCount * indexTypeSize(destinationIndexType);
indexBuffer->reserveBufferSpace(bufferSizeRequired, type);
void* output = NULL;
streamOffset = indexBuffer->mapBuffer(bufferSizeRequired, &output);
if (streamOffset == -1 || output == NULL)
{
ERR("Failed to map index buffer.");
return GL_OUT_OF_MEMORY;
}
convertIndices(type, staticBuffer ? storage->getData() : indices, convertCount, output);
if (!indexBuffer->unmapBuffer())
{
ERR("Failed to unmap index buffer.");
return GL_OUT_OF_MEMORY;
}
computeRange(type, indices, count, &translated->minIndex, &translated->maxIndex);
if (staticBuffer)
{
streamOffset = (offset / indexTypeSize(type)) * indexTypeSize(destinationIndexType);
staticBuffer->addRange(offset, count, translated->minIndex, translated->maxIndex, streamOffset);
}
}
translated->storage = directStorage ? storage : NULL;
translated->indexBuffer = indexBuffer->getIndexBuffer();
translated->serial = directStorage ? storage->getSerial() : indexBuffer->getSerial();
translated->startIndex = streamOffset / indexTypeSize(destinationIndexType);
translated->startOffset = streamOffset;
if (buffer)
{
buffer->promoteStaticUsage(count * indexTypeSize(type));
}
return GL_NO_ERROR;
}
StaticIndexBufferInterface *IndexDataManager::getCountingIndices(GLsizei count)
{
if (count <= 65536) // 16-bit indices
{
const unsigned int spaceNeeded = count * sizeof(unsigned short);
if (!mCountingBuffer || mCountingBuffer->getBufferSize() < spaceNeeded)
{
delete mCountingBuffer;
mCountingBuffer = new StaticIndexBufferInterface(mRenderer);
mCountingBuffer->reserveBufferSpace(spaceNeeded, GL_UNSIGNED_SHORT);
void* mappedMemory = NULL;
if (mCountingBuffer->mapBuffer(spaceNeeded, &mappedMemory) == -1 || mappedMemory == NULL)
{
ERR("Failed to map counting buffer.");
return NULL;
}
unsigned short *data = reinterpret_cast<unsigned short*>(mappedMemory);
for(int i = 0; i < count; i++)
{
data[i] = i;
}
if (!mCountingBuffer->unmapBuffer())
{
ERR("Failed to unmap counting buffer.");
return NULL;
}
}
}
else if (mStreamingBufferInt) // 32-bit indices supported
{
const unsigned int spaceNeeded = count * sizeof(unsigned int);
if (!mCountingBuffer || mCountingBuffer->getBufferSize() < spaceNeeded)
{
delete mCountingBuffer;
mCountingBuffer = new StaticIndexBufferInterface(mRenderer);
mCountingBuffer->reserveBufferSpace(spaceNeeded, GL_UNSIGNED_INT);
void* mappedMemory = NULL;
if (mCountingBuffer->mapBuffer(spaceNeeded, &mappedMemory) == -1 || mappedMemory == NULL)
{
ERR("Failed to map counting buffer.");
return NULL;
}
unsigned int *data = reinterpret_cast<unsigned int*>(mappedMemory);
for(int i = 0; i < count; i++)
{
data[i] = i;
}
if (!mCountingBuffer->unmapBuffer())
{
ERR("Failed to unmap counting buffer.");
return NULL;
}
}
}
else
{
return NULL;
}
return mCountingBuffer;
}
}
<|endoftext|> |
<commit_before>//
// $Id: $
# include <sys/types.h>
# include <sys/socket.h>
# include <sys/ioctl.h>
# include <netinet/in.h>
# include <arpa/inet.h>
# include <fcntl.h>
# include <errno.h>
# include <unistd.h>
# include <netdb.h>
# include "avmthane.h"
namespace thane
{
BEGIN_NATIVE_MAP(SocketClass)
NATIVE_METHOD(flash_net_Socket_private_nb_connect, SocketObject::connect)
NATIVE_METHOD(flash_net_Socket_private_nb_disconnect, SocketObject::disconnect)
NATIVE_METHOD(flash_net_Socket_private_nb_read, SocketObject::read)
NATIVE_METHOD(flash_net_Socket_private_nb_write, SocketObject::write)
END_NATIVE_MAP()
//
// Socket
//
Socket::Socket()
{
m_descriptor = -1;
}
Socket::~Socket()
{
if (m_descriptor >= 0) {
close(m_descriptor);
m_descriptor = -1;
}
}
/**
* Returns -1 for error, 0 for keep trying, 1 for success.
*/
int Socket::connect (const char *host_name, int port)
{
// see if we've opened up a socket yet
if (-1 == m_descriptor) {
// if not, we may still be resolving the address
struct hostent *resolution = gethostbyname(host_name);
if (resolution == NULL) {
if (h_errno == TRY_AGAIN) {
// tell caller to hit us again in a little while
return 0;
}
return -1;
}
// address finished resolving
memset(&m_host, 0, sizeof(m_host));
m_host.sin_family = AF_INET;
m_host.sin_port = htons(port);
in_addr_t addr = inet_addr(resolution->h_addr);
if (addr == INADDR_NONE) {
return -1;
}
m_host.sin_addr.s_addr = addr;
// if the address bits all went well, open the socket
m_descriptor = socket(AF_INET, SOCK_STREAM, 0);
if (-1 == m_descriptor) {
return -1;
}
// flag it as non-blocking
int flags = fcntl(m_descriptor, F_GETFL, 0);
fcntl(m_descriptor, F_SETFL, (flags > 0 ? flags : 0) | O_NONBLOCK);
// and fall through to connect
}
if (-1 == ::connect(m_descriptor, (struct sockaddr*) &m_host, sizeof(m_host))) {
if (errno == EALREADY || errno == EINPROGRESS) {
// tell caller to try us again later
return 0;
}
if (errno != EISCONN) {
// anything else is a real error
disconnect();
return -1;
}
}
// success!
return 1;
}
void Socket::disconnect ()
{
if (-1 != m_descriptor) {
close(m_descriptor);
m_descriptor = -1;
}
}
int Socket::read (ByteArrayFile &bytes)
{
if (m_descriptor < 0) {
return -1;
}
int tot_bytes = 0;
while (true) {
int size = ::read(m_descriptor, m_buffer, SOCK_BUF_SZ);
if (size == -1) {
if (errno != EAGAIN) {
// TODO: throw an error
return -1;
}
// EOF in non-blocking just means there was nothing to read
size = 0;
}
if (size > 0) {
bytes.Push(m_buffer, size);
tot_bytes += size;
}
if (size < SOCK_BUF_SZ) {
// nothing more to read
return tot_bytes;
}
}
}
int Socket::write (ByteArrayFile &bytes)
{
if (m_descriptor < 0) {
return -1;
}
int avail = bytes.Available();
if (avail == 0) {
return 0;
}
int ptr = bytes.GetFilePointer();
int size = ::write(m_descriptor, bytes.GetBuffer() + ptr, avail);
if (size == -1) {
if (errno != EAGAIN) {
// TODO: throw an error
return -1;
}
// no non-blocking writes are possible
size = 0;
}
if (size > 0) {
bytes.Seek(ptr + size);
}
return size;
}
void Socket::ThrowMemoryError()
{
// todo throw out of memory exception
// m_toplevel->memoryError->throwError(kOutOfMemoryError);
}
//
// SocketObject
//
SocketObject::SocketObject(VTable *ivtable,
ScriptObject *delegate)
: ScriptObject(ivtable, delegate),
m_socket()
{
c.set(&m_socket, sizeof(Socket));
}
int SocketObject::connect (Stringp host, int port)
{
return m_socket.connect(host->toUTF8String()->c_str(), port);
}
void SocketObject::disconnect ()
{
m_socket.disconnect();
}
int SocketObject::write (ByteArrayObject *bytes)
{
return m_socket.write(bytes->GetByteArrayFile());
}
int SocketObject::read (ByteArrayObject *bytes)
{
return m_socket.read(bytes->GetByteArrayFile());
}
//
// SocketClass
//
SocketClass::SocketClass(VTable *vtable)
: ClassClosure(vtable)
{
prototype = toplevel()->objectClass->construct();
}
ScriptObject* SocketClass::createInstance(VTable *ivtable,
ScriptObject *prototype)
{
return new (core()->GetGC(), ivtable->getExtraSize()) SocketObject(ivtable, prototype);
}
}
<commit_msg>Nothing to see here, move along.<commit_after>//
// $Id: $
# include <sys/types.h>
# include <sys/socket.h>
# include <sys/ioctl.h>
# include <netinet/in.h>
# include <arpa/inet.h>
# include <fcntl.h>
# include <errno.h>
# include <unistd.h>
# include <netdb.h>
# include "avmthane.h"
namespace thane
{
BEGIN_NATIVE_MAP(SocketClass)
NATIVE_METHOD(flash_net_Socket_private_nb_connect, SocketObject::connect)
NATIVE_METHOD(flash_net_Socket_private_nb_disconnect, SocketObject::disconnect)
NATIVE_METHOD(flash_net_Socket_private_nb_read, SocketObject::read)
NATIVE_METHOD(flash_net_Socket_private_nb_write, SocketObject::write)
END_NATIVE_MAP()
//
// Socket
//
Socket::Socket()
{
m_descriptor = -1;
}
Socket::~Socket()
{
if (m_descriptor >= 0) {
close(m_descriptor);
m_descriptor = -1;
}
}
/**
* Returns -1 for error, 0 for keep trying, 1 for success.
*/
int Socket::connect (const char *host_name, int port)
{
// see if we've opened up a socket yet
if (-1 == m_descriptor) {
// if not, we may still be resolving the address
struct hostent *resolution = gethostbyname(host_name);
if (resolution == NULL) {
if (h_errno == TRY_AGAIN) {
// tell caller to hit us again in a little while
return 0;
}
return -1;
}
// address finished resolving
memset(&m_host, 0, sizeof(m_host));
m_host.sin_family = resolution->h_addrtype;
m_host.sin_port = htons(port);
memcpy(&m_host.sin_addr.s_addr, resolution->h_addr, resolution->h_length);
// if the address bits all went well, open the socket
m_descriptor = socket(AF_INET, SOCK_STREAM, 0);
if (-1 == m_descriptor) {
return -1;
}
// flag it as non-blocking
int flags = fcntl(m_descriptor, F_GETFL, 0);
fcntl(m_descriptor, F_SETFL, (flags > 0 ? flags : 0) | O_NONBLOCK);
// and fall through to connect
}
if (-1 == ::connect(m_descriptor, (struct sockaddr*) &m_host, sizeof(m_host))) {
if (errno == EALREADY || errno == EINPROGRESS) {
// tell caller to try us again later
return 0;
}
if (errno != EISCONN) {
// anything else is a real error
disconnect();
return -1;
}
}
// success!
return 1;
}
void Socket::disconnect ()
{
if (-1 != m_descriptor) {
close(m_descriptor);
m_descriptor = -1;
}
}
int Socket::read (ByteArrayFile &bytes)
{
if (m_descriptor < 0) {
return -1;
}
int tot_bytes = 0;
while (true) {
int size = ::read(m_descriptor, m_buffer, SOCK_BUF_SZ);
if (size == -1) {
if (errno != EAGAIN) {
// TODO: throw an error
return -1;
}
// EOF in non-blocking just means there was nothing to read
size = 0;
}
if (size > 0) {
bytes.Push(m_buffer, size);
tot_bytes += size;
}
if (size < SOCK_BUF_SZ) {
// nothing more to read
return tot_bytes;
}
}
}
int Socket::write (ByteArrayFile &bytes)
{
if (m_descriptor < 0) {
return -1;
}
int avail = bytes.Available();
if (avail == 0) {
return 0;
}
int ptr = bytes.GetFilePointer();
int size = ::write(m_descriptor, bytes.GetBuffer() + ptr, avail);
if (size == -1) {
if (errno != EAGAIN) {
// TODO: throw an error
return -1;
}
// no non-blocking writes are possible
size = 0;
}
if (size > 0) {
bytes.Seek(ptr + size);
}
return size;
}
void Socket::ThrowMemoryError()
{
// todo throw out of memory exception
// m_toplevel->memoryError->throwError(kOutOfMemoryError);
}
//
// SocketObject
//
SocketObject::SocketObject(VTable *ivtable,
ScriptObject *delegate)
: ScriptObject(ivtable, delegate),
m_socket()
{
c.set(&m_socket, sizeof(Socket));
}
int SocketObject::connect (Stringp host, int port)
{
return m_socket.connect(host->toUTF8String()->c_str(), port);
}
void SocketObject::disconnect ()
{
m_socket.disconnect();
}
int SocketObject::write (ByteArrayObject *bytes)
{
return m_socket.write(bytes->GetByteArrayFile());
}
int SocketObject::read (ByteArrayObject *bytes)
{
return m_socket.read(bytes->GetByteArrayFile());
}
//
// SocketClass
//
SocketClass::SocketClass(VTable *vtable)
: ClassClosure(vtable)
{
prototype = toplevel()->objectClass->construct();
}
ScriptObject* SocketClass::createInstance(VTable *ivtable,
ScriptObject *prototype)
{
return new (core()->GetGC(), ivtable->getExtraSize()) SocketObject(ivtable, prototype);
}
}
<|endoftext|> |
<commit_before>//
// libavg - Media Playback Engine.
// Copyright (C) 2003-2011 Ulrich von Zadow
//
// 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 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
//
// Current versions can be found at www.libavg.de
//
#include "BmpTextureMover.h"
#include "Bitmap.h"
#include "GLTexture.h"
#include "FBO.h"
#include "Filterfliprgb.h"
#include "../base/Logger.h"
#include "../base/Exception.h"
#include "GLContext.h"
#include <iostream>
#include <cstring>
using namespace std;
using namespace boost;
namespace avg {
BmpTextureMover::BmpTextureMover(const IntPoint& size, PixelFormat pf)
: TextureMover(size, pf)
{
m_pBmp = BitmapPtr(new Bitmap(size, pf));
}
BmpTextureMover::~BmpTextureMover()
{
}
void BmpTextureMover::moveBmpToTexture(BitmapPtr pBmp, GLTexture& tex)
{
AVG_ASSERT(pBmp->getSize() == tex.getSize());
AVG_ASSERT(getSize() == pBmp->getSize());
AVG_ASSERT(pBmp->getPixelFormat() == getPF());
tex.activate();
unsigned char * pStartPos = pBmp->getPixels();
IntPoint size = tex.getSize();
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, size.x, size.y,
tex.getGLFormat(getPF()), tex.getGLType(getPF()),
pStartPos);
tex.setDirty();
tex.generateMipmaps();
GLContext::checkError("BmpTextureMover::moveBmpToTexture: glTexSubImage2D()");
}
BitmapPtr BmpTextureMover::moveTextureToBmp(GLTexture& tex, int mipmapLevel)
{
GLContext* pContext = GLContext::getCurrent();
unsigned fbo = pContext->genFBO();
glproc::BindFramebuffer(GL_FRAMEBUFFER, fbo);
glproc::FramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
tex.getID(), mipmapLevel);
FBO::checkError("BmpTextureMover::moveTextureToBmp");
IntPoint size = tex.getMipmapSize(mipmapLevel);
BitmapPtr pBmp(new Bitmap(size, getPF()));
if (GLContext::getMain()->isGLES() && getPF() == B5G6R5) {
BitmapPtr pTmpBmp(new Bitmap(size, R8G8B8));
glReadPixels(0, 0, size.x, size.y, GL_RGB, GL_UNSIGNED_BYTE, pTmpBmp->getPixels());
FilterFlipRGB().applyInPlace(pTmpBmp);
pBmp->copyPixels(*pTmpBmp);
} else {
int glPixelFormat = tex.getGLFormat(getPF());
glReadPixels(0, 0, size.x, size.y, glPixelFormat, tex.getGLType(getPF()),
pBmp->getPixels());
}
GLContext::checkError("BmpTextureMover::moveTextureToBmp: glReadPixels()");
glproc::FramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
0, 0);
pContext->returnFBOToCache(fbo);
glproc::BindFramebuffer(GL_FRAMEBUFFER, 0);
return pBmp;
}
BitmapPtr BmpTextureMover::lock()
{
return m_pBmp;
}
void BmpTextureMover::unlock()
{
}
void BmpTextureMover::moveToTexture(GLTexture& tex)
{
moveBmpToTexture(m_pBmp, tex);
}
}
<commit_msg>Fixed BGR565 compression with ES2<commit_after>//
// libavg - Media Playback Engine.
// Copyright (C) 2003-2011 Ulrich von Zadow
//
// 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 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
//
// Current versions can be found at www.libavg.de
//
#include "BmpTextureMover.h"
#include "Bitmap.h"
#include "GLTexture.h"
#include "FBO.h"
#include "Filterfliprgb.h"
#include "../base/Logger.h"
#include "../base/Exception.h"
#include "GLContext.h"
#include <iostream>
#include <cstring>
using namespace std;
using namespace boost;
namespace avg {
BmpTextureMover::BmpTextureMover(const IntPoint& size, PixelFormat pf)
: TextureMover(size, pf)
{
m_pBmp = BitmapPtr(new Bitmap(size, pf));
}
BmpTextureMover::~BmpTextureMover()
{
}
void BmpTextureMover::moveBmpToTexture(BitmapPtr pBmp, GLTexture& tex)
{
AVG_ASSERT(pBmp->getSize() == tex.getSize());
AVG_ASSERT(getSize() == pBmp->getSize());
AVG_ASSERT(pBmp->getPixelFormat() == getPF());
tex.activate();
unsigned char * pStartPos = pBmp->getPixels();
IntPoint size = tex.getSize();
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, size.x, size.y,
tex.getGLFormat(getPF()), tex.getGLType(getPF()),
pStartPos);
tex.setDirty();
tex.generateMipmaps();
GLContext::checkError("BmpTextureMover::moveBmpToTexture: glTexSubImage2D()");
}
BitmapPtr BmpTextureMover::moveTextureToBmp(GLTexture& tex, int mipmapLevel)
{
GLContext* pContext = GLContext::getCurrent();
unsigned fbo = pContext->genFBO();
glproc::BindFramebuffer(GL_FRAMEBUFFER, fbo);
glproc::FramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
tex.getID(), mipmapLevel);
FBO::checkError("BmpTextureMover::moveTextureToBmp");
IntPoint size = tex.getMipmapSize(mipmapLevel);
BitmapPtr pBmp(new Bitmap(size, getPF()));
if (GLContext::getMain()->isGLES() && getPF() == B5G6R5) {
BitmapPtr pTmpBmp(new Bitmap(size, R8G8B8A8));
glReadPixels(0, 0, size.x, size.y, GL_RGBA, GL_UNSIGNED_BYTE, pTmpBmp->getPixels());
FilterFlipRGB().applyInPlace(pTmpBmp);
pBmp->copyPixels(*pTmpBmp);
} else {
int glPixelFormat = tex.getGLFormat(getPF());
glReadPixels(0, 0, size.x, size.y, glPixelFormat, tex.getGLType(getPF()),
pBmp->getPixels());
}
GLContext::checkError("BmpTextureMover::moveTextureToBmp: glReadPixels()");
glproc::FramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
0, 0);
pContext->returnFBOToCache(fbo);
glproc::BindFramebuffer(GL_FRAMEBUFFER, 0);
return pBmp;
}
BitmapPtr BmpTextureMover::lock()
{
return m_pBmp;
}
void BmpTextureMover::unlock()
{
}
void BmpTextureMover::moveToTexture(GLTexture& tex)
{
moveBmpToTexture(m_pBmp, tex);
}
}
<|endoftext|> |
<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------
// RUN: cat %s | %cling -I%p | FileCheck %s
#include "cling/Interpreter/Interpreter.h"
#include "cling/Interpreter/InterpreterCallbacks.h"
.dynamicExtensions
gCling->setCallbacks(new cling::test::SymbolResolverCallback(gCling));
jksghdgsjdf->getVersion() // CHECK: {{.*Interpreter.*}}
hsdghfjagsp->Draw() // CHECK: (int) 12
h->PrintString(std::string("test")); // CHECK: test
int a[5] = {1,2,3,4,5};
h->PrintArray(a, 5); // CHECK: 12345
.q
<commit_msg>Add test for ROOT-6650.<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------
// RUN: cat %s | %cling -I%p | FileCheck %s
#include "cling/Interpreter/Interpreter.h"
#include "cling/Interpreter/InterpreterCallbacks.h"
.dynamicExtensions
gCling->setCallbacks(new cling::test::SymbolResolverCallback(gCling));
jksghdgsjdf->getVersion() // CHECK: {{.*Interpreter.*}}
hsdghfjagsp->Draw() // CHECK: (int) 12
h->PrintString(std::string("test")); // CHECK: test
int a[5] = {1,2,3,4,5};
h->PrintArray(a, 5); // CHECK: 12345
// ROOT-6650
std::string* s = new std::string(h->getVersion());
.q
<|endoftext|> |
<commit_before>#include <riak/request_with_timeout.hxx>
//=============================================================================
namespace riak {
//=============================================================================
using boost::mutex;
using boost::unique_lock;
using std::placeholders::_1;
using std::placeholders::_2;
using std::placeholders::_3;
request_with_timeout::request_with_timeout (
const std::string& data,
std::chrono::milliseconds timeout,
message::buffering_handler& h,
boost::asio::io_service& ios)
: timeout_length_(timeout),
timeout_(ios),
request_data_(data),
response_callback_(h),
succeeded_(false),
timed_out_(false)
{ }
void request_with_timeout::dispatch_via (transport::delivery_provider& deliver)
{
// The request can only be sent once.
assert(not terminate_request_ and not succeeded_ and not timed_out_);
auto on_response = std::bind(&request_with_timeout::on_response, shared_from_this(), _1, _2, _3);
terminate_request_ = deliver(request_data_, on_response);
timeout_.expires_from_now(boost::posix_time::milliseconds(timeout_length_.count()));
auto on_timeout = std::bind(&request_with_timeout::on_timeout, shared_from_this(), _1);
timeout_.async_wait(on_timeout);
}
void request_with_timeout::on_response (std::error_code error, size_t bytes_received, const std::string& raw_data)
{
assert(not succeeded_ and (!! terminate_request_));
unique_lock<mutex> serialize(this->mutex_);
// Whatever happened, it constitutes activity. Stop the timeout timer.
timeout_.cancel();
bool error_condition = (timed_out_ or error);
if (not error_condition) {
if (response_callback_(std::error_code(), bytes_received, raw_data)) {
(*terminate_request_)(false);
succeeded_ = true;
} else {
timeout_.expires_from_now(boost::posix_time::milliseconds(timeout_length_.count()));
auto on_timeout = std::bind(&request_with_timeout::on_timeout, shared_from_this(), _1);
timeout_.async_wait(on_timeout);
}
} else {
(*terminate_request_)(true);
// Timeout already satisfied the response callback.
if (not timed_out_)
response_callback_(error, 0, raw_data);
}
}
void request_with_timeout::on_timeout (const boost::system::error_code& error)
{
assert(not timed_out_);
unique_lock<mutex> serialize(this->mutex_);
timed_out_ = not error;
if (timed_out_) {
auto timeout_error = std::make_error_code(std::errc::timed_out);
response_callback_(timeout_error, 0, "");
}
}
//=============================================================================
} // namespace riak
//=============================================================================
<commit_msg>Fixed memory leak caused by circular shared_ptrs<commit_after>#include <riak/request_with_timeout.hxx>
//=============================================================================
namespace riak {
//=============================================================================
using boost::mutex;
using boost::unique_lock;
using std::placeholders::_1;
using std::placeholders::_2;
using std::placeholders::_3;
request_with_timeout::request_with_timeout (
const std::string& data,
std::chrono::milliseconds timeout,
message::buffering_handler& h,
boost::asio::io_service& ios)
: timeout_length_(timeout),
timeout_(ios),
request_data_(data),
response_callback_(h),
succeeded_(false),
timed_out_(false)
{ }
void request_with_timeout::dispatch_via (transport::delivery_provider& deliver)
{
// The request can only be sent once.
assert(not terminate_request_ and not succeeded_ and not timed_out_);
auto on_response = std::bind(&request_with_timeout::on_response, shared_from_this(), _1, _2, _3);
terminate_request_ = deliver(request_data_, on_response);
timeout_.expires_from_now(boost::posix_time::milliseconds(timeout_length_.count()));
auto on_timeout = std::bind(&request_with_timeout::on_timeout, shared_from_this(), _1);
timeout_.async_wait(on_timeout);
}
void request_with_timeout::on_response (std::error_code error, size_t bytes_received, const std::string& raw_data)
{
assert(not succeeded_ and (!! terminate_request_));
unique_lock<mutex> serialize(this->mutex_);
// Whatever happened, it constitutes activity. Stop the timeout timer.
timeout_.cancel();
bool error_condition = (timed_out_ or error);
if (not error_condition) {
if (response_callback_(std::error_code(), bytes_received, raw_data)) {
(*terminate_request_)(false);
succeeded_ = true;
terminate_request_.reset();
} else {
timeout_.expires_from_now(boost::posix_time::milliseconds(timeout_length_.count()));
auto on_timeout = std::bind(&request_with_timeout::on_timeout, shared_from_this(), _1);
timeout_.async_wait(on_timeout);
}
} else {
(*terminate_request_)(true);
// Timeout already satisfied the response callback.
if (not timed_out_)
response_callback_(error, 0, raw_data);
terminate_request_.reset();
}
}
void request_with_timeout::on_timeout (const boost::system::error_code& error)
{
assert(not timed_out_);
unique_lock<mutex> serialize(this->mutex_);
timed_out_ = not error;
if (timed_out_) {
auto timeout_error = std::make_error_code(std::errc::timed_out);
response_callback_(timeout_error, 0, "");
terminate_request_.reset();
}
}
//=============================================================================
} // namespace riak
//=============================================================================
<|endoftext|> |
<commit_before>/**********************************************************************
* $Id$
*
* GEOS - Geometry Engine Open Source
* http://geos.refractions.net
*
* Copyright (C) 2010 Sandro Santilli <strk@keybit.net>
*
* This is free software; you can redistribute and/or modify it under
* the terms of the GNU Lesser General Public Licence as published
* by the Free Software Foundation.
* See the COPYING file for more information.
*
**********************************************************************
*
* Last port: original work
*
* Developed by Sandro Santilli (strk@keybit.net)
* for Faunalia (http://www.faunalia.it)
* with funding from Regione Toscana - Settore SISTEMA INFORMATIVO
* TERRITORIALE ED AMBIENTALE - for the project: "Sviluppo strumenti
* software per il trattamento di dati geografici basati su QuantumGIS
* e Postgis (CIG 0494241492)"
*
**********************************************************************/
#include <geos/operation/sharedpaths/SharedPathsOp.h>
#include <geos/geom/Geometry.h>
#include <geos/geom/LineString.h>
#include <geos/geom/MultiLineString.h>
#include <geos/linearref/LinearLocation.h>
#include <geos/linearref/LocationIndexOfPoint.h>
#include <geos/operation/overlay/OverlayOp.h>
#include <geos/util/IllegalArgumentException.h>
using namespace geos::geom;
namespace geos {
namespace operation { // geos.operation
namespace sharedpaths { // geos.operation.sharedpaths
/* public static */
void
SharedPathsOp::sharedPathsOp(const Geometry& g1, const Geometry& g2,
PathList& sameDirection,
PathList& oppositeDirection)
{
SharedPathsOp sp(g1, g2);
sp.getSharedPaths(sameDirection, oppositeDirection);
}
/* public */
SharedPathsOp::SharedPathsOp(
const geom::Geometry& g1, const geom::Geometry& g2)
:
_g1(g1),
_g2(g2),
_gf(*g1.getFactory())
{
checkLinealInput(_g1);
checkLinealInput(_g2);
}
/* private */
void
SharedPathsOp::checkLinealInput(const geom::Geometry& g)
{
if ( ! dynamic_cast<const LineString*>(&g) &&
! dynamic_cast<const MultiLineString*>(&g) )
{
throw util::IllegalArgumentException("Geometry is not lineal");
}
}
/* public */
void
SharedPathsOp::getSharedPaths(PathList& forwDir, PathList& backDir)
{
PathList paths;
findLinearIntersections(paths);
for (size_t i=0, n=paths.size(); i<n; ++i)
{
LineString* path = paths[i];
if ( isSameDirection(*path) ) forwDir.push_back(path);
else backDir.push_back(path);
}
}
/* static private */
void
SharedPathsOp::clearEdges(PathList& edges)
{
for (PathList::const_iterator
i=edges.begin(), e=edges.end();
i!=e; ++i)
{
delete *i;
}
edges.clear();
}
/* private */
void
SharedPathsOp::findLinearIntersections(PathList& to)
{
using geos::operation::overlay::OverlayOp;
// TODO: optionally use the tolerance,
// snapping _g2 over _g1 ?
std::auto_ptr<Geometry> full ( OverlayOp::overlayOp(
&_g1, &_g2, OverlayOp::opINTERSECTION) );
// NOTE: intersection of equal lines yelds splitted lines,
// should we sew them back ?
for (size_t i=0, n=full->getNumGeometries(); i<n; ++i)
{
const Geometry* sub = full->getGeometryN(i);
const LineString* path = dynamic_cast<const LineString*>(sub);
if ( path ) {
// NOTE: we're making a copy here, wouldn't be needed
// for a simple predicate
to.push_back(_gf.createLineString(*path).release());
}
}
}
/* private */
bool
SharedPathsOp::isForward(const geom::LineString& edge,
const geom::Geometry& geom)
{
using namespace geos::linearref;
/*
ALGO:
1. find first point of edge on geom (linearref)
2. find second point of edge on geom (linearref)
3. if first < second, we're forward
PRECONDITIONS:
1. edge has at least 2 points
2. edge first two points are not equal
3. geom is simple
*/
const Coordinate& pt1 = edge.getCoordinateN(0);
const Coordinate& pt2 = edge.getCoordinateN(1);
/*
* We move the coordinate somewhat closer, to avoid
* vertices of the geometry being checked (geom).
*
* This is mostly only needed when one of the two points
* of the edge is an endpoint of a _closed_ geom.
* We have an unit test for this...
*/
Coordinate pt1i = LinearLocation::pointAlongSegmentByFraction(pt1, pt2, 0.1);
Coordinate pt2i = LinearLocation::pointAlongSegmentByFraction(pt1, pt2, 0.9);
LinearLocation l1 = LocationIndexOfPoint::indexOf(&geom, pt1i);
LinearLocation l2 = LocationIndexOfPoint::indexOf(&geom, pt2i);
return l1.compareTo(l2) < 0;
}
} // namespace geos.operation.sharedpaths
} // namespace geos::operation
} // namespace geos
<commit_msg>Include required GeometryFactory header (it's used)<commit_after>/**********************************************************************
* $Id$
*
* GEOS - Geometry Engine Open Source
* http://geos.refractions.net
*
* Copyright (C) 2010 Sandro Santilli <strk@keybit.net>
*
* This is free software; you can redistribute and/or modify it under
* the terms of the GNU Lesser General Public Licence as published
* by the Free Software Foundation.
* See the COPYING file for more information.
*
**********************************************************************
*
* Last port: original work
*
* Developed by Sandro Santilli (strk@keybit.net)
* for Faunalia (http://www.faunalia.it)
* with funding from Regione Toscana - Settore SISTEMA INFORMATIVO
* TERRITORIALE ED AMBIENTALE - for the project: "Sviluppo strumenti
* software per il trattamento di dati geografici basati su QuantumGIS
* e Postgis (CIG 0494241492)"
*
**********************************************************************/
#include <geos/operation/sharedpaths/SharedPathsOp.h>
#include <geos/geom/GeometryFactory.h>
#include <geos/geom/Geometry.h>
#include <geos/geom/LineString.h>
#include <geos/geom/MultiLineString.h>
#include <geos/linearref/LinearLocation.h>
#include <geos/linearref/LocationIndexOfPoint.h>
#include <geos/operation/overlay/OverlayOp.h>
#include <geos/util/IllegalArgumentException.h>
using namespace geos::geom;
namespace geos {
namespace operation { // geos.operation
namespace sharedpaths { // geos.operation.sharedpaths
/* public static */
void
SharedPathsOp::sharedPathsOp(const Geometry& g1, const Geometry& g2,
PathList& sameDirection,
PathList& oppositeDirection)
{
SharedPathsOp sp(g1, g2);
sp.getSharedPaths(sameDirection, oppositeDirection);
}
/* public */
SharedPathsOp::SharedPathsOp(
const geom::Geometry& g1, const geom::Geometry& g2)
:
_g1(g1),
_g2(g2),
_gf(*g1.getFactory())
{
checkLinealInput(_g1);
checkLinealInput(_g2);
}
/* private */
void
SharedPathsOp::checkLinealInput(const geom::Geometry& g)
{
if ( ! dynamic_cast<const LineString*>(&g) &&
! dynamic_cast<const MultiLineString*>(&g) )
{
throw util::IllegalArgumentException("Geometry is not lineal");
}
}
/* public */
void
SharedPathsOp::getSharedPaths(PathList& forwDir, PathList& backDir)
{
PathList paths;
findLinearIntersections(paths);
for (size_t i=0, n=paths.size(); i<n; ++i)
{
LineString* path = paths[i];
if ( isSameDirection(*path) ) forwDir.push_back(path);
else backDir.push_back(path);
}
}
/* static private */
void
SharedPathsOp::clearEdges(PathList& edges)
{
for (PathList::const_iterator
i=edges.begin(), e=edges.end();
i!=e; ++i)
{
delete *i;
}
edges.clear();
}
/* private */
void
SharedPathsOp::findLinearIntersections(PathList& to)
{
using geos::operation::overlay::OverlayOp;
// TODO: optionally use the tolerance,
// snapping _g2 over _g1 ?
std::auto_ptr<Geometry> full ( OverlayOp::overlayOp(
&_g1, &_g2, OverlayOp::opINTERSECTION) );
// NOTE: intersection of equal lines yelds splitted lines,
// should we sew them back ?
for (size_t i=0, n=full->getNumGeometries(); i<n; ++i)
{
const Geometry* sub = full->getGeometryN(i);
const LineString* path = dynamic_cast<const LineString*>(sub);
if ( path ) {
// NOTE: we're making a copy here, wouldn't be needed
// for a simple predicate
to.push_back(_gf.createLineString(*path).release());
}
}
}
/* private */
bool
SharedPathsOp::isForward(const geom::LineString& edge,
const geom::Geometry& geom)
{
using namespace geos::linearref;
/*
ALGO:
1. find first point of edge on geom (linearref)
2. find second point of edge on geom (linearref)
3. if first < second, we're forward
PRECONDITIONS:
1. edge has at least 2 points
2. edge first two points are not equal
3. geom is simple
*/
const Coordinate& pt1 = edge.getCoordinateN(0);
const Coordinate& pt2 = edge.getCoordinateN(1);
/*
* We move the coordinate somewhat closer, to avoid
* vertices of the geometry being checked (geom).
*
* This is mostly only needed when one of the two points
* of the edge is an endpoint of a _closed_ geom.
* We have an unit test for this...
*/
Coordinate pt1i = LinearLocation::pointAlongSegmentByFraction(pt1, pt2, 0.1);
Coordinate pt2i = LinearLocation::pointAlongSegmentByFraction(pt1, pt2, 0.9);
LinearLocation l1 = LocationIndexOfPoint::indexOf(&geom, pt1i);
LinearLocation l2 = LocationIndexOfPoint::indexOf(&geom, pt2i);
return l1.compareTo(l2) < 0;
}
} // namespace geos.operation.sharedpaths
} // namespace geos::operation
} // namespace geos
<|endoftext|> |
<commit_before>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2012 Anton Chernov <chernov.anton.mail@gmail.com>
// Copyright 2012 "LOTES TM" LLC <lotes.sis@gmail.com>
// Copyright 2012 Dennis Nienhüser <earthwings@gentoo.org>
//
#include "DeclarativeDataPlugin.h"
#include "DeclarativeDataPluginModel.h"
#include "DeclarativeDataPluginItem.h"
#include "MarbleDeclarativeWidget.h"
#include "MarbleDebug.h"
#include "MarbleWidget.h"
#include "MarbleModel.h"
#include <QtCore/QMetaObject>
#include <QtCore/QMetaProperty>
#include <QtScript/QScriptValue>
using namespace Marble;
class DeclarativeDataPluginPrivate {
public:
DeclarativeDataPlugin* q;
QString m_planet;
QString m_name;
QString m_nameId;
QString m_version;
QString m_guiString;
QString m_copyrightYears;
QString m_description;
QList<Marble::PluginAuthor> m_authors;
QString m_aboutText;
bool m_isInitialized;
QList<AbstractDataPluginItem *> m_items;
QList<DeclarativeDataPluginModel*> m_modelInstances;
QDeclarativeComponent* m_delegate;
QVariant m_model;
static int m_counter;
DeclarativeDataPluginPrivate( DeclarativeDataPlugin* q );
void parseChunk( DeclarativeDataPluginItem * item, GeoDataCoordinates &coordinates, const QString &key, const QVariant &value );
void addItem( DeclarativeDataPluginItem* item, const GeoDataCoordinates &coordinates );
void parseListModel( QAbstractListModel* listModel );
void parseObject( QObject* object );
};
int DeclarativeDataPluginPrivate::m_counter = 0;
DeclarativeDataPluginPrivate::DeclarativeDataPluginPrivate( DeclarativeDataPlugin* parent ) :
q( parent ), m_planet( "earth"), m_isInitialized( false ), m_delegate( 0 )
{
++m_counter;
}
void DeclarativeDataPluginPrivate::parseChunk( DeclarativeDataPluginItem *item, GeoDataCoordinates &coordinates, const QString &key, const QVariant &value )
{
if( key == "lat" || key == "latitude" ) {
coordinates.setLatitude( value.toDouble(), GeoDataCoordinates::Degree );
} else if( key == "lon" || key == "longitude" ) {
coordinates.setLongitude( value.toDouble(), GeoDataCoordinates::Degree );
} else if( key == "alt" || key == "altitude" ) {
coordinates.setAltitude( value.toDouble() );
} else {
item->setProperty( key.toAscii(), value );
}
}
void DeclarativeDataPluginPrivate::addItem( DeclarativeDataPluginItem *item, const GeoDataCoordinates &coordinates )
{
if ( coordinates.isValid() ) {
item->setCoordinate( coordinates );
item->setTarget( m_planet );
QVariant const idValue = item->property( "identifier" );
if ( idValue.isValid() && !idValue.toString().isEmpty() ) {
item->setId( idValue.toString() );
} else {
item->setId( coordinates.toString() ) ;
}
m_items.append( item );
} else {
delete item;
}
}
void DeclarativeDataPluginPrivate::parseListModel( QAbstractListModel *listModel )
{
QHash< int, QByteArray > roles = listModel->roleNames();
for( int i = 0; i < listModel->rowCount(); ++i ) {
GeoDataCoordinates coordinates;
QMap< int, QVariant > const itemData = listModel->itemData( listModel->index( i ) );
QHash< int, QByteArray >::const_iterator it = roles.constBegin();
DeclarativeDataPluginItem * item = new DeclarativeDataPluginItem( q );
for ( ; it != roles.constEnd(); ++it ) {
parseChunk( item, coordinates, it.value(), itemData.value( it.key() ) );
}
addItem( item, coordinates );
}
}
void DeclarativeDataPluginPrivate::parseObject( QObject *object )
{
int count;
QMetaObject const * meta = object->metaObject();
for( int i = 0; i < meta->propertyCount(); ++i ) {
if( qstrcmp( meta->property(i).name(), "count" ) == 0 ) {
count = meta->property(i).read( object ).toInt();
}
}
for( int i = 0; i < meta->methodCount(); ++i ) {
if( qstrcmp( meta->method(i).signature(), "get(int)" ) == 0 ) {
for( int j=0; j < count; ++j ) {
QScriptValue value;
meta->method(i).invoke( object, Qt::AutoConnection, Q_RETURN_ARG( QScriptValue , value), Q_ARG( int, j ) );
QObject * propertyObject = value.toQObject();
GeoDataCoordinates coordinates;
DeclarativeDataPluginItem * item = new DeclarativeDataPluginItem( q );
if ( propertyObject ) {
for( int k = 0; k < propertyObject->metaObject()->propertyCount(); ++k ) {
QString const propertyName = propertyObject->metaObject()->property( k ).name();
QVariant const value = propertyObject->metaObject()->property( k ).read( propertyObject );
parseChunk( item, coordinates, propertyName, value );
}
} else {
QScriptValueIterator it( value );
while ( it.hasNext() ) {
it.next();
parseChunk( item, coordinates, it.name(), it.value().toVariant() );
}
}
addItem( item, coordinates );
}
}
}
}
Marble::RenderPlugin *DeclarativeDataPlugin::newInstance(const Marble::MarbleModel *marbleModel) const
{
DeclarativeDataPlugin* instance = new DeclarativeDataPlugin( marbleModel );
instance->d->m_planet = d->m_planet;
instance->d->m_name = d->m_name;
instance->d->m_nameId = d->m_nameId;
instance->d->m_version = d->m_version;
instance->d->m_guiString = d->m_guiString;
instance->d->m_copyrightYears = d->m_copyrightYears;
instance->d->m_description = d->m_description;
instance->d->m_authors = d->m_authors;
instance->d->m_aboutText = d->m_aboutText;
instance->d->m_isInitialized = d->m_isInitialized;
instance->d->m_items = d->m_items;
instance->d->m_delegate = d->m_delegate;
instance->d->m_model = d->m_model;
instance->d->m_counter = d->m_counter;
DeclarativeDataPluginModel* dataModel = new DeclarativeDataPluginModel( marbleModel->pluginManager() );
dataModel->addItemsToList( d->m_items );
instance->setModel( dataModel );
connect( dataModel, SIGNAL( dataRequest( qreal, qreal, qreal, qreal ) ), this, SIGNAL( dataRequest( qreal, qreal, qreal, qreal ) ) );
d->m_modelInstances << dataModel;
return instance;
}
DeclarativeDataPlugin::DeclarativeDataPlugin( const Marble::MarbleModel *marbleModel )
: AbstractDataPlugin( marbleModel ), d( new DeclarativeDataPluginPrivate( this ) )
{
setEnabled( true );
setVisible( true );
}
DeclarativeDataPlugin::~DeclarativeDataPlugin()
{
delete d;
}
QString DeclarativeDataPlugin::planet() const
{
return d->m_planet;
}
void DeclarativeDataPlugin::setPlanet( const QString &planet )
{
if ( d->m_planet != planet ) {
d->m_planet = planet;
emit planetChanged();
}
}
QString DeclarativeDataPlugin::name() const
{
return d->m_name.isEmpty() ? "Anonymous DeclarativeDataPlugin" : d->m_name;
}
QString DeclarativeDataPlugin::guiString() const
{
return d->m_guiString.isEmpty() ? name() : d->m_guiString;
}
QString DeclarativeDataPlugin::nameId() const
{
return d->m_nameId.isEmpty() ? QString( "DeclarativeDataPlugin_%1" ).arg( d->m_counter ) : d->m_nameId;
}
QString DeclarativeDataPlugin::version() const
{
return d->m_version.isEmpty() ? "1.0" : d->m_version;
}
QString DeclarativeDataPlugin::description() const
{
return d->m_description;
}
QString DeclarativeDataPlugin::copyrightYears() const
{
return d->m_copyrightYears;
}
QList<PluginAuthor> DeclarativeDataPlugin::pluginAuthors() const
{
return d->m_authors;
}
QStringList DeclarativeDataPlugin::authors() const
{
QStringList authors;
foreach( const PluginAuthor& author, d->m_authors ) {
authors<< author.name << author.email;
}
return authors;
}
QString DeclarativeDataPlugin::aboutDataText() const
{
return d->m_aboutText;
}
QIcon DeclarativeDataPlugin::icon() const
{
return QIcon();
}
void DeclarativeDataPlugin::setName( const QString & name )
{
if( d->m_name != name ) {
d->m_name = name;
emit nameChanged();
}
}
void DeclarativeDataPlugin::setGuiString( const QString & guiString )
{
if( d->m_guiString != guiString ) {
d->m_guiString = guiString;
emit guiStringChanged();
}
}
void DeclarativeDataPlugin::setNameId( const QString & nameId )
{
if( d->m_nameId != nameId ) {
d->m_nameId = nameId;
emit nameIdChanged();
}
}
void DeclarativeDataPlugin::setVersion( const QString & version )
{
if( d->m_version != version ) {
d->m_version = version;
emit versionChanged();
}
}
void DeclarativeDataPlugin::setCopyrightYears( const QString & copyrightYears )
{
if( d->m_copyrightYears != copyrightYears ) {
d->m_copyrightYears = copyrightYears;
emit copyrightYearsChanged();
}
}
void DeclarativeDataPlugin::setDescription( const QString description )
{
if( d->m_description != description ) {
d->m_description = description;
emit descriptionChanged();
}
}
void DeclarativeDataPlugin::setAuthors( const QStringList & pluginAuthors )
{
if( pluginAuthors.size() % 2 == 0 ) {
QStringList::const_iterator it = pluginAuthors.constBegin();
while ( it != pluginAuthors.constEnd() ) {
QString name = *(++it);
QString email = *(++it);;
d->m_authors.append( PluginAuthor( name, email) );
}
emit authorsChanged();
}
}
void DeclarativeDataPlugin::setAboutDataText( const QString & aboutDataText )
{
if( d->m_aboutText != aboutDataText ) {
d->m_aboutText = aboutDataText;
emit aboutDataTextChanged();
}
}
QDeclarativeComponent *DeclarativeDataPlugin::delegate()
{
return d->m_delegate;
}
void DeclarativeDataPlugin::setDelegate( QDeclarativeComponent *delegate )
{
if ( delegate != d->m_delegate ) {
d->m_delegate = delegate;
emit delegateChanged();
}
}
void DeclarativeDataPlugin::initialize()
{
if( !model() ) {
setModel( new DeclarativeDataPluginModel( pluginManager(), this ) );
}
d->m_isInitialized = true;
}
bool DeclarativeDataPlugin::isInitialized() const
{
return d->m_isInitialized;
}
void DeclarativeDataPlugin::setDeclarativeModel( const QVariant &model )
{
d->m_model = model;
d->m_items.clear();
QObject* object = qVariantValue<QObject*>( model );
if( qobject_cast< QAbstractListModel* >( object ) ) {
d->parseListModel( qobject_cast< QAbstractListModel *>( object ) );
} else {
d->parseObject( object );
}
/** @todo: Listen for and reflect changes to the items in the model */
foreach( DeclarativeDataPluginModel* model, d->m_modelInstances ) {
model->addItemsToList( d->m_items );
}
emit declarativeModelChanged();
}
QVariant DeclarativeDataPlugin::declarativeModel()
{
return d->m_model;
}
#include "DeclarativeDataPlugin.moc"
<commit_msg>Avoid uninitialized variable<commit_after>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2012 Anton Chernov <chernov.anton.mail@gmail.com>
// Copyright 2012 "LOTES TM" LLC <lotes.sis@gmail.com>
// Copyright 2012 Dennis Nienhüser <earthwings@gentoo.org>
//
#include "DeclarativeDataPlugin.h"
#include "DeclarativeDataPluginModel.h"
#include "DeclarativeDataPluginItem.h"
#include "MarbleDeclarativeWidget.h"
#include "MarbleDebug.h"
#include "MarbleWidget.h"
#include "MarbleModel.h"
#include <QtCore/QMetaObject>
#include <QtCore/QMetaProperty>
#include <QtScript/QScriptValue>
using namespace Marble;
class DeclarativeDataPluginPrivate {
public:
DeclarativeDataPlugin* q;
QString m_planet;
QString m_name;
QString m_nameId;
QString m_version;
QString m_guiString;
QString m_copyrightYears;
QString m_description;
QList<Marble::PluginAuthor> m_authors;
QString m_aboutText;
bool m_isInitialized;
QList<AbstractDataPluginItem *> m_items;
QList<DeclarativeDataPluginModel*> m_modelInstances;
QDeclarativeComponent* m_delegate;
QVariant m_model;
static int m_counter;
DeclarativeDataPluginPrivate( DeclarativeDataPlugin* q );
void parseChunk( DeclarativeDataPluginItem * item, GeoDataCoordinates &coordinates, const QString &key, const QVariant &value );
void addItem( DeclarativeDataPluginItem* item, const GeoDataCoordinates &coordinates );
void parseListModel( QAbstractListModel* listModel );
void parseObject( QObject* object );
};
int DeclarativeDataPluginPrivate::m_counter = 0;
DeclarativeDataPluginPrivate::DeclarativeDataPluginPrivate( DeclarativeDataPlugin* parent ) :
q( parent ), m_planet( "earth"), m_isInitialized( false ), m_delegate( 0 )
{
++m_counter;
}
void DeclarativeDataPluginPrivate::parseChunk( DeclarativeDataPluginItem *item, GeoDataCoordinates &coordinates, const QString &key, const QVariant &value )
{
if( key == "lat" || key == "latitude" ) {
coordinates.setLatitude( value.toDouble(), GeoDataCoordinates::Degree );
} else if( key == "lon" || key == "longitude" ) {
coordinates.setLongitude( value.toDouble(), GeoDataCoordinates::Degree );
} else if( key == "alt" || key == "altitude" ) {
coordinates.setAltitude( value.toDouble() );
} else {
item->setProperty( key.toAscii(), value );
}
}
void DeclarativeDataPluginPrivate::addItem( DeclarativeDataPluginItem *item, const GeoDataCoordinates &coordinates )
{
if ( coordinates.isValid() ) {
item->setCoordinate( coordinates );
item->setTarget( m_planet );
QVariant const idValue = item->property( "identifier" );
if ( idValue.isValid() && !idValue.toString().isEmpty() ) {
item->setId( idValue.toString() );
} else {
item->setId( coordinates.toString() ) ;
}
m_items.append( item );
} else {
delete item;
}
}
void DeclarativeDataPluginPrivate::parseListModel( QAbstractListModel *listModel )
{
QHash< int, QByteArray > roles = listModel->roleNames();
for( int i = 0; i < listModel->rowCount(); ++i ) {
GeoDataCoordinates coordinates;
QMap< int, QVariant > const itemData = listModel->itemData( listModel->index( i ) );
QHash< int, QByteArray >::const_iterator it = roles.constBegin();
DeclarativeDataPluginItem * item = new DeclarativeDataPluginItem( q );
for ( ; it != roles.constEnd(); ++it ) {
parseChunk( item, coordinates, it.value(), itemData.value( it.key() ) );
}
addItem( item, coordinates );
}
}
void DeclarativeDataPluginPrivate::parseObject( QObject *object )
{
int count = 0;
QMetaObject const * meta = object->metaObject();
for( int i = 0; i < meta->propertyCount(); ++i ) {
if( qstrcmp( meta->property(i).name(), "count" ) == 0 ) {
count = meta->property(i).read( object ).toInt();
}
}
for( int i = 0; i < meta->methodCount(); ++i ) {
if( qstrcmp( meta->method(i).signature(), "get(int)" ) == 0 ) {
for( int j=0; j < count; ++j ) {
QScriptValue value;
meta->method(i).invoke( object, Qt::AutoConnection, Q_RETURN_ARG( QScriptValue , value), Q_ARG( int, j ) );
QObject * propertyObject = value.toQObject();
GeoDataCoordinates coordinates;
DeclarativeDataPluginItem * item = new DeclarativeDataPluginItem( q );
if ( propertyObject ) {
for( int k = 0; k < propertyObject->metaObject()->propertyCount(); ++k ) {
QString const propertyName = propertyObject->metaObject()->property( k ).name();
QVariant const value = propertyObject->metaObject()->property( k ).read( propertyObject );
parseChunk( item, coordinates, propertyName, value );
}
} else {
QScriptValueIterator it( value );
while ( it.hasNext() ) {
it.next();
parseChunk( item, coordinates, it.name(), it.value().toVariant() );
}
}
addItem( item, coordinates );
}
}
}
}
Marble::RenderPlugin *DeclarativeDataPlugin::newInstance(const Marble::MarbleModel *marbleModel) const
{
DeclarativeDataPlugin* instance = new DeclarativeDataPlugin( marbleModel );
instance->d->m_planet = d->m_planet;
instance->d->m_name = d->m_name;
instance->d->m_nameId = d->m_nameId;
instance->d->m_version = d->m_version;
instance->d->m_guiString = d->m_guiString;
instance->d->m_copyrightYears = d->m_copyrightYears;
instance->d->m_description = d->m_description;
instance->d->m_authors = d->m_authors;
instance->d->m_aboutText = d->m_aboutText;
instance->d->m_isInitialized = d->m_isInitialized;
instance->d->m_items = d->m_items;
instance->d->m_delegate = d->m_delegate;
instance->d->m_model = d->m_model;
instance->d->m_counter = d->m_counter;
DeclarativeDataPluginModel* dataModel = new DeclarativeDataPluginModel( marbleModel->pluginManager() );
dataModel->addItemsToList( d->m_items );
instance->setModel( dataModel );
connect( dataModel, SIGNAL( dataRequest( qreal, qreal, qreal, qreal ) ), this, SIGNAL( dataRequest( qreal, qreal, qreal, qreal ) ) );
d->m_modelInstances << dataModel;
return instance;
}
DeclarativeDataPlugin::DeclarativeDataPlugin( const Marble::MarbleModel *marbleModel )
: AbstractDataPlugin( marbleModel ), d( new DeclarativeDataPluginPrivate( this ) )
{
setEnabled( true );
setVisible( true );
}
DeclarativeDataPlugin::~DeclarativeDataPlugin()
{
delete d;
}
QString DeclarativeDataPlugin::planet() const
{
return d->m_planet;
}
void DeclarativeDataPlugin::setPlanet( const QString &planet )
{
if ( d->m_planet != planet ) {
d->m_planet = planet;
emit planetChanged();
}
}
QString DeclarativeDataPlugin::name() const
{
return d->m_name.isEmpty() ? "Anonymous DeclarativeDataPlugin" : d->m_name;
}
QString DeclarativeDataPlugin::guiString() const
{
return d->m_guiString.isEmpty() ? name() : d->m_guiString;
}
QString DeclarativeDataPlugin::nameId() const
{
return d->m_nameId.isEmpty() ? QString( "DeclarativeDataPlugin_%1" ).arg( d->m_counter ) : d->m_nameId;
}
QString DeclarativeDataPlugin::version() const
{
return d->m_version.isEmpty() ? "1.0" : d->m_version;
}
QString DeclarativeDataPlugin::description() const
{
return d->m_description;
}
QString DeclarativeDataPlugin::copyrightYears() const
{
return d->m_copyrightYears;
}
QList<PluginAuthor> DeclarativeDataPlugin::pluginAuthors() const
{
return d->m_authors;
}
QStringList DeclarativeDataPlugin::authors() const
{
QStringList authors;
foreach( const PluginAuthor& author, d->m_authors ) {
authors<< author.name << author.email;
}
return authors;
}
QString DeclarativeDataPlugin::aboutDataText() const
{
return d->m_aboutText;
}
QIcon DeclarativeDataPlugin::icon() const
{
return QIcon();
}
void DeclarativeDataPlugin::setName( const QString & name )
{
if( d->m_name != name ) {
d->m_name = name;
emit nameChanged();
}
}
void DeclarativeDataPlugin::setGuiString( const QString & guiString )
{
if( d->m_guiString != guiString ) {
d->m_guiString = guiString;
emit guiStringChanged();
}
}
void DeclarativeDataPlugin::setNameId( const QString & nameId )
{
if( d->m_nameId != nameId ) {
d->m_nameId = nameId;
emit nameIdChanged();
}
}
void DeclarativeDataPlugin::setVersion( const QString & version )
{
if( d->m_version != version ) {
d->m_version = version;
emit versionChanged();
}
}
void DeclarativeDataPlugin::setCopyrightYears( const QString & copyrightYears )
{
if( d->m_copyrightYears != copyrightYears ) {
d->m_copyrightYears = copyrightYears;
emit copyrightYearsChanged();
}
}
void DeclarativeDataPlugin::setDescription( const QString description )
{
if( d->m_description != description ) {
d->m_description = description;
emit descriptionChanged();
}
}
void DeclarativeDataPlugin::setAuthors( const QStringList & pluginAuthors )
{
if( pluginAuthors.size() % 2 == 0 ) {
QStringList::const_iterator it = pluginAuthors.constBegin();
while ( it != pluginAuthors.constEnd() ) {
QString name = *(++it);
QString email = *(++it);;
d->m_authors.append( PluginAuthor( name, email) );
}
emit authorsChanged();
}
}
void DeclarativeDataPlugin::setAboutDataText( const QString & aboutDataText )
{
if( d->m_aboutText != aboutDataText ) {
d->m_aboutText = aboutDataText;
emit aboutDataTextChanged();
}
}
QDeclarativeComponent *DeclarativeDataPlugin::delegate()
{
return d->m_delegate;
}
void DeclarativeDataPlugin::setDelegate( QDeclarativeComponent *delegate )
{
if ( delegate != d->m_delegate ) {
d->m_delegate = delegate;
emit delegateChanged();
}
}
void DeclarativeDataPlugin::initialize()
{
if( !model() ) {
setModel( new DeclarativeDataPluginModel( pluginManager(), this ) );
}
d->m_isInitialized = true;
}
bool DeclarativeDataPlugin::isInitialized() const
{
return d->m_isInitialized;
}
void DeclarativeDataPlugin::setDeclarativeModel( const QVariant &model )
{
d->m_model = model;
d->m_items.clear();
QObject* object = qVariantValue<QObject*>( model );
if( qobject_cast< QAbstractListModel* >( object ) ) {
d->parseListModel( qobject_cast< QAbstractListModel *>( object ) );
} else {
d->parseObject( object );
}
/** @todo: Listen for and reflect changes to the items in the model */
foreach( DeclarativeDataPluginModel* model, d->m_modelInstances ) {
model->addItemsToList( d->m_items );
}
emit declarativeModelChanged();
}
QVariant DeclarativeDataPlugin::declarativeModel()
{
return d->m_model;
}
#include "DeclarativeDataPlugin.moc"
<|endoftext|> |
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/
#include "searchresulttreeitemdelegate.h"
#include "searchresulttreeitemroles.h"
#include <QtGui/QTextDocument>
#include <QtGui/QPainter>
#include <QtGui/QAbstractTextDocumentLayout>
#include <QtGui/QApplication>
#include <QtCore/QModelIndex>
#include <QtCore/QDebug>
#include <math.h>
using namespace Find::Internal;
SearchResultTreeItemDelegate::SearchResultTreeItemDelegate(QObject *parent)
: QItemDelegate(parent)
{
}
void SearchResultTreeItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
static const int iconSize = 16;
painter->save();
QStyleOptionViewItemV3 opt = setOptions(index, option);
painter->setFont(opt.font);
QItemDelegate::drawBackground(painter, opt, index);
// ---- do the layout
QRect checkRect;
QRect pixmapRect;
QRect textRect;
// check mark
bool checkable = (index.model()->flags(index) & Qt::ItemIsUserCheckable);
Qt::CheckState checkState = Qt::Unchecked;
if (checkable) {
QVariant checkStateData = index.data(Qt::CheckStateRole);
checkState = static_cast<Qt::CheckState>(checkStateData.toInt());
checkRect = check(opt, opt.rect, checkStateData);
}
// icon
QIcon icon = index.model()->data(index, ItemDataRoles::ResultIconRole).value<QIcon>();
if (!icon.isNull()) {
pixmapRect = QRect(0, 0, iconSize, iconSize);
}
// text
textRect = opt.rect.adjusted(0, 0, checkRect.width() + pixmapRect.width(), 0);
// do layout
doLayout(opt, &checkRect, &pixmapRect, &textRect, false);
// ---- draw the items
// icon
if (!icon.isNull())
QItemDelegate::drawDecoration(painter, opt, pixmapRect, icon.pixmap(iconSize));
// line numbers
int lineNumberAreaWidth = drawLineNumber(painter, opt, textRect, index);
textRect.adjust(lineNumberAreaWidth, 0, 0, 0);
// selected text
QString displayString = index.model()->data(index, Qt::DisplayRole).toString();
drawMarker(painter, index, displayString, textRect);
// show number of subresults in displayString
if (index.model()->hasChildren(index)) {
displayString += QString::fromLatin1(" (")
+ QString::number(index.model()->rowCount(index))
+ QLatin1Char(')');
}
// text and focus/selection
QItemDelegate::drawDisplay(painter, opt, textRect, displayString);
QItemDelegate::drawFocus(painter, opt, opt.rect);
// check mark
if (checkable)
QItemDelegate::drawCheck(painter, opt, checkRect, checkState);
painter->restore();
}
int SearchResultTreeItemDelegate::drawLineNumber(QPainter *painter, const QStyleOptionViewItemV3 &option,
const QRect &rect,
const QModelIndex &index) const
{
static const int lineNumberAreaHorizontalPadding = 4;
int lineNumber = index.model()->data(index, ItemDataRoles::ResultLineNumberRole).toInt();
if (lineNumber < 1)
return 0;
const bool isSelected = option.state & QStyle::State_Selected;
int lineNumberDigits = (int)floor(log10((double)lineNumber)) + 1;
int minimumLineNumberDigits = qMax((int)m_minimumLineNumberDigits, lineNumberDigits);
int fontWidth = painter->fontMetrics().width(QString(minimumLineNumberDigits, QLatin1Char('0')));
int lineNumberAreaWidth = lineNumberAreaHorizontalPadding + fontWidth + lineNumberAreaHorizontalPadding;
QRect lineNumberAreaRect(rect);
lineNumberAreaRect.setWidth(lineNumberAreaWidth);
QPalette::ColorGroup cg = QPalette::Normal;
if (!(option.state & QStyle::State_Active))
cg = QPalette::Inactive;
else if (!(option.state & QStyle::State_Enabled))
cg = QPalette::Disabled;
painter->fillRect(lineNumberAreaRect, QBrush(isSelected ?
option.palette.brush(cg, QPalette::Highlight) :
option.palette.color(cg, QPalette::Base).darker(111)));
QStyleOptionViewItemV3 opt = option;
opt.displayAlignment = Qt::AlignRight | Qt::AlignVCenter;
opt.palette.setColor(cg, QPalette::Text, Qt::darkGray);
const QStyle *style = QApplication::style();
const int textMargin = style->pixelMetric(QStyle::PM_FocusFrameHMargin, 0, 0) + 1;
const QRect rowRect = lineNumberAreaRect.adjusted(-textMargin, 0, textMargin-lineNumberAreaHorizontalPadding, 0);
QItemDelegate::drawDisplay(painter, opt, rowRect, QString::number(lineNumber));
return lineNumberAreaWidth;
}
void SearchResultTreeItemDelegate::drawMarker(QPainter *painter, const QModelIndex &index, const QString text,
const QRect &rect) const
{
int searchTermStart = index.model()->data(index, ItemDataRoles::SearchTermStartRole).toInt();
int searchTermLength = index.model()->data(index, ItemDataRoles::SearchTermLengthRole).toInt();
if (searchTermStart < 0 || searchTermStart >= text.length() || searchTermLength < 1)
return;
// clip searchTermLength to end of line
searchTermLength = qMin(searchTermLength, text.length() - searchTermStart);
const int textMargin = QApplication::style()->pixelMetric(QStyle::PM_FocusFrameHMargin) + 1;
int searchTermStartPixels = painter->fontMetrics().width(text.left(searchTermStart));
int searchTermLengthPixels = painter->fontMetrics().width(text.mid(searchTermStart, searchTermLength));
QRect resultHighlightRect(rect);
resultHighlightRect.setLeft(resultHighlightRect.left() + searchTermStartPixels + textMargin - 1); // -1: Cosmetics
resultHighlightRect.setRight(resultHighlightRect.left() + searchTermLengthPixels + 1); // +1: Cosmetics
painter->fillRect(resultHighlightRect, QBrush(qRgb(255, 240, 120)));
}
<commit_msg>Handle method rename in Qt5.<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/
#include "searchresulttreeitemdelegate.h"
#include "searchresulttreeitemroles.h"
#include <QtGui/QTextDocument>
#include <QtGui/QPainter>
#include <QtGui/QAbstractTextDocumentLayout>
#include <QtGui/QApplication>
#include <QtCore/QModelIndex>
#include <QtCore/QDebug>
#include <math.h>
using namespace Find::Internal;
SearchResultTreeItemDelegate::SearchResultTreeItemDelegate(QObject *parent)
: QItemDelegate(parent)
{
}
void SearchResultTreeItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
static const int iconSize = 16;
painter->save();
QStyleOptionViewItemV3 opt = setOptions(index, option);
painter->setFont(opt.font);
QItemDelegate::drawBackground(painter, opt, index);
// ---- do the layout
QRect checkRect;
QRect pixmapRect;
QRect textRect;
// check mark
bool checkable = (index.model()->flags(index) & Qt::ItemIsUserCheckable);
Qt::CheckState checkState = Qt::Unchecked;
if (checkable) {
QVariant checkStateData = index.data(Qt::CheckStateRole);
checkState = static_cast<Qt::CheckState>(checkStateData.toInt());
#if QT_VERSION >= 0x050000
checkRect = doCheck(opt, opt.rect, checkStateData);
#else // Qt4
checkRect = check(opt, opt.rect, checkStateData);
#endif
}
// icon
QIcon icon = index.model()->data(index, ItemDataRoles::ResultIconRole).value<QIcon>();
if (!icon.isNull()) {
pixmapRect = QRect(0, 0, iconSize, iconSize);
}
// text
textRect = opt.rect.adjusted(0, 0, checkRect.width() + pixmapRect.width(), 0);
// do layout
doLayout(opt, &checkRect, &pixmapRect, &textRect, false);
// ---- draw the items
// icon
if (!icon.isNull())
QItemDelegate::drawDecoration(painter, opt, pixmapRect, icon.pixmap(iconSize));
// line numbers
int lineNumberAreaWidth = drawLineNumber(painter, opt, textRect, index);
textRect.adjust(lineNumberAreaWidth, 0, 0, 0);
// selected text
QString displayString = index.model()->data(index, Qt::DisplayRole).toString();
drawMarker(painter, index, displayString, textRect);
// show number of subresults in displayString
if (index.model()->hasChildren(index)) {
displayString += QString::fromLatin1(" (")
+ QString::number(index.model()->rowCount(index))
+ QLatin1Char(')');
}
// text and focus/selection
QItemDelegate::drawDisplay(painter, opt, textRect, displayString);
QItemDelegate::drawFocus(painter, opt, opt.rect);
// check mark
if (checkable)
QItemDelegate::drawCheck(painter, opt, checkRect, checkState);
painter->restore();
}
int SearchResultTreeItemDelegate::drawLineNumber(QPainter *painter, const QStyleOptionViewItemV3 &option,
const QRect &rect,
const QModelIndex &index) const
{
static const int lineNumberAreaHorizontalPadding = 4;
int lineNumber = index.model()->data(index, ItemDataRoles::ResultLineNumberRole).toInt();
if (lineNumber < 1)
return 0;
const bool isSelected = option.state & QStyle::State_Selected;
int lineNumberDigits = (int)floor(log10((double)lineNumber)) + 1;
int minimumLineNumberDigits = qMax((int)m_minimumLineNumberDigits, lineNumberDigits);
int fontWidth = painter->fontMetrics().width(QString(minimumLineNumberDigits, QLatin1Char('0')));
int lineNumberAreaWidth = lineNumberAreaHorizontalPadding + fontWidth + lineNumberAreaHorizontalPadding;
QRect lineNumberAreaRect(rect);
lineNumberAreaRect.setWidth(lineNumberAreaWidth);
QPalette::ColorGroup cg = QPalette::Normal;
if (!(option.state & QStyle::State_Active))
cg = QPalette::Inactive;
else if (!(option.state & QStyle::State_Enabled))
cg = QPalette::Disabled;
painter->fillRect(lineNumberAreaRect, QBrush(isSelected ?
option.palette.brush(cg, QPalette::Highlight) :
option.palette.color(cg, QPalette::Base).darker(111)));
QStyleOptionViewItemV3 opt = option;
opt.displayAlignment = Qt::AlignRight | Qt::AlignVCenter;
opt.palette.setColor(cg, QPalette::Text, Qt::darkGray);
const QStyle *style = QApplication::style();
const int textMargin = style->pixelMetric(QStyle::PM_FocusFrameHMargin, 0, 0) + 1;
const QRect rowRect = lineNumberAreaRect.adjusted(-textMargin, 0, textMargin-lineNumberAreaHorizontalPadding, 0);
QItemDelegate::drawDisplay(painter, opt, rowRect, QString::number(lineNumber));
return lineNumberAreaWidth;
}
void SearchResultTreeItemDelegate::drawMarker(QPainter *painter, const QModelIndex &index, const QString text,
const QRect &rect) const
{
int searchTermStart = index.model()->data(index, ItemDataRoles::SearchTermStartRole).toInt();
int searchTermLength = index.model()->data(index, ItemDataRoles::SearchTermLengthRole).toInt();
if (searchTermStart < 0 || searchTermStart >= text.length() || searchTermLength < 1)
return;
// clip searchTermLength to end of line
searchTermLength = qMin(searchTermLength, text.length() - searchTermStart);
const int textMargin = QApplication::style()->pixelMetric(QStyle::PM_FocusFrameHMargin) + 1;
int searchTermStartPixels = painter->fontMetrics().width(text.left(searchTermStart));
int searchTermLengthPixels = painter->fontMetrics().width(text.mid(searchTermStart, searchTermLength));
QRect resultHighlightRect(rect);
resultHighlightRect.setLeft(resultHighlightRect.left() + searchTermStartPixels + textMargin - 1); // -1: Cosmetics
resultHighlightRect.setRight(resultHighlightRect.left() + searchTermLengthPixels + 1); // +1: Cosmetics
painter->fillRect(resultHighlightRect, QBrush(qRgb(255, 240, 120)));
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the plugins of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qwaylanddisplay.h"
#include "qwaylandwindow.h"
#include "qwaylandscreen.h"
#include "qwaylandcursor.h"
#include "qwaylandinputdevice.h"
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
struct wl_surface *QWaylandDisplay::createSurface()
{
return wl_compositor_create_surface(mCompositor);
}
struct wl_buffer *QWaylandDisplay::createShmBuffer(int fd,
int width, int height,
uint32_t stride,
struct wl_visual *visual)
{
return wl_shm_create_buffer(mShm, fd, width, height, stride, visual);
}
struct wl_visual *QWaylandDisplay::rgbVisual()
{
return wl_display_get_rgb_visual(mDisplay);
}
struct wl_visual *QWaylandDisplay::argbVisual()
{
return wl_display_get_argb_visual(mDisplay);
}
struct wl_visual *QWaylandDisplay::argbPremultipliedVisual()
{
return wl_display_get_premultiplied_argb_visual(mDisplay);
}
struct wl_egl_display *QWaylandDisplay::nativeDisplay()
{
return mNativeEglDisplay;
}
void QWaylandDisplay::shellHandleConfigure(void *data, struct wl_shell *shell,
uint32_t time, uint32_t edges,
struct wl_surface *surface,
int32_t width, int32_t height)
{
Q_UNUSED(data);
Q_UNUSED(shell);
Q_UNUSED(time);
Q_UNUSED(edges);
QWaylandWindow *ww = (QWaylandWindow *) wl_surface_get_user_data(surface);
ww->configure(time, edges, 0, 0, width, height);
}
const struct wl_shell_listener QWaylandDisplay::shellListener = {
QWaylandDisplay::shellHandleConfigure,
};
void QWaylandDisplay::outputHandleGeometry(void *data,
struct wl_output *output,
int32_t x, int32_t y,
int32_t width, int32_t height)
{
QWaylandDisplay *waylandDisplay = (QWaylandDisplay *) data;
QRect outputRect = QRect(x, y, width, height);
waylandDisplay->createNewScreen(output, outputRect);
}
const struct wl_output_listener QWaylandDisplay::outputListener = {
QWaylandDisplay::outputHandleGeometry
};
void QWaylandDisplay::displayHandleGlobal(struct wl_display *display,
uint32_t id,
const char *interface,
uint32_t version, void *data)
{
Q_UNUSED(version);
QWaylandDisplay *qwd = (QWaylandDisplay *) data;
if (strcmp(interface, "compositor") == 0) {
qwd->mCompositor = wl_compositor_create(display, id);
} else if (strcmp(interface, "shm") == 0) {
qwd->mShm = wl_shm_create(display, id);
} else if (strcmp(interface, "shell") == 0) {
qwd->mShell = wl_shell_create(display, id);
wl_shell_add_listener(qwd->mShell, &shellListener, qwd);
} else if (strcmp(interface, "output") == 0) {
struct wl_output *output = wl_output_create(display, id);
wl_output_add_listener(output, &outputListener, qwd);
} else if (strcmp(interface, "input_device") == 0) {
QWaylandInputDevice *inputDevice =
new QWaylandInputDevice(display, id);
qwd->mInputDevices.append(inputDevice);
}
}
void QWaylandDisplay::eventDispatcher(void)
{
wl_display_iterate(mDisplay, WL_DISPLAY_READABLE);
}
int
QWaylandDisplay::sourceUpdate(uint32_t mask, void *data)
{
QWaylandDisplay *qwd = (QWaylandDisplay *) data;
/* FIXME: We get a callback here when we ask wl_display for the
* fd, but at that point we don't have the socket notifier as we
* need the fd to create that. We'll probably need to split that
* API into get_fd and set_update_func functions. */
if (qwd->mWriteNotifier == NULL)
return 0;
qwd->mWriteNotifier->setEnabled(mask & WL_DISPLAY_WRITABLE);
return 0;
}
void QWaylandDisplay::flushRequests(void)
{
wl_display_iterate(mDisplay, WL_DISPLAY_WRITABLE);
}
QWaylandDisplay::QWaylandDisplay(void)
: mWriteNotifier(0)
{
#ifdef QT_WAYLAND_GL_SUPPORT
EGLint major, minor;
#endif
mDisplay = wl_display_connect(NULL);
if (mDisplay == NULL) {
fprintf(stderr, "failed to create display: %m\n");
return;
}
wl_display_add_global_listener(mDisplay,
QWaylandDisplay::displayHandleGlobal, this);
#ifdef QT_WAYLAND_GL_SUPPORT
mNativeEglDisplay = wl_egl_display_create(mDisplay);
mEglDisplay = eglGetDisplay((EGLNativeDisplayType)mNativeEglDisplay);
if (mEglDisplay == NULL) {
qWarning("EGL not available");
} else {
if (!eglInitialize(mEglDisplay, &major, &minor)) {
qWarning("failed to initialize EGL display");
return;
}
}
#else
mNativeEglDisplay = 0;
mEglDisplay = 0;
#endif
eventDispatcher();
int fd = wl_display_get_fd(mDisplay, sourceUpdate, this);
mReadNotifier = new QSocketNotifier(fd, QSocketNotifier::Read, this);
connect(mReadNotifier,
SIGNAL(activated(int)), this, SLOT(eventDispatcher()));
mWriteNotifier = new QSocketNotifier(fd, QSocketNotifier::Write, this);
connect(mWriteNotifier,
SIGNAL(activated(int)), this, SLOT(flushRequests()));
mWriteNotifier->setEnabled(false);
}
QWaylandDisplay::~QWaylandDisplay(void)
{
close(mFd);
#ifdef QT_WAYLAND_GL_SUPPORT
eglTerminate(mEglDisplay);
#endif
wl_display_destroy(mDisplay);
}
void QWaylandDisplay::createNewScreen(struct wl_output *output, QRect geometry)
{
QWaylandScreen *waylandScreen = new QWaylandScreen(this,output,geometry);
mScreens.append(waylandScreen);
}
void QWaylandDisplay::syncCallback(wl_display_sync_func_t func, void *data)
{
wl_display_sync_callback(mDisplay, func, data);
}
void QWaylandDisplay::frameCallback(wl_display_frame_func_t func, void *data)
{
wl_display_frame_callback(mDisplay, func, data);
}
<commit_msg>Lighthouse: Fix a block for wayland with gl support<commit_after>/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the plugins of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qwaylanddisplay.h"
#include "qwaylandwindow.h"
#include "qwaylandscreen.h"
#include "qwaylandcursor.h"
#include "qwaylandinputdevice.h"
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
struct wl_surface *QWaylandDisplay::createSurface()
{
return wl_compositor_create_surface(mCompositor);
}
struct wl_buffer *QWaylandDisplay::createShmBuffer(int fd,
int width, int height,
uint32_t stride,
struct wl_visual *visual)
{
return wl_shm_create_buffer(mShm, fd, width, height, stride, visual);
}
struct wl_visual *QWaylandDisplay::rgbVisual()
{
return wl_display_get_rgb_visual(mDisplay);
}
struct wl_visual *QWaylandDisplay::argbVisual()
{
return wl_display_get_argb_visual(mDisplay);
}
struct wl_visual *QWaylandDisplay::argbPremultipliedVisual()
{
return wl_display_get_premultiplied_argb_visual(mDisplay);
}
struct wl_egl_display *QWaylandDisplay::nativeDisplay()
{
return mNativeEglDisplay;
}
void QWaylandDisplay::shellHandleConfigure(void *data, struct wl_shell *shell,
uint32_t time, uint32_t edges,
struct wl_surface *surface,
int32_t width, int32_t height)
{
Q_UNUSED(data);
Q_UNUSED(shell);
Q_UNUSED(time);
Q_UNUSED(edges);
QWaylandWindow *ww = (QWaylandWindow *) wl_surface_get_user_data(surface);
ww->configure(time, edges, 0, 0, width, height);
}
const struct wl_shell_listener QWaylandDisplay::shellListener = {
QWaylandDisplay::shellHandleConfigure,
};
void QWaylandDisplay::outputHandleGeometry(void *data,
struct wl_output *output,
int32_t x, int32_t y,
int32_t width, int32_t height)
{
QWaylandDisplay *waylandDisplay = (QWaylandDisplay *) data;
QRect outputRect = QRect(x, y, width, height);
waylandDisplay->createNewScreen(output, outputRect);
}
const struct wl_output_listener QWaylandDisplay::outputListener = {
QWaylandDisplay::outputHandleGeometry
};
void QWaylandDisplay::displayHandleGlobal(struct wl_display *display,
uint32_t id,
const char *interface,
uint32_t version, void *data)
{
Q_UNUSED(version);
QWaylandDisplay *qwd = (QWaylandDisplay *) data;
if (strcmp(interface, "compositor") == 0) {
qwd->mCompositor = wl_compositor_create(display, id);
} else if (strcmp(interface, "shm") == 0) {
qwd->mShm = wl_shm_create(display, id);
} else if (strcmp(interface, "shell") == 0) {
qwd->mShell = wl_shell_create(display, id);
wl_shell_add_listener(qwd->mShell, &shellListener, qwd);
} else if (strcmp(interface, "output") == 0) {
struct wl_output *output = wl_output_create(display, id);
wl_output_add_listener(output, &outputListener, qwd);
} else if (strcmp(interface, "input_device") == 0) {
QWaylandInputDevice *inputDevice =
new QWaylandInputDevice(display, id);
qwd->mInputDevices.append(inputDevice);
}
}
void QWaylandDisplay::eventDispatcher(void)
{
wl_display_iterate(mDisplay, WL_DISPLAY_READABLE);
}
int
QWaylandDisplay::sourceUpdate(uint32_t mask, void *data)
{
QWaylandDisplay *qwd = (QWaylandDisplay *) data;
/* FIXME: We get a callback here when we ask wl_display for the
* fd, but at that point we don't have the socket notifier as we
* need the fd to create that. We'll probably need to split that
* API into get_fd and set_update_func functions. */
if (qwd->mWriteNotifier == NULL)
return 0;
qwd->mWriteNotifier->setEnabled(mask & WL_DISPLAY_WRITABLE);
return 0;
}
void QWaylandDisplay::flushRequests(void)
{
wl_display_iterate(mDisplay, WL_DISPLAY_WRITABLE);
}
QWaylandDisplay::QWaylandDisplay(void)
: mWriteNotifier(0)
{
#ifdef QT_WAYLAND_GL_SUPPORT
EGLint major, minor;
#endif
mDisplay = wl_display_connect(NULL);
if (mDisplay == NULL) {
fprintf(stderr, "failed to create display: %m\n");
return;
}
wl_display_add_global_listener(mDisplay,
QWaylandDisplay::displayHandleGlobal, this);
#ifdef QT_WAYLAND_GL_SUPPORT
mNativeEglDisplay = wl_egl_display_create(mDisplay);
#else
mNativeEglDisplay = 0;
#endif
eventDispatcher();
#ifdef QT_WAYLAND_GL_SUPPORT
mEglDisplay = eglGetDisplay((EGLNativeDisplayType)mNativeEglDisplay);
if (mEglDisplay == NULL) {
qWarning("EGL not available");
} else {
if (!eglInitialize(mEglDisplay, &major, &minor)) {
qWarning("failed to initialize EGL display");
return;
}
}
#else
mEglDisplay = 0;
#endif
int fd = wl_display_get_fd(mDisplay, sourceUpdate, this);
mReadNotifier = new QSocketNotifier(fd, QSocketNotifier::Read, this);
connect(mReadNotifier,
SIGNAL(activated(int)), this, SLOT(eventDispatcher()));
mWriteNotifier = new QSocketNotifier(fd, QSocketNotifier::Write, this);
connect(mWriteNotifier,
SIGNAL(activated(int)), this, SLOT(flushRequests()));
mWriteNotifier->setEnabled(false);
}
QWaylandDisplay::~QWaylandDisplay(void)
{
close(mFd);
#ifdef QT_WAYLAND_GL_SUPPORT
eglTerminate(mEglDisplay);
#endif
wl_display_destroy(mDisplay);
}
void QWaylandDisplay::createNewScreen(struct wl_output *output, QRect geometry)
{
QWaylandScreen *waylandScreen = new QWaylandScreen(this,output,geometry);
mScreens.append(waylandScreen);
}
void QWaylandDisplay::syncCallback(wl_display_sync_func_t func, void *data)
{
wl_display_sync_callback(mDisplay, func, data);
}
void QWaylandDisplay::frameCallback(wl_display_frame_func_t func, void *data)
{
wl_display_frame_callback(mDisplay, func, data);
}
<|endoftext|> |
<commit_before>/** @file
@brief Implementation
@date 2014
@author
Sensics, Inc.
<http://sensics.com/osvr>
*/
// Copyright 2014 Sensics, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Internal Includes
#include "VrpnBasedConnection.h"
#include "VrpnMessageType.h"
#include "VrpnConnectionDevice.h"
#include "VrpnConnectionKind.h"
#include <osvr/Util/Verbosity.h>
// Library/third-party includes
// - none
// Standard includes
// - none
namespace osvr {
namespace connection {
namespace messageid {
/// @brief Return the string identifying VRPN ping messages
const char *vrpnPing() { return "vrpn_Base ping_message"; }
} // namespace messageid
VrpnBasedConnection::VrpnBasedConnection(ConnectionType type) {
switch (type) {
case VRPN_LOCAL_ONLY: {
m_initConnection("localhost");
break;
}
case VRPN_SHARED: {
m_initConnection();
break;
}
case VRPN_LOOPBACK: {
m_initConnection("loopback:");
break;
}
}
}
VrpnBasedConnection::VrpnBasedConnection(
boost::optional<std::string const &> iface, boost::optional<int> port) {
int myPort = port.get_value_or(0);
if (iface && !(iface->empty())) {
m_initConnection(iface->c_str(), myPort);
} else {
m_initConnection(nullptr, myPort);
}
}
void VrpnBasedConnection::m_initConnection(const char iface[], int port) {
if (!m_network.isUp()) {
OSVR_DEV_VERBOSE("Network error: " << m_network.getError());
throw std::runtime_error(m_network.getError());
}
if (0 == port) {
port = vrpn_DEFAULT_LISTEN_PORT_NO;
}
m_vrpnConnection = vrpn_ConnectionPtr::create_server_connection(
port, nullptr, nullptr, iface);
}
MessageTypePtr
VrpnBasedConnection::m_registerMessageType(std::string const &messageId) {
MessageTypePtr ret(new VrpnMessageType(messageId, m_vrpnConnection));
return ret;
}
ConnectionDevicePtr
VrpnBasedConnection::m_createConnectionDevice(DeviceInitObject &init) {
ConnectionDevicePtr ret =
make_shared<VrpnConnectionDevice>(init, m_vrpnConnection);
return ret;
}
void VrpnBasedConnection::m_registerConnectionHandler(
std::function<void()> handler) {
if (m_connectionHandlers.empty()) {
/// got connection handler
m_vrpnConnection->register_handler(
m_vrpnConnection->register_message_type(vrpn_got_connection),
&m_connectionHandler, static_cast<void *>(this),
vrpn_ANY_SENDER);
/// Ping handler
#if 0
m_vrpnConnection->register_handler(
m_vrpnConnection->register_message_type(messageid::vrpnPing()),
&m_connectionHandler, static_cast<void *>(this),
vrpn_ANY_SENDER);
#endif
}
m_connectionHandlers.push_back(handler);
}
int VrpnBasedConnection::m_connectionHandler(void *userdata,
vrpn_HANDLERPARAM) {
VrpnBasedConnection *conn =
static_cast<VrpnBasedConnection *>(userdata);
for (auto const &f : conn->m_connectionHandlers) {
f();
}
return 0;
}
void VrpnBasedConnection::m_process() { m_vrpnConnection->mainloop(); }
VrpnBasedConnection::~VrpnBasedConnection() {
/// @todo wait until all async threads are done
}
void *VrpnBasedConnection::getUnderlyingObject() {
return static_cast<void *>(m_vrpnConnection.get());
}
const char *VrpnBasedConnection::getConnectionKindID() {
return getVRPNConnectionKindID();
}
} // namespace connection
} // namespace osvr
<commit_msg>Add a todo based on profiling investigation<commit_after>/** @file
@brief Implementation
@date 2014
@author
Sensics, Inc.
<http://sensics.com/osvr>
*/
// Copyright 2014 Sensics, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Internal Includes
#include "VrpnBasedConnection.h"
#include "VrpnMessageType.h"
#include "VrpnConnectionDevice.h"
#include "VrpnConnectionKind.h"
#include <osvr/Util/Verbosity.h>
// Library/third-party includes
// - none
// Standard includes
// - none
namespace osvr {
namespace connection {
namespace messageid {
/// @brief Return the string identifying VRPN ping messages
const char *vrpnPing() { return "vrpn_Base ping_message"; }
} // namespace messageid
VrpnBasedConnection::VrpnBasedConnection(ConnectionType type) {
switch (type) {
case VRPN_LOCAL_ONLY: {
m_initConnection("localhost");
break;
}
case VRPN_SHARED: {
m_initConnection();
break;
}
case VRPN_LOOPBACK: {
m_initConnection("loopback:");
break;
}
}
}
VrpnBasedConnection::VrpnBasedConnection(
boost::optional<std::string const &> iface, boost::optional<int> port) {
int myPort = port.get_value_or(0);
if (iface && !(iface->empty())) {
m_initConnection(iface->c_str(), myPort);
} else {
m_initConnection(nullptr, myPort);
}
}
void VrpnBasedConnection::m_initConnection(const char iface[], int port) {
if (!m_network.isUp()) {
OSVR_DEV_VERBOSE("Network error: " << m_network.getError());
throw std::runtime_error(m_network.getError());
}
if (0 == port) {
port = vrpn_DEFAULT_LISTEN_PORT_NO;
}
m_vrpnConnection = vrpn_ConnectionPtr::create_server_connection(
port, nullptr, nullptr, iface);
}
MessageTypePtr
VrpnBasedConnection::m_registerMessageType(std::string const &messageId) {
MessageTypePtr ret(new VrpnMessageType(messageId, m_vrpnConnection));
return ret;
}
ConnectionDevicePtr
VrpnBasedConnection::m_createConnectionDevice(DeviceInitObject &init) {
ConnectionDevicePtr ret =
make_shared<VrpnConnectionDevice>(init, m_vrpnConnection);
return ret;
}
void VrpnBasedConnection::m_registerConnectionHandler(
std::function<void()> handler) {
if (m_connectionHandlers.empty()) {
/// got connection handler
m_vrpnConnection->register_handler(
m_vrpnConnection->register_message_type(vrpn_got_connection),
&m_connectionHandler, static_cast<void *>(this),
vrpn_ANY_SENDER);
/// Ping handler
#if 0
m_vrpnConnection->register_handler(
m_vrpnConnection->register_message_type(messageid::vrpnPing()),
&m_connectionHandler, static_cast<void *>(this),
vrpn_ANY_SENDER);
#endif
}
m_connectionHandlers.push_back(handler);
}
int VrpnBasedConnection::m_connectionHandler(void *userdata,
vrpn_HANDLERPARAM) {
VrpnBasedConnection *conn =
static_cast<VrpnBasedConnection *>(userdata);
for (auto const &f : conn->m_connectionHandlers) {
f();
}
return 0;
}
void VrpnBasedConnection::m_process() {
/// @todo there's an optional timeout here - see that we use it properly
m_vrpnConnection->mainloop();
}
VrpnBasedConnection::~VrpnBasedConnection() {
/// @todo wait until all async threads are done
}
void *VrpnBasedConnection::getUnderlyingObject() {
return static_cast<void *>(m_vrpnConnection.get());
}
const char *VrpnBasedConnection::getConnectionKindID() {
return getVRPNConnectionKindID();
}
} // namespace connection
} // namespace osvr
<|endoftext|> |
<commit_before>/***************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2008 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Qt Software Information (qt-info@nokia.com)
**
**
** Non-Open Source Usage
**
** Licensees may use this file in accordance with the Qt Beta Version
** License Agreement, Agreement version 2.2 provided with the Software or,
** alternatively, in accordance with the terms contained in a written
** agreement between you and Nokia.
**
** GNU General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU General
** Public License versions 2.0 or 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the packaging
** of this file. Please review the following information to ensure GNU
** General Public Licensing requirements will be met:
**
** http://www.fsf.org/licensing/licenses/info/GPLv2.html and
** http://www.gnu.org/copyleft/gpl.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt GPL Exception
** version 1.3, included in the file GPL_EXCEPTION.txt in this package.
**
***************************************************************************/
#include "completionwidget.h"
#include "completionsupport.h"
#include "icompletioncollector.h"
#include <texteditor/itexteditable.h>
#include <utils/qtcassert.h>
#include <QtCore/QEvent>
#include <QtGui/QApplication>
#include <QtGui/QDesktopWidget>
#include <QtGui/QKeyEvent>
#include <QtGui/QVBoxLayout>
#include <limits.h>
using namespace TextEditor;
using namespace TextEditor::Internal;
#define NUMBER_OF_VISIBLE_ITEMS 10
class AutoCompletionModel : public QAbstractListModel
{
public:
AutoCompletionModel(QObject *parent, const QList<CompletionItem> &items);
inline const CompletionItem &itemAt(const QModelIndex &index) const
{ return m_items.at(index.row()); }
void setItems(const QList<CompletionItem> &items);
int rowCount(const QModelIndex &parent = QModelIndex()) const;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
private:
QList<CompletionItem> m_items;
};
AutoCompletionModel::AutoCompletionModel(QObject *parent, const QList<CompletionItem> &items)
: QAbstractListModel(parent)
{
m_items = items;
}
void AutoCompletionModel::setItems(const QList<CompletionItem> &items)
{
m_items = items;
reset();
}
int AutoCompletionModel::rowCount(const QModelIndex &) const
{
return m_items.count();
}
QVariant AutoCompletionModel::data(const QModelIndex &index, int role) const
{
if (index.row() >= m_items.count())
return QVariant();
if (role == Qt::DisplayRole) {
return itemAt(index).m_text;
} else if (role == Qt::DecorationRole) {
return itemAt(index).m_icon;
} else if (role == Qt::ToolTipRole) {
return itemAt(index).m_details;
}
return QVariant();
}
CompletionWidget::CompletionWidget(CompletionSupport *support, ITextEditable *editor)
: QListView(),
m_blockFocusOut(false),
m_editor(editor),
m_editorWidget(editor->widget()),
m_model(0),
m_support(support)
{
QTC_ASSERT(m_editorWidget, return);
setUniformItemSizes(true);
setSelectionBehavior(QAbstractItemView::SelectItems);
setSelectionMode(QAbstractItemView::SingleSelection);
connect(this, SIGNAL(activated(const QModelIndex &)),
this, SLOT(completionActivated(const QModelIndex &)));
// We disable the frame on this list view and use a QFrame around it instead.
// This fixes the missing frame on Mac and improves the look with QGTKStyle.
m_popupFrame = new QFrame(0, Qt::Popup);
m_popupFrame->setFrameStyle(frameStyle());
setFrameStyle(QFrame::NoFrame);
setParent(m_popupFrame);
m_popupFrame->setObjectName("m_popupFrame");
m_popupFrame->setAttribute(Qt::WA_DeleteOnClose);
QVBoxLayout *layout = new QVBoxLayout(m_popupFrame);
layout->setMargin(0);
layout->addWidget(this);
setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
m_popupFrame->setMinimumSize(1, 1);
setMinimumSize(1, 1);
}
bool CompletionWidget::event(QEvent *e)
{
if (m_blockFocusOut)
return QListView::event(e);
bool forwardKeys = true;
if (e->type() == QEvent::FocusOut) {
closeList();
return true;
} else if (e->type() == QEvent::KeyPress) {
QKeyEvent *ke = static_cast<QKeyEvent *>(e);
switch (ke->key()) {
case Qt::Key_Escape:
closeList();
return true;
case Qt::Key_Right:
case Qt::Key_Left:
break;
case Qt::Key_Tab:
case Qt::Key_Return:
//independently from style, accept current entry if return is pressed
closeList(currentIndex());
return true;
case Qt::Key_Up:
case Qt::Key_Down:
case Qt::Key_Enter:
case Qt::Key_PageDown:
case Qt::Key_PageUp:
forwardKeys = false;
break;
default:
break;
}
if (forwardKeys) {
m_blockFocusOut = true;
QApplication::sendEvent(m_editorWidget, e);
m_blockFocusOut = false;
// Have the completion support update the list of items
m_support->autoComplete(m_editor, false);
return true;
}
}
return QListView::event(e);
}
void CompletionWidget::keyboardSearch(const QString &search)
{
Q_UNUSED(search);
}
void CompletionWidget::closeList(const QModelIndex &index)
{
m_blockFocusOut = true;
if (index.isValid())
emit itemSelected(m_model->itemAt(index));
close();
if (m_popupFrame) {
m_popupFrame->close();
m_popupFrame = 0;
}
emit completionListClosed();
m_blockFocusOut = false;
}
void CompletionWidget::setCompletionItems(const QList<TextEditor::CompletionItem> &completionItems)
{
if (!m_model) {
m_model = new AutoCompletionModel(this, completionItems);
setModel(m_model);
} else {
m_model->setItems(completionItems);
}
// Select the first of the most relevant completion items
int relevance = INT_MIN;
int mostRelevantIndex = 0;
for (int i = 0; i < completionItems.size(); ++i) {
const CompletionItem &item = completionItems.at(i);
if (item.m_relevance > relevance) {
relevance = item.m_relevance;
mostRelevantIndex = i;
}
}
setCurrentIndex(m_model->index(mostRelevantIndex));
}
void CompletionWidget::showCompletions(int startPos)
{
updatePositionAndSize(startPos);
m_popupFrame->show();
show();
setFocus();
}
void CompletionWidget::updatePositionAndSize(int startPos)
{
// Determine size by calculating the space of the visible items
int visibleItems = m_model->rowCount();
if (visibleItems > NUMBER_OF_VISIBLE_ITEMS)
visibleItems = NUMBER_OF_VISIBLE_ITEMS;
const QStyleOptionViewItem &option = viewOptions();
QSize shint;
for (int i = 0; i < visibleItems; ++i) {
QSize tmp = itemDelegate()->sizeHint(option, m_model->index(i));
if (shint.width() < tmp.width())
shint = tmp;
}
const int frameWidth = m_popupFrame->frameWidth();
const int width = shint.width() + frameWidth * 2 + 30;
const int height = shint.height() * visibleItems + frameWidth * 2;
// Determine the position, keeping the popup on the screen
const QRect cursorRect = m_editor->cursorRect(startPos);
const QDesktopWidget *desktop = QApplication::desktop();
const QRect screen = desktop->availableGeometry(desktop->screenNumber(this));
QPoint pos = cursorRect.bottomLeft();
pos.rx() -= 16 + frameWidth; // Space for the icons
if (pos.y() + height > screen.bottom())
pos.setY(cursorRect.top() - height);
if (pos.x() + width > screen.right())
pos.setX(screen.right() - width);
m_popupFrame->setGeometry(pos.x(), pos.y(), width, height);
}
void CompletionWidget::completionActivated(const QModelIndex &index)
{
closeList(index);
}
<commit_msg>Allow some more space for popup on most desktops<commit_after>/***************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2008 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Qt Software Information (qt-info@nokia.com)
**
**
** Non-Open Source Usage
**
** Licensees may use this file in accordance with the Qt Beta Version
** License Agreement, Agreement version 2.2 provided with the Software or,
** alternatively, in accordance with the terms contained in a written
** agreement between you and Nokia.
**
** GNU General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU General
** Public License versions 2.0 or 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the packaging
** of this file. Please review the following information to ensure GNU
** General Public Licensing requirements will be met:
**
** http://www.fsf.org/licensing/licenses/info/GPLv2.html and
** http://www.gnu.org/copyleft/gpl.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt GPL Exception
** version 1.3, included in the file GPL_EXCEPTION.txt in this package.
**
***************************************************************************/
#include "completionwidget.h"
#include "completionsupport.h"
#include "icompletioncollector.h"
#include <texteditor/itexteditable.h>
#include <utils/qtcassert.h>
#include <QtCore/QEvent>
#include <QtGui/QApplication>
#include <QtGui/QDesktopWidget>
#include <QtGui/QKeyEvent>
#include <QtGui/QVBoxLayout>
#include <limits.h>
using namespace TextEditor;
using namespace TextEditor::Internal;
#define NUMBER_OF_VISIBLE_ITEMS 10
class AutoCompletionModel : public QAbstractListModel
{
public:
AutoCompletionModel(QObject *parent, const QList<CompletionItem> &items);
inline const CompletionItem &itemAt(const QModelIndex &index) const
{ return m_items.at(index.row()); }
void setItems(const QList<CompletionItem> &items);
int rowCount(const QModelIndex &parent = QModelIndex()) const;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
private:
QList<CompletionItem> m_items;
};
AutoCompletionModel::AutoCompletionModel(QObject *parent, const QList<CompletionItem> &items)
: QAbstractListModel(parent)
{
m_items = items;
}
void AutoCompletionModel::setItems(const QList<CompletionItem> &items)
{
m_items = items;
reset();
}
int AutoCompletionModel::rowCount(const QModelIndex &) const
{
return m_items.count();
}
QVariant AutoCompletionModel::data(const QModelIndex &index, int role) const
{
if (index.row() >= m_items.count())
return QVariant();
if (role == Qt::DisplayRole) {
return itemAt(index).m_text;
} else if (role == Qt::DecorationRole) {
return itemAt(index).m_icon;
} else if (role == Qt::ToolTipRole) {
return itemAt(index).m_details;
}
return QVariant();
}
CompletionWidget::CompletionWidget(CompletionSupport *support, ITextEditable *editor)
: QListView(),
m_blockFocusOut(false),
m_editor(editor),
m_editorWidget(editor->widget()),
m_model(0),
m_support(support)
{
QTC_ASSERT(m_editorWidget, return);
setUniformItemSizes(true);
setSelectionBehavior(QAbstractItemView::SelectItems);
setSelectionMode(QAbstractItemView::SingleSelection);
connect(this, SIGNAL(activated(const QModelIndex &)),
this, SLOT(completionActivated(const QModelIndex &)));
// We disable the frame on this list view and use a QFrame around it instead.
// This fixes the missing frame on Mac and improves the look with QGTKStyle.
m_popupFrame = new QFrame(0, Qt::Popup);
m_popupFrame->setFrameStyle(frameStyle());
setFrameStyle(QFrame::NoFrame);
setParent(m_popupFrame);
m_popupFrame->setObjectName("m_popupFrame");
m_popupFrame->setAttribute(Qt::WA_DeleteOnClose);
QVBoxLayout *layout = new QVBoxLayout(m_popupFrame);
layout->setMargin(0);
layout->addWidget(this);
setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
m_popupFrame->setMinimumSize(1, 1);
setMinimumSize(1, 1);
}
bool CompletionWidget::event(QEvent *e)
{
if (m_blockFocusOut)
return QListView::event(e);
bool forwardKeys = true;
if (e->type() == QEvent::FocusOut) {
closeList();
return true;
} else if (e->type() == QEvent::KeyPress) {
QKeyEvent *ke = static_cast<QKeyEvent *>(e);
switch (ke->key()) {
case Qt::Key_Escape:
closeList();
return true;
case Qt::Key_Right:
case Qt::Key_Left:
break;
case Qt::Key_Tab:
case Qt::Key_Return:
//independently from style, accept current entry if return is pressed
closeList(currentIndex());
return true;
case Qt::Key_Up:
case Qt::Key_Down:
case Qt::Key_Enter:
case Qt::Key_PageDown:
case Qt::Key_PageUp:
forwardKeys = false;
break;
default:
break;
}
if (forwardKeys) {
m_blockFocusOut = true;
QApplication::sendEvent(m_editorWidget, e);
m_blockFocusOut = false;
// Have the completion support update the list of items
m_support->autoComplete(m_editor, false);
return true;
}
}
return QListView::event(e);
}
void CompletionWidget::keyboardSearch(const QString &search)
{
Q_UNUSED(search);
}
void CompletionWidget::closeList(const QModelIndex &index)
{
m_blockFocusOut = true;
if (index.isValid())
emit itemSelected(m_model->itemAt(index));
close();
if (m_popupFrame) {
m_popupFrame->close();
m_popupFrame = 0;
}
emit completionListClosed();
m_blockFocusOut = false;
}
void CompletionWidget::setCompletionItems(const QList<TextEditor::CompletionItem> &completionItems)
{
if (!m_model) {
m_model = new AutoCompletionModel(this, completionItems);
setModel(m_model);
} else {
m_model->setItems(completionItems);
}
// Select the first of the most relevant completion items
int relevance = INT_MIN;
int mostRelevantIndex = 0;
for (int i = 0; i < completionItems.size(); ++i) {
const CompletionItem &item = completionItems.at(i);
if (item.m_relevance > relevance) {
relevance = item.m_relevance;
mostRelevantIndex = i;
}
}
setCurrentIndex(m_model->index(mostRelevantIndex));
}
void CompletionWidget::showCompletions(int startPos)
{
updatePositionAndSize(startPos);
m_popupFrame->show();
show();
setFocus();
}
void CompletionWidget::updatePositionAndSize(int startPos)
{
// Determine size by calculating the space of the visible items
int visibleItems = m_model->rowCount();
if (visibleItems > NUMBER_OF_VISIBLE_ITEMS)
visibleItems = NUMBER_OF_VISIBLE_ITEMS;
const QStyleOptionViewItem &option = viewOptions();
QSize shint;
for (int i = 0; i < visibleItems; ++i) {
QSize tmp = itemDelegate()->sizeHint(option, m_model->index(i));
if (shint.width() < tmp.width())
shint = tmp;
}
const int frameWidth = m_popupFrame->frameWidth();
const int width = shint.width() + frameWidth * 2 + 30;
const int height = shint.height() * visibleItems + frameWidth * 2;
// Determine the position, keeping the popup on the screen
const QRect cursorRect = m_editor->cursorRect(startPos);
const QDesktopWidget *desktop = QApplication::desktop();
#ifdef Q_OS_MAC
const QRect screen = desktop->availableGeometry(desktop->screenNumber(this));
#else
const QRect screen = desktop->screenGeometry(desktop->screenNumber(this));
#endif
QPoint pos = cursorRect.bottomLeft();
pos.rx() -= 16 + frameWidth; // Space for the icons
if (pos.y() + height > screen.bottom())
pos.setY(cursorRect.top() - height);
if (pos.x() + width > screen.right())
pos.setX(screen.right() - width);
m_popupFrame->setGeometry(pos.x(), pos.y(), width, height);
}
void CompletionWidget::completionActivated(const QModelIndex &index)
{
closeList(index);
}
<|endoftext|> |
<commit_before>/**
* The Seeks proxy and plugin framework are part of the SEEKS project.
* Copyright (C) 2009, 2010
* sileht, theli48@gmail.com
* Emmanuel Benazera, juban@free.fr
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
**/
#include "errlog.h"
#include "se_parser_exalead.h"
#include "miscutil.h"
#include <strings.h>
#include <iostream>
using sp::miscutil;
using sp::errlog;
namespace seeks_plugins
{
se_parser_exalead::se_parser_exalead()
:se_parser(),_result_flag(false),_title_flag(false),_p_flag(false),
_summary_flag(false),_cite_flag(false),_cached_flag(false),_b_title_flag(false),
_b_summary_flag(false),_ignore_flag(false)
{
}
se_parser_exalead::~se_parser_exalead()
{
}
void se_parser_exalead::start_element(parser_context *pc,
const xmlChar *name,
const xmlChar **attributes)
{
const char *tag = (const char*)name;
if (strcasecmp(tag,"div") == 0)
{
const char *a_class = se_parser::get_attribute((const char**)attributes,"class");
if (a_class && strcasecmp(a_class,"resultContent") == 0)
{
// assert previous snippet, if any.
if (pc->_current_snippet)
{
if (pc->_current_snippet->_title.empty()
|| pc->_current_snippet->_url.empty())
{
delete pc->_current_snippet;
pc->_current_snippet = NULL;
_count--;
}
else pc->_snippets->push_back(pc->_current_snippet);
}
_result_flag = true;
search_snippet *sp = new search_snippet(_count+1);
_count++;
sp->_engine |= std::bitset<NSEs>(SE_EXALEAD);
pc->_current_snippet = sp;
}
}
else if (_result_flag)
{
if (strcasecmp(tag,"p") == 0)
{
_p_flag = true;
}
else if (_p_flag && strcasecmp(tag,"span") == 0)
{
const char *a_class = se_parser::get_attribute((const char**)attributes,"class");
if (!_summary_flag && !a_class)
_summary_flag = true;
if (_summary_flag && a_class && strcmp(a_class,"bookmarkLinks") == 0)
{
_ignore_flag = true;
}
}
else if (strcasecmp(tag,"a") == 0)
{
const char *a_class = se_parser::get_attribute((const char**)attributes,"class");
if (a_class && strcasecmp(a_class,"url") == 0)
{
_cite_flag = true;
}
else if (a_class && strcasecmp(a_class,"title") == 0)
{
_title_flag = true;
const char *a_link = se_parser::get_attribute((const char**)attributes,"href");
if (a_link)
pc->_current_snippet->set_url(a_link);
}
else if (a_class && strcasecmp(a_class,"cache") == 0)
{
_cached_flag = true;
const char *a_cached = se_parser::get_attribute((const char**)attributes,"href");
if (a_cached)
{
_cached = std::string(a_cached);
pc->_current_snippet->_cached = "http://www.exalead.com" + _cached; // beware: check on the host.
_cached = "";
}
}
}
else if (_title_flag && strcasecmp(tag,"b") == 0)
{
_b_title_flag = true;
}
else if (_summary_flag && strcasecmp(tag,"b") == 0)
{
_b_summary_flag = true;
}
}
}
void se_parser_exalead::characters(parser_context *pc,
const xmlChar *chars,
int length)
{
handle_characters(pc, chars, length);
}
void se_parser_exalead::cdata(parser_context *pc,
const xmlChar *chars,
int length)
{
handle_characters(pc, chars, length);
}
void se_parser_exalead::handle_characters(parser_context *pc,
const xmlChar *chars,
int length)
{
if (!_ignore_flag && _summary_flag)
{
std::string a_chars = std::string(miscutil::chomp((char*)chars));
miscutil::replace_in_string(a_chars,"\n"," ");
miscutil::replace_in_string(a_chars,"\r"," ");
if (_b_summary_flag)
_summary += " ";
_summary += a_chars;
if (_b_summary_flag)
_summary += " ";
}
else if (_cite_flag)
{
std::string a_chars = std::string((char*)chars);
miscutil::replace_in_string(a_chars,"\n"," ");
miscutil::replace_in_string(a_chars,"\r"," ");
_cite += a_chars;
}
else if (_title_flag)
{
std::string a_chars = std::string(miscutil::chomp((char*)chars));
miscutil::replace_in_string(a_chars,"\n"," ");
miscutil::replace_in_string(a_chars,"\r"," ");
if (_b_title_flag)
_title += " ";
_title += a_chars;
if (_b_title_flag)
_title += " ";
}
}
void se_parser_exalead::end_element(parser_context *pc,
const xmlChar *name)
{
const char *tag = (const char*) name;
if (_result_flag)
{
if (strcasecmp(tag,"div") == 0)
{
_result_flag = false;
_title_flag = false;
_p_flag = false;
_summary_flag = false;
_cite_flag = false;
_cached_flag = false;
}
else if (strcasecmp(tag,"span") == 0)
{
if (!_ignore_flag && _summary_flag)
{
pc->_current_snippet->set_summary(_summary);
_summary = "";
_summary_flag = false;
}
else if (_ignore_flag)
_ignore_flag = false;
}
else if ( _cite_flag && strcasecmp(tag,"a") == 0)
{
pc->_current_snippet->_cite = _cite;
_cite = "";
_cite_flag = false;
}
else if (_title_flag && strcasecmp(tag,"a") == 0)
{
pc->_current_snippet->_title = _title;
_title = "";
_title_flag = false;
}
else if (_title_flag && strcasecmp(tag,"b") == 0)
_b_title_flag = false;
else if (_summary_flag && strcasecmp(tag,"b") == 0)
_b_summary_flag = false;
}
}
} /* end of namespace. */
<commit_msg>crash fixes to exalead parser<commit_after>/**
* The Seeks proxy and plugin framework are part of the SEEKS project.
* Copyright (C) 2009, 2010
* sileht, theli48@gmail.com
* Emmanuel Benazera, juban@free.fr
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
**/
#include "errlog.h"
#include "se_parser_exalead.h"
#include "miscutil.h"
#include <strings.h>
#include <iostream>
using sp::miscutil;
using sp::errlog;
namespace seeks_plugins
{
se_parser_exalead::se_parser_exalead()
:se_parser(),_result_flag(false),_title_flag(false),_p_flag(false),
_summary_flag(false),_cite_flag(false),_cached_flag(false),_b_title_flag(false),
_b_summary_flag(false),_ignore_flag(false)
{
}
se_parser_exalead::~se_parser_exalead()
{
}
void se_parser_exalead::start_element(parser_context *pc,
const xmlChar *name,
const xmlChar **attributes)
{
const char *tag = (const char*)name;
if (strcasecmp(tag,"div") == 0)
{
const char *a_class = se_parser::get_attribute((const char**)attributes,"class");
if (a_class && strcasecmp(a_class,"resultContent") == 0)
{
// assert previous snippet, if any.
if (pc->_current_snippet)
{
if (pc->_current_snippet->_title.empty()
|| pc->_current_snippet->_url.empty())
{
delete pc->_current_snippet;
pc->_current_snippet = NULL;
_count--;
}
else pc->_snippets->push_back(pc->_current_snippet);
}
_result_flag = true;
search_snippet *sp = new search_snippet(_count+1);
_count++;
sp->_engine |= std::bitset<NSEs>(SE_EXALEAD);
pc->_current_snippet = sp;
}
}
else if (_result_flag)
{
if (strcasecmp(tag,"p") == 0)
{
_p_flag = true;
}
else if (_p_flag && strcasecmp(tag,"span") == 0)
{
const char *a_class = se_parser::get_attribute((const char**)attributes,"class");
if (!_summary_flag && !a_class)
_summary_flag = true;
if (_summary_flag && a_class && strcmp(a_class,"bookmarkLinks") == 0)
{
_ignore_flag = true;
}
}
else if (strcasecmp(tag,"a") == 0)
{
const char *a_class = se_parser::get_attribute((const char**)attributes,"class");
if (a_class && strcasecmp(a_class,"url") == 0)
{
_cite_flag = true;
}
else if (a_class && strcasecmp(a_class,"title") == 0)
{
_title_flag = true;
const char *a_link = se_parser::get_attribute((const char**)attributes,"href");
if (a_link)
pc->_current_snippet->set_url(a_link);
}
else if (a_class && strcasecmp(a_class,"cache") == 0)
{
_cached_flag = true;
const char *a_cached = se_parser::get_attribute((const char**)attributes,"href");
if (a_cached)
{
_cached = std::string(a_cached);
pc->_current_snippet->_cached = "http://www.exalead.com" + _cached; // beware: check on the host.
_cached = "";
}
}
}
else if (_title_flag && strcasecmp(tag,"b") == 0)
{
_b_title_flag = true;
}
else if (_summary_flag && strcasecmp(tag,"b") == 0)
{
_b_summary_flag = true;
}
}
}
void se_parser_exalead::characters(parser_context *pc,
const xmlChar *chars,
int length)
{
handle_characters(pc, chars, length);
}
void se_parser_exalead::cdata(parser_context *pc,
const xmlChar *chars,
int length)
{
handle_characters(pc, chars, length);
}
void se_parser_exalead::handle_characters(parser_context *pc,
const xmlChar *chars,
int length)
{
if (!chars)
return;
if (!_ignore_flag && _summary_flag)
{
std::string a_chars = std::string((char*)chars);
size_t i=0;
while(i<a_chars.length() && isspace(a_chars[i++]))
{
}
a_chars = a_chars.substr(i);
miscutil::replace_in_string(a_chars,"\n"," ");
miscutil::replace_in_string(a_chars,"\r"," ");
if (_b_summary_flag)
_summary += " ";
_summary += a_chars;
if (_b_summary_flag)
_summary += " ";
}
else if (_cite_flag)
{
std::string a_chars = std::string((char*)chars);
miscutil::replace_in_string(a_chars,"\n"," ");
miscutil::replace_in_string(a_chars,"\r"," ");
_cite += a_chars;
}
else if (_title_flag)
{
std::string a_chars = std::string((char*)chars);
size_t i=0;
while(i<a_chars.length() && isspace(a_chars[i++]))
{
}
a_chars = a_chars.substr(i);
miscutil::replace_in_string(a_chars,"\n"," ");
miscutil::replace_in_string(a_chars,"\r"," ");
if (_b_title_flag)
_title += " ";
_title += a_chars;
if (_b_title_flag)
_title += " ";
}
}
void se_parser_exalead::end_element(parser_context *pc,
const xmlChar *name)
{
const char *tag = (const char*) name;
if (_result_flag)
{
if (strcasecmp(tag,"div") == 0)
{
_result_flag = false;
_title_flag = false;
_p_flag = false;
_summary_flag = false;
_cite_flag = false;
_cached_flag = false;
}
else if (strcasecmp(tag,"span") == 0)
{
if (!_ignore_flag && _summary_flag)
{
pc->_current_snippet->set_summary(_summary);
_summary = "";
_summary_flag = false;
}
else if (_ignore_flag)
_ignore_flag = false;
}
else if ( _cite_flag && strcasecmp(tag,"a") == 0)
{
pc->_current_snippet->_cite = _cite;
_cite = "";
_cite_flag = false;
}
else if (_title_flag && strcasecmp(tag,"a") == 0)
{
pc->_current_snippet->_title = _title;
_title = "";
_title_flag = false;
}
else if (_title_flag && strcasecmp(tag,"b") == 0)
_b_title_flag = false;
else if (_summary_flag && strcasecmp(tag,"b") == 0)
_b_summary_flag = false;
}
}
} /* end of namespace. */
<|endoftext|> |
<commit_before>/*
Copyright (c) 2014-2015 DataStax
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.
*/
#ifdef STAND_ALONE
# define BOOST_TEST_MODULE cassandra
#endif
#include <boost/test/unit_test.hpp>
#include <boost/test/debug.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/cstdint.hpp>
#include <boost/format.hpp>
#include <boost/thread.hpp>
#include "cassandra.h"
#include "test_utils.hpp"
struct ByNameTests : public test_utils::SingleSessionTest {
ByNameTests() : test_utils::SingleSessionTest(1, 0) {
test_utils::execute_query(session, str(boost::format(test_utils::CREATE_KEYSPACE_SIMPLE_FORMAT)
% test_utils::SIMPLE_KEYSPACE % "1"));
test_utils::execute_query(session, str(boost::format("USE %s") % test_utils::SIMPLE_KEYSPACE));
test_utils::execute_query(session, "CREATE TABLE by_name (key uuid PRIMARY KEY, a int, b boolean, c text, abc float, \"ABC\" float, \"aBc\" float)");
}
test_utils::CassPreparedPtr prepare(const std::string& query) {
test_utils::CassFuturePtr prepared_future(cass_session_prepare(session,
cass_string_init2(query.data(), query.size())));
test_utils::wait_and_check_error(prepared_future.get());
return test_utils::CassPreparedPtr(cass_future_get_prepared(prepared_future.get()));
}
test_utils::CassResultPtr select_all_from_by_name() {
test_utils::CassResultPtr result;
test_utils::execute_query(session, "SELECT * FROM by_name", &result);
BOOST_REQUIRE(cass_result_column_count(result.get()) == 7);
BOOST_REQUIRE(cass_result_row_count(result.get()) > 0);
return result;
}
};
BOOST_FIXTURE_TEST_SUITE(by_name, ByNameTests)
BOOST_AUTO_TEST_CASE(bind_and_get)
{
test_utils::CassPreparedPtr prepared = prepare("INSERT INTO by_name (key, a, b, c) VALUES (?, ?, ?, ?)");
test_utils::CassStatementPtr statement(cass_prepared_bind(prepared.get()));
CassUuid key = test_utils::generate_time_uuid(uuid_gen);
BOOST_REQUIRE_EQUAL(cass_statement_bind_uuid_by_name(statement.get(), "key", key), CASS_OK);
BOOST_REQUIRE_EQUAL(cass_statement_bind_int32_by_name(statement.get(), "a", 9042), CASS_OK);
BOOST_REQUIRE_EQUAL(cass_statement_bind_bool_by_name(statement.get(), "b", cass_true), CASS_OK);
BOOST_REQUIRE_EQUAL(cass_statement_bind_string_by_name(statement.get(), "c", cass_string_init("xyz")), CASS_OK);
test_utils::CassFuturePtr future(cass_session_execute(session, statement.get()));
test_utils::wait_and_check_error(future.get());
test_utils::CassResultPtr result = select_all_from_by_name();
const CassRow* row = cass_result_first_row(result.get());
const CassValue* value;
value = cass_row_get_column_by_name(row, "key");
BOOST_REQUIRE(value != NULL);
CassUuid result_key;
BOOST_REQUIRE_EQUAL(cass_value_get_uuid(value, &result_key), CASS_OK);
BOOST_CHECK(test_utils::Value<CassUuid>::equal(result_key, key));
value = cass_row_get_column_by_name(row, "a");
BOOST_REQUIRE(value != NULL);
cass_int32_t a;
BOOST_REQUIRE_EQUAL(cass_value_get_int32(value, &a), CASS_OK);
BOOST_CHECK_EQUAL(a, 9042);
value = cass_row_get_column_by_name(row, "b");
BOOST_REQUIRE(value != NULL);
cass_bool_t b;
BOOST_REQUIRE_EQUAL(cass_value_get_bool(value, &b), CASS_OK);
BOOST_CHECK_EQUAL(b, cass_true);
value = cass_row_get_column_by_name(row, "c");
BOOST_REQUIRE(value != NULL);
CassString c;
BOOST_REQUIRE_EQUAL(cass_value_get_string(value, &c), CASS_OK);
BOOST_CHECK(test_utils::Value<CassString>::equal(c, cass_string_init("xyz")));
}
BOOST_AUTO_TEST_CASE(bind_and_get_case_sensitive)
{
test_utils::CassPreparedPtr prepared = prepare("INSERT INTO by_name (key, abc, \"ABC\", \"aBc\") VALUES (?, ?, ?, ?)");
test_utils::CassStatementPtr statement(cass_prepared_bind(prepared.get()));
CassUuid key = test_utils::generate_time_uuid(uuid_gen);
BOOST_REQUIRE_EQUAL(cass_statement_bind_uuid_by_name(statement.get(), "key", key), CASS_OK);
BOOST_REQUIRE_EQUAL(cass_statement_bind_float_by_name(statement.get(), "\"abc\"", 1.1f), CASS_OK);
BOOST_REQUIRE_EQUAL(cass_statement_bind_float_by_name(statement.get(), "\"ABC\"", 2.2f), CASS_OK);
BOOST_REQUIRE_EQUAL(cass_statement_bind_float_by_name(statement.get(), "\"aBc\"", 3.3f), CASS_OK);
test_utils::CassFuturePtr future(cass_session_execute(session, statement.get()));
test_utils::wait_and_check_error(future.get());
test_utils::CassResultPtr result = select_all_from_by_name();
const CassRow* row = cass_result_first_row(result.get());
const CassValue* value;
value = cass_row_get_column_by_name(row, "key");
BOOST_REQUIRE(value != NULL);
CassUuid result_key;
BOOST_REQUIRE_EQUAL(cass_value_get_uuid(value, &result_key), CASS_OK);
BOOST_CHECK(test_utils::Value<CassUuid>::equal(result_key, key));
value = cass_row_get_column_by_name(row, "\"abc\"");
BOOST_REQUIRE(value != NULL);
cass_float_t abc;
BOOST_REQUIRE_EQUAL(cass_value_get_float(value, &abc), CASS_OK);
BOOST_CHECK(abc == 1.1f);
value = cass_row_get_column_by_name(row, "\"ABC\"");
BOOST_REQUIRE(value != NULL);
BOOST_REQUIRE_EQUAL(cass_value_get_float(value, &abc), CASS_OK);
BOOST_CHECK(abc == 2.2f);
value = cass_row_get_column_by_name(row, "\"aBc\"");
BOOST_REQUIRE(value != NULL);
BOOST_REQUIRE_EQUAL(cass_value_get_float(value, &abc), CASS_OK);
BOOST_CHECK(abc == 3.3f);
}
BOOST_AUTO_TEST_CASE(bind_multiple_columns)
{
test_utils::CassPreparedPtr prepared = prepare("INSERT INTO by_name (key, abc, \"ABC\", \"aBc\") VALUES (?, ?, ?, ?)");
test_utils::CassStatementPtr statement(cass_prepared_bind(prepared.get()));
CassUuid key = test_utils::generate_time_uuid(uuid_gen);
BOOST_REQUIRE_EQUAL(cass_statement_bind_uuid_by_name(statement.get(), "key", key), CASS_OK);
BOOST_REQUIRE_EQUAL(cass_statement_bind_float_by_name(statement.get(), "abc", 1.23f), CASS_OK);
test_utils::CassFuturePtr future(cass_session_execute(session, statement.get()));
test_utils::wait_and_check_error(future.get());
test_utils::CassResultPtr result = select_all_from_by_name();
const CassRow* row = cass_result_first_row(result.get());
const CassValue* value;
value = cass_row_get_column_by_name(row, "key");
BOOST_REQUIRE(value != NULL);
CassUuid result_key;
BOOST_REQUIRE_EQUAL(cass_value_get_uuid(value, &result_key), CASS_OK);
BOOST_CHECK(test_utils::Value<CassUuid>::equal(result_key, key));
value = cass_row_get_column_by_name(row, "\"abc\"");
BOOST_REQUIRE(value != NULL);
cass_float_t abc;
BOOST_REQUIRE_EQUAL(cass_value_get_float(value, &abc), CASS_OK);
BOOST_CHECK(abc == 1.23f);
value = cass_row_get_column_by_name(row, "\"ABC\"");
BOOST_REQUIRE(value != NULL);
BOOST_REQUIRE_EQUAL(cass_value_get_float(value, &abc), CASS_OK);
BOOST_CHECK(abc == 1.23f);
value = cass_row_get_column_by_name(row, "\"aBc\"");
BOOST_REQUIRE(value != NULL);
BOOST_REQUIRE_EQUAL(cass_value_get_float(value, &abc), CASS_OK);
BOOST_CHECK(abc == 1.23f);
}
BOOST_AUTO_TEST_CASE(bind_not_prepared)
{
test_utils::CassStatementPtr statement(cass_statement_new(cass_string_init("INSERT INTO by_name (key, a) VALUES (?, ?)"), 2));
CassUuid key = test_utils::generate_time_uuid(uuid_gen);
BOOST_REQUIRE_EQUAL(cass_statement_bind_uuid_by_name(statement.get(), "key", key), CASS_ERROR_LIB_INVALID_STATEMENT_TYPE);
BOOST_REQUIRE_EQUAL(cass_statement_bind_int32_by_name(statement.get(), "a", 9042), CASS_ERROR_LIB_INVALID_STATEMENT_TYPE);
}
BOOST_AUTO_TEST_CASE(bind_invalid_name)
{
test_utils::CassPreparedPtr prepared = prepare("INSERT INTO by_name (key, a, b, c, abc, \"ABC\", \"aBc\") VALUES (?, ?, ?, ?, ?, ?, ?)");
test_utils::CassStatementPtr statement(cass_prepared_bind(prepared.get()));
BOOST_REQUIRE_EQUAL(cass_statement_bind_int32_by_name(statement.get(), "d", 0), CASS_ERROR_LIB_NAME_DOES_NOT_EXIST);
BOOST_REQUIRE_EQUAL(cass_statement_bind_float_by_name(statement.get(), "\"aBC\"", 0.0), CASS_ERROR_LIB_NAME_DOES_NOT_EXIST);
BOOST_REQUIRE_EQUAL(cass_statement_bind_float_by_name(statement.get(), "\"abC\"", 0.0), CASS_ERROR_LIB_NAME_DOES_NOT_EXIST);
}
BOOST_AUTO_TEST_CASE(get_invalid_name)
{
test_utils::CassStatementPtr statement(cass_statement_new(cass_string_init("INSERT INTO by_name (key, a) VALUES (?, ?)"), 2));
CassUuid key = test_utils::generate_time_uuid(uuid_gen);
BOOST_REQUIRE_EQUAL(cass_statement_bind_uuid(statement.get(), 0, key), CASS_OK);
BOOST_REQUIRE_EQUAL(cass_statement_bind_int32(statement.get(), 1, 9042), CASS_OK);
test_utils::CassFuturePtr future(cass_session_execute(session, statement.get()));
test_utils::wait_and_check_error(future.get());
test_utils::CassResultPtr result = select_all_from_by_name();
const CassRow* row = cass_result_first_row(result.get());
BOOST_CHECK(cass_row_get_column_by_name(row, "d") == NULL);
BOOST_CHECK(cass_row_get_column_by_name(row, "\"aBC\"") == NULL);
BOOST_CHECK(cass_row_get_column_by_name(row, "\"abC\"") == NULL);
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>test: Adding bind_null_by_name integration tests<commit_after>/*
Copyright (c) 2014-2015 DataStax
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.
*/
#ifdef STAND_ALONE
# define BOOST_TEST_MODULE cassandra
#endif
#include <boost/test/unit_test.hpp>
#include <boost/test/debug.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/cstdint.hpp>
#include <boost/format.hpp>
#include <boost/thread.hpp>
#include "cassandra.h"
#include "test_utils.hpp"
struct ByNameTests : public test_utils::SingleSessionTest {
ByNameTests() : test_utils::SingleSessionTest(1, 0) {
test_utils::execute_query(session, str(boost::format(test_utils::CREATE_KEYSPACE_SIMPLE_FORMAT)
% test_utils::SIMPLE_KEYSPACE % "1"));
test_utils::execute_query(session, str(boost::format("USE %s") % test_utils::SIMPLE_KEYSPACE));
test_utils::execute_query(session, "CREATE TABLE by_name (key uuid PRIMARY KEY, a int, b boolean, c text, abc float, \"ABC\" float, \"aBc\" float)");
}
test_utils::CassPreparedPtr prepare(const std::string& query) {
test_utils::CassFuturePtr prepared_future(cass_session_prepare(session,
cass_string_init2(query.data(), query.size())));
test_utils::wait_and_check_error(prepared_future.get());
return test_utils::CassPreparedPtr(cass_future_get_prepared(prepared_future.get()));
}
test_utils::CassResultPtr select_all_from_by_name() {
test_utils::CassResultPtr result;
test_utils::execute_query(session, "SELECT * FROM by_name", &result);
BOOST_REQUIRE(cass_result_column_count(result.get()) == 7);
BOOST_REQUIRE(cass_result_row_count(result.get()) > 0);
return result;
}
};
BOOST_FIXTURE_TEST_SUITE(by_name, ByNameTests)
BOOST_AUTO_TEST_CASE(bind_and_get)
{
test_utils::CassPreparedPtr prepared = prepare("INSERT INTO by_name (key, a, b, c) VALUES (?, ?, ?, ?)");
test_utils::CassStatementPtr statement(cass_prepared_bind(prepared.get()));
CassUuid key = test_utils::generate_time_uuid(uuid_gen);
BOOST_REQUIRE_EQUAL(cass_statement_bind_uuid_by_name(statement.get(), "key", key), CASS_OK);
BOOST_REQUIRE_EQUAL(cass_statement_bind_int32_by_name(statement.get(), "a", 9042), CASS_OK);
BOOST_REQUIRE_EQUAL(cass_statement_bind_bool_by_name(statement.get(), "b", cass_true), CASS_OK);
BOOST_REQUIRE_EQUAL(cass_statement_bind_string_by_name(statement.get(), "c", cass_string_init("xyz")), CASS_OK);
test_utils::CassFuturePtr future(cass_session_execute(session, statement.get()));
test_utils::wait_and_check_error(future.get());
test_utils::CassResultPtr result = select_all_from_by_name();
const CassRow* row = cass_result_first_row(result.get());
const CassValue* value;
value = cass_row_get_column_by_name(row, "key");
BOOST_REQUIRE(value != NULL);
CassUuid result_key;
BOOST_REQUIRE_EQUAL(cass_value_get_uuid(value, &result_key), CASS_OK);
BOOST_CHECK(test_utils::Value<CassUuid>::equal(result_key, key));
value = cass_row_get_column_by_name(row, "a");
BOOST_REQUIRE(value != NULL);
cass_int32_t a;
BOOST_REQUIRE_EQUAL(cass_value_get_int32(value, &a), CASS_OK);
BOOST_CHECK_EQUAL(a, 9042);
value = cass_row_get_column_by_name(row, "b");
BOOST_REQUIRE(value != NULL);
cass_bool_t b;
BOOST_REQUIRE_EQUAL(cass_value_get_bool(value, &b), CASS_OK);
BOOST_CHECK_EQUAL(b, cass_true);
value = cass_row_get_column_by_name(row, "c");
BOOST_REQUIRE(value != NULL);
CassString c;
BOOST_REQUIRE_EQUAL(cass_value_get_string(value, &c), CASS_OK);
BOOST_CHECK(test_utils::Value<CassString>::equal(c, cass_string_init("xyz")));
}
BOOST_AUTO_TEST_CASE(bind_and_get_case_sensitive)
{
test_utils::CassPreparedPtr prepared = prepare("INSERT INTO by_name (key, abc, \"ABC\", \"aBc\") VALUES (?, ?, ?, ?)");
test_utils::CassStatementPtr statement(cass_prepared_bind(prepared.get()));
CassUuid key = test_utils::generate_time_uuid(uuid_gen);
BOOST_REQUIRE_EQUAL(cass_statement_bind_uuid_by_name(statement.get(), "key", key), CASS_OK);
BOOST_REQUIRE_EQUAL(cass_statement_bind_float_by_name(statement.get(), "\"abc\"", 1.1f), CASS_OK);
BOOST_REQUIRE_EQUAL(cass_statement_bind_float_by_name(statement.get(), "\"ABC\"", 2.2f), CASS_OK);
BOOST_REQUIRE_EQUAL(cass_statement_bind_float_by_name(statement.get(), "\"aBc\"", 3.3f), CASS_OK);
test_utils::CassFuturePtr future(cass_session_execute(session, statement.get()));
test_utils::wait_and_check_error(future.get());
test_utils::CassResultPtr result = select_all_from_by_name();
const CassRow* row = cass_result_first_row(result.get());
const CassValue* value;
value = cass_row_get_column_by_name(row, "key");
BOOST_REQUIRE(value != NULL);
CassUuid result_key;
BOOST_REQUIRE_EQUAL(cass_value_get_uuid(value, &result_key), CASS_OK);
BOOST_CHECK(test_utils::Value<CassUuid>::equal(result_key, key));
value = cass_row_get_column_by_name(row, "\"abc\"");
BOOST_REQUIRE(value != NULL);
cass_float_t abc;
BOOST_REQUIRE_EQUAL(cass_value_get_float(value, &abc), CASS_OK);
BOOST_CHECK(abc == 1.1f);
value = cass_row_get_column_by_name(row, "\"ABC\"");
BOOST_REQUIRE(value != NULL);
BOOST_REQUIRE_EQUAL(cass_value_get_float(value, &abc), CASS_OK);
BOOST_CHECK(abc == 2.2f);
value = cass_row_get_column_by_name(row, "\"aBc\"");
BOOST_REQUIRE(value != NULL);
BOOST_REQUIRE_EQUAL(cass_value_get_float(value, &abc), CASS_OK);
BOOST_CHECK(abc == 3.3f);
}
BOOST_AUTO_TEST_CASE(bind_multiple_columns)
{
test_utils::CassPreparedPtr prepared = prepare("INSERT INTO by_name (key, abc, \"ABC\", \"aBc\") VALUES (?, ?, ?, ?)");
test_utils::CassStatementPtr statement(cass_prepared_bind(prepared.get()));
CassUuid key = test_utils::generate_time_uuid(uuid_gen);
BOOST_REQUIRE_EQUAL(cass_statement_bind_uuid_by_name(statement.get(), "key", key), CASS_OK);
BOOST_REQUIRE_EQUAL(cass_statement_bind_float_by_name(statement.get(), "abc", 1.23f), CASS_OK);
test_utils::CassFuturePtr future(cass_session_execute(session, statement.get()));
test_utils::wait_and_check_error(future.get());
test_utils::CassResultPtr result = select_all_from_by_name();
const CassRow* row = cass_result_first_row(result.get());
const CassValue* value;
value = cass_row_get_column_by_name(row, "key");
BOOST_REQUIRE(value != NULL);
CassUuid result_key;
BOOST_REQUIRE_EQUAL(cass_value_get_uuid(value, &result_key), CASS_OK);
BOOST_CHECK(test_utils::Value<CassUuid>::equal(result_key, key));
value = cass_row_get_column_by_name(row, "\"abc\"");
BOOST_REQUIRE(value != NULL);
cass_float_t abc;
BOOST_REQUIRE_EQUAL(cass_value_get_float(value, &abc), CASS_OK);
BOOST_CHECK(abc == 1.23f);
value = cass_row_get_column_by_name(row, "\"ABC\"");
BOOST_REQUIRE(value != NULL);
BOOST_REQUIRE_EQUAL(cass_value_get_float(value, &abc), CASS_OK);
BOOST_CHECK(abc == 1.23f);
value = cass_row_get_column_by_name(row, "\"aBc\"");
BOOST_REQUIRE(value != NULL);
BOOST_REQUIRE_EQUAL(cass_value_get_float(value, &abc), CASS_OK);
BOOST_CHECK(abc == 1.23f);
}
BOOST_AUTO_TEST_CASE(bind_not_prepared)
{
test_utils::CassStatementPtr statement(cass_statement_new(cass_string_init("INSERT INTO by_name (key, a) VALUES (?, ?)"), 2));
CassUuid key = test_utils::generate_time_uuid(uuid_gen);
BOOST_REQUIRE_EQUAL(cass_statement_bind_uuid_by_name(statement.get(), "key", key), CASS_ERROR_LIB_INVALID_STATEMENT_TYPE);
BOOST_REQUIRE_EQUAL(cass_statement_bind_int32_by_name(statement.get(), "a", 9042), CASS_ERROR_LIB_INVALID_STATEMENT_TYPE);
}
BOOST_AUTO_TEST_CASE(bind_invalid_name)
{
test_utils::CassPreparedPtr prepared = prepare("INSERT INTO by_name (key, a, b, c, abc, \"ABC\", \"aBc\") VALUES (?, ?, ?, ?, ?, ?, ?)");
test_utils::CassStatementPtr statement(cass_prepared_bind(prepared.get()));
BOOST_REQUIRE_EQUAL(cass_statement_bind_int32_by_name(statement.get(), "d", 0), CASS_ERROR_LIB_NAME_DOES_NOT_EXIST);
BOOST_REQUIRE_EQUAL(cass_statement_bind_float_by_name(statement.get(), "\"aBC\"", 0.0), CASS_ERROR_LIB_NAME_DOES_NOT_EXIST);
BOOST_REQUIRE_EQUAL(cass_statement_bind_float_by_name(statement.get(), "\"abC\"", 0.0), CASS_ERROR_LIB_NAME_DOES_NOT_EXIST);
}
BOOST_AUTO_TEST_CASE(get_invalid_name)
{
test_utils::CassStatementPtr statement(cass_statement_new(cass_string_init("INSERT INTO by_name (key, a) VALUES (?, ?)"), 2));
CassUuid key = test_utils::generate_time_uuid(uuid_gen);
BOOST_REQUIRE_EQUAL(cass_statement_bind_uuid(statement.get(), 0, key), CASS_OK);
BOOST_REQUIRE_EQUAL(cass_statement_bind_int32(statement.get(), 1, 9042), CASS_OK);
test_utils::CassFuturePtr future(cass_session_execute(session, statement.get()));
test_utils::wait_and_check_error(future.get());
test_utils::CassResultPtr result = select_all_from_by_name();
const CassRow* row = cass_result_first_row(result.get());
BOOST_CHECK(cass_row_get_column_by_name(row, "d") == NULL);
BOOST_CHECK(cass_row_get_column_by_name(row, "\"aBC\"") == NULL);
BOOST_CHECK(cass_row_get_column_by_name(row, "\"abC\"") == NULL);
}
BOOST_AUTO_TEST_CASE(null)
{
test_utils::CassPreparedPtr prepared = prepare("INSERT INTO by_name (key, a, b, c, abc, \"ABC\", \"aBc\") VALUES (?, ?, ?, ?, ?, ?, ?)");
test_utils::CassStatementPtr statement(cass_prepared_bind(prepared.get()));
CassUuid key = test_utils::generate_time_uuid(uuid_gen);
BOOST_REQUIRE_EQUAL(cass_statement_bind_uuid_by_name(statement.get(), "key", key), CASS_OK);
BOOST_REQUIRE_EQUAL(cass_statement_bind_null_by_name(statement.get(), "a"), CASS_OK);
BOOST_REQUIRE_EQUAL(cass_statement_bind_null_by_name(statement.get(), "b"), CASS_OK);
BOOST_REQUIRE_EQUAL(cass_statement_bind_null_by_name(statement.get(), "c"), CASS_OK);
BOOST_REQUIRE_EQUAL(cass_statement_bind_null_by_name(statement.get(), "abc"), CASS_OK);
BOOST_REQUIRE_EQUAL(cass_statement_bind_null_by_name(statement.get(), "\"ABC\""), CASS_OK);
BOOST_REQUIRE_EQUAL(cass_statement_bind_null_by_name(statement.get(), "\"aBc\""), CASS_OK);
test_utils::CassFuturePtr future(cass_session_execute(session, statement.get()));
test_utils::wait_and_check_error(future.get());
test_utils::CassResultPtr result = select_all_from_by_name();
const CassRow* row = cass_result_first_row(result.get());
BOOST_CHECK(cass_value_is_null(cass_row_get_column_by_name(row, "a")));
BOOST_CHECK(cass_value_is_null(cass_row_get_column_by_name(row, "b")));
BOOST_CHECK(cass_value_is_null(cass_row_get_column_by_name(row, "c")));
BOOST_CHECK(cass_value_is_null(cass_row_get_column_by_name(row, "abc")));
BOOST_CHECK(cass_value_is_null(cass_row_get_column_by_name(row, "\"ABC\"")));
BOOST_CHECK(cass_value_is_null(cass_row_get_column_by_name(row, "\"aBc\"")));
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|> |
<commit_before>/*
* spi.cpp - Threaded SPI driver
*
* Copyright (C) 2013 William Markezana <william.markezana@me.com>
*
*/
#include "spi.h"
/*
* constructor
*
*/
spi::spi(const char *pDevice)
{
mMode = 0;
mRunning = false;
mActiveTransfert = false;
mInitializationSuccessful = false;
mThreadId = 0;
mTransfert.rx_buf = 0;
mTransfert.delay_usecs = 0;
mTransfert.speed_hz = 2000000;
mTransfert.bits_per_word = 8;
mTransfert.cs_change = 0;
mTransfert.pad = 0;
mTransfert.len = 0;
mHandle = open(pDevice, O_RDWR);
if (mHandle < 0)
{
cerr << "can't open device " << pDevice;
return;
}
ioctl(mHandle, SPI_IOC_WR_MODE, &mMode);
ioctl(mHandle, SPI_IOC_RD_MODE, &mMode);
ioctl(mHandle, SPI_IOC_WR_BITS_PER_WORD, &mTransfert.bits_per_word);
ioctl(mHandle, SPI_IOC_RD_BITS_PER_WORD, &mTransfert.bits_per_word);
ioctl(mHandle, SPI_IOC_WR_MAX_SPEED_HZ, &mTransfert.speed_hz);
ioctl(mHandle, SPI_IOC_RD_MAX_SPEED_HZ, &mTransfert.speed_hz);
run();
mInitializationSuccessful = true;
}
/*
* destructor
*
*/
spi::~spi()
{
mRunning = false;
close(mHandle);
}
/*
* private functions
*
*/
static void *thread_run_callback(void *pOwner)
{
((spi *) pOwner)->thread_run();
return NULL;
}
/*
* public functions
*
*/
void spi::thread_run()
{
while (mRunning)
{
if (mTransfert.len)
{
mMutex.lock();
int bytesWritten = ioctl(mHandle, SPI_IOC_MESSAGE(1), &mTransfert);
if (bytesWritten < 0)
{
cerr << "write spi error";
}
if (bytesWritten != (int) mTransfert.len)
{
cerr << "write spi error";
}
mTransfert.len = 0;
mActiveTransfert = false;
mMutex.unlock();
}
usleep(1000);
}
pthread_exit(NULL);
}
void spi::run()
{
mRunning = true;
(void) pthread_create(&mThreadId, NULL, thread_run_callback, this);
}
void spi::write_buffer(uint8_t *pBuffer, int pLength)
{
if (mInitializationSuccessful && mMutex.try_lock())
{
mTransfert.tx_buf = (unsigned long) pBuffer;
mTransfert.len = pLength;
mActiveTransfert = true;
mMutex.unlock();
}
}
bool spi::activeTransfert()
{
return mActiveTransfert;
}
void spi::waitForTransfertToComplete()
{
while (mActiveTransfert);
}
<commit_msg>spi : error log messages endl added<commit_after>/*
* spi.cpp - Threaded SPI driver
*
* Copyright (C) 2013 William Markezana <william.markezana@me.com>
*
*/
#include "spi.h"
/*
* constructor
*
*/
spi::spi(const char *pDevice)
{
mMode = 0;
mRunning = false;
mActiveTransfert = false;
mInitializationSuccessful = false;
mThreadId = 0;
mTransfert.rx_buf = 0;
mTransfert.delay_usecs = 0;
mTransfert.speed_hz = 2000000;
mTransfert.bits_per_word = 8;
mTransfert.cs_change = 0;
mTransfert.pad = 0;
mTransfert.len = 0;
mHandle = open(pDevice, O_RDWR);
if (mHandle < 0)
{
cerr << "can't open device " << pDevice << endl;
return;
}
ioctl(mHandle, SPI_IOC_WR_MODE, &mMode);
ioctl(mHandle, SPI_IOC_RD_MODE, &mMode);
ioctl(mHandle, SPI_IOC_WR_BITS_PER_WORD, &mTransfert.bits_per_word);
ioctl(mHandle, SPI_IOC_RD_BITS_PER_WORD, &mTransfert.bits_per_word);
ioctl(mHandle, SPI_IOC_WR_MAX_SPEED_HZ, &mTransfert.speed_hz);
ioctl(mHandle, SPI_IOC_RD_MAX_SPEED_HZ, &mTransfert.speed_hz);
run();
mInitializationSuccessful = true;
}
/*
* destructor
*
*/
spi::~spi()
{
mRunning = false;
close(mHandle);
}
/*
* private functions
*
*/
static void *thread_run_callback(void *pOwner)
{
((spi *) pOwner)->thread_run();
return NULL;
}
/*
* public functions
*
*/
void spi::thread_run()
{
while (mRunning)
{
if (mTransfert.len)
{
mMutex.lock();
int bytesWritten = ioctl(mHandle, SPI_IOC_MESSAGE(1), &mTransfert);
if (bytesWritten < 0)
{
cerr << "write spi error" << endl;
}
if (bytesWritten != (int) mTransfert.len)
{
cerr << "write spi error" << endl;
}
mTransfert.len = 0;
mActiveTransfert = false;
mMutex.unlock();
}
usleep(1000);
}
pthread_exit(NULL);
}
void spi::run()
{
mRunning = true;
(void) pthread_create(&mThreadId, NULL, thread_run_callback, this);
}
void spi::write_buffer(uint8_t *pBuffer, int pLength)
{
if (mInitializationSuccessful && mMutex.try_lock())
{
mTransfert.tx_buf = (unsigned long) pBuffer;
mTransfert.len = pLength;
mActiveTransfert = true;
mMutex.unlock();
}
}
bool spi::activeTransfert()
{
return mActiveTransfert;
}
void spi::waitForTransfertToComplete()
{
while (mActiveTransfert);
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2019 The Android Open Source Project
*
* 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 "perfetto/ext/tracing/core/startup_trace_writer_registry.h"
#include <algorithm>
#include <cmath>
#include <functional>
#include "perfetto/base/logging.h"
#include "perfetto/base/task_runner.h"
#include "perfetto/ext/tracing/core/startup_trace_writer.h"
#include "src/tracing/core/shared_memory_arbiter_impl.h"
using ChunkHeader = perfetto::SharedMemoryABI::ChunkHeader;
namespace perfetto {
StartupTraceWriterRegistryHandle::StartupTraceWriterRegistryHandle(
StartupTraceWriterRegistry* registry)
: registry_(registry) {}
void StartupTraceWriterRegistryHandle::ReturnWriterToRegistry(
std::unique_ptr<StartupTraceWriter> writer) {
std::lock_guard<std::mutex> lock(lock_);
if (registry_)
registry_->ReturnTraceWriter(std::move(writer));
}
void StartupTraceWriterRegistryHandle::OnRegistryDestroyed() {
std::lock_guard<std::mutex> lock(lock_);
registry_ = nullptr;
}
StartupTraceWriterRegistry::StartupTraceWriterRegistry()
: handle_(std::make_shared<StartupTraceWriterRegistryHandle>(this)) {}
StartupTraceWriterRegistry::~StartupTraceWriterRegistry() {
handle_->OnRegistryDestroyed();
}
// static
constexpr size_t StartupTraceWriterRegistry::kDefaultMaxBufferSizeBytes;
std::unique_ptr<StartupTraceWriter>
StartupTraceWriterRegistry::CreateUnboundTraceWriter(
BufferExhaustedPolicy buffer_exhausted_policy,
size_t max_buffer_size_bytes) {
std::lock_guard<std::mutex> lock(lock_);
PERFETTO_DCHECK(!arbiter_); // Should only be called while unbound.
std::unique_ptr<StartupTraceWriter> writer(new StartupTraceWriter(
handle_, buffer_exhausted_policy, max_buffer_size_bytes));
unbound_writers_.push_back(writer.get());
return writer;
}
void StartupTraceWriterRegistry::ReturnTraceWriter(
std::unique_ptr<StartupTraceWriter> trace_writer) {
std::unique_lock<std::mutex> lock(lock_);
// We can only bind the writer on task_runner_.
if (task_runner_ && !task_runner_->RunsTasksOnCurrentThread()) {
// We shouldn't post tasks while holding a lock. |task_runner_| is only set
// once, so will remain valid.
lock.release();
auto weak_this = weak_ptr_factory_->GetWeakPtr();
auto* trace_writer_raw = trace_writer.get();
task_runner_->PostTask([weak_this, trace_writer_raw]() {
std::unique_ptr<StartupTraceWriter> owned_writer(trace_writer_raw);
weak_this->ReturnTraceWriter(std::move(owned_writer));
});
return;
}
PERFETTO_DCHECK(!trace_writer->write_in_progress_);
auto it = std::find(unbound_writers_.begin(), unbound_writers_.end(),
trace_writer.get());
// If the registry is already bound, but the writer wasn't, bind it now.
if (arbiter_) {
if (it == unbound_writers_.end()) {
// Nothing to do, the writer was already bound.
return;
}
// This should succeed since nobody can write to this writer concurrently.
bool success = trace_writer->BindToArbiter(arbiter_, target_buffer_,
chunks_per_batch_);
PERFETTO_DCHECK(success);
unbound_writers_.erase(it);
OnUnboundWritersRemovedLocked();
return;
}
// If the registry was not bound yet, keep the writer alive until it is.
PERFETTO_DCHECK(it != unbound_writers_.end());
unbound_writers_.erase(it);
unbound_owned_writers_.push_back(std::move(trace_writer));
}
void StartupTraceWriterRegistry::BindToArbiter(
SharedMemoryArbiterImpl* arbiter,
BufferID target_buffer,
base::TaskRunner* task_runner,
std::function<void(StartupTraceWriterRegistry*)> on_bound_callback) {
std::vector<std::unique_ptr<StartupTraceWriter>> unbound_owned_writers;
{
std::lock_guard<std::mutex> lock(lock_);
PERFETTO_DCHECK(!arbiter_);
arbiter_ = arbiter;
target_buffer_ = target_buffer;
task_runner_ = task_runner;
// Attempt to use at most half the SMB for binding of StartupTraceWriters at
// the same time. In the worst case, all writers are binding at the same
// time, so divide it up between them.
//
// TODO(eseckler): This assumes that there's only a single registry at the
// same time. SharedMemoryArbiterImpl should advise us how much of the SMB
// we're allowed to use in the first place.
size_t num_writers =
unbound_owned_writers_.size() + unbound_writers_.size();
if (num_writers) {
chunks_per_batch_ = arbiter_->num_pages() / 2 / num_writers;
} else {
chunks_per_batch_ = arbiter_->num_pages() / 2;
}
// We should use at least one chunk per batch.
chunks_per_batch_ = std::max(chunks_per_batch_, static_cast<size_t>(1u));
// Weakptrs should be valid on |task_runner|. For this, the factory needs to
// be created on |task_runner|, i.e. BindToArbiter must be called on
// |task_runner|.
PERFETTO_DCHECK(task_runner_->RunsTasksOnCurrentThread());
weak_ptr_factory_.reset(
new base::WeakPtrFactory<StartupTraceWriterRegistry>(this));
on_bound_callback_ = std::move(on_bound_callback);
// We can't destroy the writers while holding |lock_|, so we swap them out
// here instead. After we are bound, no more writers can be added to the
// list.
unbound_owned_writers.swap(unbound_owned_writers_);
}
// Bind and destroy the owned writers.
for (const auto& writer : unbound_owned_writers) {
// This should succeed since nobody can write to these writers concurrently.
bool success =
writer->BindToArbiter(arbiter_, target_buffer_, chunks_per_batch_);
PERFETTO_DCHECK(success);
}
unbound_owned_writers.clear();
TryBindWriters();
}
void StartupTraceWriterRegistry::TryBindWriters() {
std::lock_guard<std::mutex> lock(lock_);
for (auto it = unbound_writers_.begin(); it != unbound_writers_.end();) {
if ((*it)->BindToArbiter(arbiter_, target_buffer_, chunks_per_batch_)) {
it = unbound_writers_.erase(it);
} else {
break;
}
}
if (!unbound_writers_.empty()) {
auto weak_this = weak_ptr_factory_->GetWeakPtr();
task_runner_->PostTask([weak_this] {
if (weak_this)
weak_this->TryBindWriters();
});
}
OnUnboundWritersRemovedLocked();
}
void StartupTraceWriterRegistry::OnUnboundWritersRemovedLocked() {
if (!unbound_writers_.empty() || !task_runner_ || !on_bound_callback_)
return;
PERFETTO_DCHECK(weak_ptr_factory_);
auto weak_this = weak_ptr_factory_->GetWeakPtr();
// Run callback in PostTask() since the callback may delete |this| and thus
// might otherwise cause a deadlock.
auto callback = on_bound_callback_;
on_bound_callback_ = nullptr;
task_runner_->PostTask([weak_this, callback]() {
if (!weak_this)
return;
// Note: callback may delete |this|.
callback(weak_this.get());
});
}
} // namespace perfetto
<commit_msg>startup writers: Add missing weak_ptr check am: aea0ac9c96 am: 8df00ab209<commit_after>/*
* Copyright (C) 2019 The Android Open Source Project
*
* 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 "perfetto/ext/tracing/core/startup_trace_writer_registry.h"
#include <algorithm>
#include <cmath>
#include <functional>
#include "perfetto/base/logging.h"
#include "perfetto/base/task_runner.h"
#include "perfetto/ext/tracing/core/startup_trace_writer.h"
#include "src/tracing/core/shared_memory_arbiter_impl.h"
using ChunkHeader = perfetto::SharedMemoryABI::ChunkHeader;
namespace perfetto {
StartupTraceWriterRegistryHandle::StartupTraceWriterRegistryHandle(
StartupTraceWriterRegistry* registry)
: registry_(registry) {}
void StartupTraceWriterRegistryHandle::ReturnWriterToRegistry(
std::unique_ptr<StartupTraceWriter> writer) {
std::lock_guard<std::mutex> lock(lock_);
if (registry_)
registry_->ReturnTraceWriter(std::move(writer));
}
void StartupTraceWriterRegistryHandle::OnRegistryDestroyed() {
std::lock_guard<std::mutex> lock(lock_);
registry_ = nullptr;
}
StartupTraceWriterRegistry::StartupTraceWriterRegistry()
: handle_(std::make_shared<StartupTraceWriterRegistryHandle>(this)) {}
StartupTraceWriterRegistry::~StartupTraceWriterRegistry() {
handle_->OnRegistryDestroyed();
}
// static
constexpr size_t StartupTraceWriterRegistry::kDefaultMaxBufferSizeBytes;
std::unique_ptr<StartupTraceWriter>
StartupTraceWriterRegistry::CreateUnboundTraceWriter(
BufferExhaustedPolicy buffer_exhausted_policy,
size_t max_buffer_size_bytes) {
std::lock_guard<std::mutex> lock(lock_);
PERFETTO_DCHECK(!arbiter_); // Should only be called while unbound.
std::unique_ptr<StartupTraceWriter> writer(new StartupTraceWriter(
handle_, buffer_exhausted_policy, max_buffer_size_bytes));
unbound_writers_.push_back(writer.get());
return writer;
}
void StartupTraceWriterRegistry::ReturnTraceWriter(
std::unique_ptr<StartupTraceWriter> trace_writer) {
std::unique_lock<std::mutex> lock(lock_);
// We can only bind the writer on task_runner_.
if (task_runner_ && !task_runner_->RunsTasksOnCurrentThread()) {
// We shouldn't post tasks while holding a lock. |task_runner_| is only set
// once, so will remain valid.
lock.release();
auto weak_this = weak_ptr_factory_->GetWeakPtr();
auto* trace_writer_raw = trace_writer.get();
task_runner_->PostTask([weak_this, trace_writer_raw]() {
std::unique_ptr<StartupTraceWriter> owned_writer(trace_writer_raw);
if (weak_this)
weak_this->ReturnTraceWriter(std::move(owned_writer));
});
return;
}
PERFETTO_DCHECK(!trace_writer->write_in_progress_);
auto it = std::find(unbound_writers_.begin(), unbound_writers_.end(),
trace_writer.get());
// If the registry is already bound, but the writer wasn't, bind it now.
if (arbiter_) {
if (it == unbound_writers_.end()) {
// Nothing to do, the writer was already bound.
return;
}
// This should succeed since nobody can write to this writer concurrently.
bool success = trace_writer->BindToArbiter(arbiter_, target_buffer_,
chunks_per_batch_);
PERFETTO_DCHECK(success);
unbound_writers_.erase(it);
OnUnboundWritersRemovedLocked();
return;
}
// If the registry was not bound yet, keep the writer alive until it is.
PERFETTO_DCHECK(it != unbound_writers_.end());
unbound_writers_.erase(it);
unbound_owned_writers_.push_back(std::move(trace_writer));
}
void StartupTraceWriterRegistry::BindToArbiter(
SharedMemoryArbiterImpl* arbiter,
BufferID target_buffer,
base::TaskRunner* task_runner,
std::function<void(StartupTraceWriterRegistry*)> on_bound_callback) {
std::vector<std::unique_ptr<StartupTraceWriter>> unbound_owned_writers;
{
std::lock_guard<std::mutex> lock(lock_);
PERFETTO_DCHECK(!arbiter_);
arbiter_ = arbiter;
target_buffer_ = target_buffer;
task_runner_ = task_runner;
// Attempt to use at most half the SMB for binding of StartupTraceWriters at
// the same time. In the worst case, all writers are binding at the same
// time, so divide it up between them.
//
// TODO(eseckler): This assumes that there's only a single registry at the
// same time. SharedMemoryArbiterImpl should advise us how much of the SMB
// we're allowed to use in the first place.
size_t num_writers =
unbound_owned_writers_.size() + unbound_writers_.size();
if (num_writers) {
chunks_per_batch_ = arbiter_->num_pages() / 2 / num_writers;
} else {
chunks_per_batch_ = arbiter_->num_pages() / 2;
}
// We should use at least one chunk per batch.
chunks_per_batch_ = std::max(chunks_per_batch_, static_cast<size_t>(1u));
// Weakptrs should be valid on |task_runner|. For this, the factory needs to
// be created on |task_runner|, i.e. BindToArbiter must be called on
// |task_runner|.
PERFETTO_DCHECK(task_runner_->RunsTasksOnCurrentThread());
weak_ptr_factory_.reset(
new base::WeakPtrFactory<StartupTraceWriterRegistry>(this));
on_bound_callback_ = std::move(on_bound_callback);
// We can't destroy the writers while holding |lock_|, so we swap them out
// here instead. After we are bound, no more writers can be added to the
// list.
unbound_owned_writers.swap(unbound_owned_writers_);
}
// Bind and destroy the owned writers.
for (const auto& writer : unbound_owned_writers) {
// This should succeed since nobody can write to these writers concurrently.
bool success =
writer->BindToArbiter(arbiter_, target_buffer_, chunks_per_batch_);
PERFETTO_DCHECK(success);
}
unbound_owned_writers.clear();
TryBindWriters();
}
void StartupTraceWriterRegistry::TryBindWriters() {
std::lock_guard<std::mutex> lock(lock_);
for (auto it = unbound_writers_.begin(); it != unbound_writers_.end();) {
if ((*it)->BindToArbiter(arbiter_, target_buffer_, chunks_per_batch_)) {
it = unbound_writers_.erase(it);
} else {
break;
}
}
if (!unbound_writers_.empty()) {
auto weak_this = weak_ptr_factory_->GetWeakPtr();
task_runner_->PostTask([weak_this] {
if (weak_this)
weak_this->TryBindWriters();
});
}
OnUnboundWritersRemovedLocked();
}
void StartupTraceWriterRegistry::OnUnboundWritersRemovedLocked() {
if (!unbound_writers_.empty() || !task_runner_ || !on_bound_callback_)
return;
PERFETTO_DCHECK(weak_ptr_factory_);
auto weak_this = weak_ptr_factory_->GetWeakPtr();
// Run callback in PostTask() since the callback may delete |this| and thus
// might otherwise cause a deadlock.
auto callback = on_bound_callback_;
on_bound_callback_ = nullptr;
task_runner_->PostTask([weak_this, callback]() {
if (!weak_this)
return;
// Note: callback may delete |this|.
callback(weak_this.get());
});
}
} // namespace perfetto
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/usr/isteps/istep06/call_host_voltage_config.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
#include <stdint.h>
#include <trace/interface.H>
#include <errl/errlentry.H>
#include <errl/errlmanager.H>
#include <isteps/hwpisteperror.H>
#include <initservice/isteps_trace.H>
#include <fapi2.H>
#include <fapi2/plat_hwp_invoker.H>
//Targeting
#include <targeting/common/commontargeting.H>
#include <targeting/common/util.H>
#include <targeting/common/utilFilter.H>
#include <targeting/common/target.H>
#include <p9_pm_get_poundv_bucket.H>
#include <p9_setup_evid.H>
//SBE
#include <sbe/sbeif.H>
#include <initservice/mboxRegs.H>
#include <p9_frequency_buckets.H>
using namespace TARGETING;
namespace ISTEP_06
{
void* call_host_voltage_config( void *io_pArgs )
{
TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
"call_host_voltage_config entry" );
ISTEP_ERROR::IStepError l_stepError;
errlHndl_t l_err = nullptr;
Target * l_sys = nullptr;
TargetHandleList l_procList;
TargetHandleList l_eqList;
fapi2::voltageBucketData_t l_voltageData;
fapi2::ReturnCode l_rc;
uint32_t l_nominalFreq = 0; //ATTR_NOMINAL_FREQ_MHZ
uint32_t l_floorFreq = 0; //ATTR_FREQ_FLOOR_MHZ
uint32_t l_ceilingFreq = 0; //ATTR_FREQ_CORE_CEILING_MHZ
uint32_t l_ultraTurboFreq = 0; //ATTR_ULTRA_TURBO_FREQ_MHZ
uint32_t l_turboFreq = 0; //ATTR_FREQ_CORE_MAX
uint32_t l_vddBootVoltage = 0; //ATTR_VDD_BOOT_VOLTAGE
uint32_t l_vdnBootVoltage = 0; //ATTR_VDN_BOOT_VOLTAGE
uint32_t l_vcsBootVoltage = 0; //ATTR_VCS_BOOT_VOLTAGE
uint32_t l_nestFreq = 0; //ATTR_FREQ_PB_MHZ
bool l_firstPass = true;
PredicateCTM l_eqFilter(CLASS_UNIT, TYPE_EQ);
PredicateHwas l_predPres;
l_predPres.present(true);
PredicatePostfixExpr l_presentEqs;
l_presentEqs.push(&l_eqFilter).push(&l_predPres).And();
do
{
// Get the system target
targetService().getTopLevelTarget(l_sys);
// Set the Nest frequency to whatever we boot with
l_err = SBE::getBootNestFreq( l_nestFreq );
if( l_err )
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"call_host_voltage_config.C::"
"Failed getting the boot nest frequency from the SBE");
break;
}
l_sys->setAttr<TARGETING::ATTR_FREQ_PB_MHZ>( l_nestFreq );
// Get the child proc chips
getChildAffinityTargets( l_procList,
l_sys,
CLASS_CHIP,
TYPE_PROC );
// for each proc target
for( const auto & l_proc : l_procList )
{
// get the child EQ targets
targetService().getAssociated(
l_eqList,
l_proc,
TargetService::CHILD_BY_AFFINITY,
TargetService::ALL,
&l_presentEqs );
if( l_eqList.empty() )
{
TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
"No children of proc 0x%x found to have type EQ",
get_huid(l_proc));
/*@
* @errortype
* @moduleid ISTEP::MOD_VOLTAGE_CONFIG
* @reasoncode ISTEP::RC_NO_PRESENT_EQS
* @userdata1 Parent PROC huid
* @devdesc No present EQs found on processor
* @custdesc A problem occurred during the IPL of the system.
*/
l_err = new ERRORLOG::ErrlEntry
(ERRORLOG::ERRL_SEV_CRITICAL_SYS_TERM,
ISTEP::MOD_VOLTAGE_CONFIG,
ISTEP::RC_NO_PRESENT_EQS,
get_huid(l_proc),
0,
true /*HB SW error*/ );
break;
}
// for each child EQ target
for( const auto & l_eq : l_eqList )
{
// cast to fapi2 target
fapi2::Target<fapi2::TARGET_TYPE_EQ> l_fapiEq( l_eq );
// get the #V data for this EQ
FAPI_INVOKE_HWP( l_err,
p9_pm_get_poundv_bucket,
l_fapiEq,
l_voltageData);
if( l_err )
{
TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
"Error in call_host_voltage_config::p9_pm_get_poundv_bucket");
// Create IStep error log and cross reference occurred error
l_stepError.addErrorDetails( l_err );
// Commit Error
errlCommit( l_err, ISTEP_COMP_ID );
continue;
}
// Save the voltage data for future comparison
if( l_firstPass )
{
l_nominalFreq = l_voltageData.nomFreq;
l_floorFreq = l_voltageData.PSFreq;
l_ceilingFreq = l_voltageData.turboFreq;
l_ultraTurboFreq = l_voltageData.uTurboFreq;
l_turboFreq = l_voltageData.turboFreq;
l_vddBootVoltage = l_voltageData.VddPSVltg;
l_vdnBootVoltage = l_voltageData.VddPSVltg;
l_vcsBootVoltage = l_voltageData.VcsPSVltg;
l_firstPass = false;
}
else
{
// save it to variable and compare agains other nomFreq
// All of the buckets should report the same Nominal frequency
if( l_nominalFreq != l_voltageData.nomFreq )
{
TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
"NOMINAL FREQ MISMATCH! expected: %d actual: %d",
l_nominalFreq, l_voltageData.nomFreq );
l_err = new ERRORLOG::ErrlEntry
(ERRORLOG::ERRL_SEV_CRITICAL_SYS_TERM,
ISTEP::MOD_VOLTAGE_CONFIG,
ISTEP::RC_NOMINAL_FREQ_MISMATCH,
l_nominalFreq,
l_voltageData.nomFreq,
false );
l_err->addHwCallout(l_proc,
HWAS::SRCI_PRIORITY_HIGH,
HWAS::DECONFIG,
HWAS::GARD_NULL );
// Create IStep error log and cross reference occurred error
l_stepError.addErrorDetails( l_err );
// Commit Error
errlCommit( l_err, ISTEP_COMP_ID );
continue;
}
// Floor frequency is the maximum of the Power Save Freqs
l_floorFreq =
(l_voltageData.PSFreq > l_floorFreq) ? l_voltageData.PSFreq : l_floorFreq;
// Ceiling frequency is the minimum of the Turbo Freqs
l_ceilingFreq = (l_voltageData.turboFreq < l_ceilingFreq) ?
l_voltageData.turboFreq : l_ceilingFreq;
// Ultra Turbo frequency is the minimum of the Ultra Turbo Freqs
l_ultraTurboFreq = (l_voltageData.uTurboFreq < l_ultraTurboFreq) ?
l_voltageData.uTurboFreq : l_ultraTurboFreq;
// Turbo frequency is the minimum of the Turbo Freqs
l_turboFreq = l_ceilingFreq;
}
} // EQ for-loop
// set the approprate attributes on the processor
l_proc->setAttr<ATTR_VDD_BOOT_VOLTAGE>( l_vddBootVoltage );
l_proc->setAttr<ATTR_VDN_BOOT_VOLTAGE>( l_vdnBootVoltage );
l_proc->setAttr<ATTR_VCS_BOOT_VOLTAGE>( l_vcsBootVoltage );
TRACDCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"Setting VDD/VDN/VCS boot voltage for proc huid = 0x%x"
" VDD = %d, VDN = %d, VCS = %d",
get_huid(l_proc),
l_vddBootVoltage,
l_vdnBootVoltage,
l_vcsBootVoltage );
// call p9_setup_evid for each processor
fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>l_fapiProc(l_proc);
FAPI_INVOKE_HWP(l_err, p9_setup_evid, l_fapiProc, COMPUTE_VOLTAGE_SETTINGS);
if( l_err )
{
TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
"Error in call_host_voltage_config::p9_setup_evid");
// Create IStep error log and cross reference occurred error
l_stepError.addErrorDetails( l_err );
// Commit Error
errlCommit( l_err, ISTEP_COMP_ID );
continue;
}
} // PROC for-loop
// If we hit an error from p9_setup_evid, quit
if( l_err )
{
break;
}
// set the frequency system targets
l_sys->setAttr<ATTR_NOMINAL_FREQ_MHZ>( l_nominalFreq );
l_sys->setAttr<ATTR_MIN_FREQ_MHZ>( l_floorFreq );
l_sys->setAttr<ATTR_FREQ_CORE_CEILING_MHZ>( l_ceilingFreq );
l_sys->setAttr<ATTR_FREQ_CORE_MAX>( l_turboFreq );
l_sys->setAttr<ATTR_ULTRA_TURBO_FREQ_MHZ>(l_ultraTurboFreq);
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"Setting System Frequency Attributes: "
"Nominal = %d, Floor = %d, Ceiling = %d, "
"Turbo = %d, UltraTurbo = %d",
l_nominalFreq, l_floorFreq, l_ceilingFreq,
l_turboFreq, l_ultraTurboFreq );
// Setup the remaining attributes that are based on PB/Nest
SBE::setNestFreqAttributes(l_nestFreq);
//NEST_PLL_BUCKET
for( size_t l_bucket = 1; l_bucket <= NEST_PLL_FREQ_BUCKETS; l_bucket++ )
{
// The nest PLL bucket IDs are numbered 1 - 5. Subtract 1 to
// take zero-based indexing into account.
if( NEST_PLL_FREQ_LIST[l_bucket-1] == l_nestFreq )
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"ATTR_NEST_PLL_BUCKET getting set to %x",
l_bucket);
l_sys->setAttr<TARGETING::ATTR_NEST_PLL_BUCKET>(l_bucket);
break;
}
}
} while( 0 );
if( l_err )
{
// Create IStep error log and cross reference occurred error
l_stepError.addErrorDetails( l_err );
// Commit Error
errlCommit( l_err, ISTEP_COMP_ID );
}
TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
"call_host_voltage_config exit" );
return l_stepError.getErrorHandle();
}
};
<commit_msg>Read VDN from appropriate #V field<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/usr/isteps/istep06/call_host_voltage_config.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
#include <stdint.h>
#include <trace/interface.H>
#include <errl/errlentry.H>
#include <errl/errlmanager.H>
#include <isteps/hwpisteperror.H>
#include <initservice/isteps_trace.H>
#include <fapi2.H>
#include <fapi2/plat_hwp_invoker.H>
//Targeting
#include <targeting/common/commontargeting.H>
#include <targeting/common/util.H>
#include <targeting/common/utilFilter.H>
#include <targeting/common/target.H>
#include <p9_pm_get_poundv_bucket.H>
#include <p9_setup_evid.H>
//SBE
#include <sbe/sbeif.H>
#include <initservice/mboxRegs.H>
#include <p9_frequency_buckets.H>
using namespace TARGETING;
namespace ISTEP_06
{
void* call_host_voltage_config( void *io_pArgs )
{
TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
"call_host_voltage_config entry" );
ISTEP_ERROR::IStepError l_stepError;
errlHndl_t l_err = nullptr;
Target * l_sys = nullptr;
TargetHandleList l_procList;
TargetHandleList l_eqList;
fapi2::voltageBucketData_t l_voltageData;
fapi2::ReturnCode l_rc;
uint32_t l_nominalFreq = 0; //ATTR_NOMINAL_FREQ_MHZ
uint32_t l_floorFreq = 0; //ATTR_FREQ_FLOOR_MHZ
uint32_t l_ceilingFreq = 0; //ATTR_FREQ_CORE_CEILING_MHZ
uint32_t l_ultraTurboFreq = 0; //ATTR_ULTRA_TURBO_FREQ_MHZ
uint32_t l_turboFreq = 0; //ATTR_FREQ_CORE_MAX
uint32_t l_vddBootVoltage = 0; //ATTR_VDD_BOOT_VOLTAGE
uint32_t l_vdnBootVoltage = 0; //ATTR_VDN_BOOT_VOLTAGE
uint32_t l_vcsBootVoltage = 0; //ATTR_VCS_BOOT_VOLTAGE
uint32_t l_nestFreq = 0; //ATTR_FREQ_PB_MHZ
bool l_firstPass = true;
PredicateCTM l_eqFilter(CLASS_UNIT, TYPE_EQ);
PredicateHwas l_predPres;
l_predPres.present(true);
PredicatePostfixExpr l_presentEqs;
l_presentEqs.push(&l_eqFilter).push(&l_predPres).And();
do
{
// Get the system target
targetService().getTopLevelTarget(l_sys);
// Set the Nest frequency to whatever we boot with
l_err = SBE::getBootNestFreq( l_nestFreq );
if( l_err )
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"call_host_voltage_config.C::"
"Failed getting the boot nest frequency from the SBE");
break;
}
l_sys->setAttr<TARGETING::ATTR_FREQ_PB_MHZ>( l_nestFreq );
// Get the child proc chips
getChildAffinityTargets( l_procList,
l_sys,
CLASS_CHIP,
TYPE_PROC );
// for each proc target
for( const auto & l_proc : l_procList )
{
// get the child EQ targets
targetService().getAssociated(
l_eqList,
l_proc,
TargetService::CHILD_BY_AFFINITY,
TargetService::ALL,
&l_presentEqs );
if( l_eqList.empty() )
{
TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
"No children of proc 0x%x found to have type EQ",
get_huid(l_proc));
/*@
* @errortype
* @moduleid ISTEP::MOD_VOLTAGE_CONFIG
* @reasoncode ISTEP::RC_NO_PRESENT_EQS
* @userdata1 Parent PROC huid
* @devdesc No present EQs found on processor
* @custdesc A problem occurred during the IPL of the system.
*/
l_err = new ERRORLOG::ErrlEntry
(ERRORLOG::ERRL_SEV_CRITICAL_SYS_TERM,
ISTEP::MOD_VOLTAGE_CONFIG,
ISTEP::RC_NO_PRESENT_EQS,
get_huid(l_proc),
0,
true /*HB SW error*/ );
break;
}
// for each child EQ target
for( const auto & l_eq : l_eqList )
{
// cast to fapi2 target
fapi2::Target<fapi2::TARGET_TYPE_EQ> l_fapiEq( l_eq );
// get the #V data for this EQ
FAPI_INVOKE_HWP( l_err,
p9_pm_get_poundv_bucket,
l_fapiEq,
l_voltageData);
if( l_err )
{
TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
"Error in call_host_voltage_config::p9_pm_get_poundv_bucket");
// Create IStep error log and cross reference occurred error
l_stepError.addErrorDetails( l_err );
// Commit Error
errlCommit( l_err, ISTEP_COMP_ID );
continue;
}
// Save the voltage data for future comparison
if( l_firstPass )
{
l_nominalFreq = l_voltageData.nomFreq;
l_floorFreq = l_voltageData.PSFreq;
l_ceilingFreq = l_voltageData.turboFreq;
l_ultraTurboFreq = l_voltageData.uTurboFreq;
l_turboFreq = l_voltageData.turboFreq;
l_vddBootVoltage = l_voltageData.VddPSVltg;
l_vdnBootVoltage = l_voltageData.VdnPbVltg;
l_vcsBootVoltage = l_voltageData.VcsPSVltg;
l_firstPass = false;
}
else
{
// save it to variable and compare agains other nomFreq
// All of the buckets should report the same Nominal frequency
if( l_nominalFreq != l_voltageData.nomFreq )
{
TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
"NOMINAL FREQ MISMATCH! expected: %d actual: %d",
l_nominalFreq, l_voltageData.nomFreq );
l_err = new ERRORLOG::ErrlEntry
(ERRORLOG::ERRL_SEV_CRITICAL_SYS_TERM,
ISTEP::MOD_VOLTAGE_CONFIG,
ISTEP::RC_NOMINAL_FREQ_MISMATCH,
l_nominalFreq,
l_voltageData.nomFreq,
false );
l_err->addHwCallout(l_proc,
HWAS::SRCI_PRIORITY_HIGH,
HWAS::DECONFIG,
HWAS::GARD_NULL );
// Create IStep error log and cross reference occurred error
l_stepError.addErrorDetails( l_err );
// Commit Error
errlCommit( l_err, ISTEP_COMP_ID );
continue;
}
// Floor frequency is the maximum of the Power Save Freqs
l_floorFreq =
(l_voltageData.PSFreq > l_floorFreq) ? l_voltageData.PSFreq : l_floorFreq;
// Ceiling frequency is the minimum of the Turbo Freqs
l_ceilingFreq = (l_voltageData.turboFreq < l_ceilingFreq) ?
l_voltageData.turboFreq : l_ceilingFreq;
// Ultra Turbo frequency is the minimum of the Ultra Turbo Freqs
l_ultraTurboFreq = (l_voltageData.uTurboFreq < l_ultraTurboFreq) ?
l_voltageData.uTurboFreq : l_ultraTurboFreq;
// Turbo frequency is the minimum of the Turbo Freqs
l_turboFreq = l_ceilingFreq;
}
} // EQ for-loop
// set the approprate attributes on the processor
l_proc->setAttr<ATTR_VDD_BOOT_VOLTAGE>( l_vddBootVoltage );
l_proc->setAttr<ATTR_VDN_BOOT_VOLTAGE>( l_vdnBootVoltage );
l_proc->setAttr<ATTR_VCS_BOOT_VOLTAGE>( l_vcsBootVoltage );
TRACDCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"Setting VDD/VDN/VCS boot voltage for proc huid = 0x%x"
" VDD = %d, VDN = %d, VCS = %d",
get_huid(l_proc),
l_vddBootVoltage,
l_vdnBootVoltage,
l_vcsBootVoltage );
// call p9_setup_evid for each processor
fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>l_fapiProc(l_proc);
FAPI_INVOKE_HWP(l_err, p9_setup_evid, l_fapiProc, COMPUTE_VOLTAGE_SETTINGS);
if( l_err )
{
TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
"Error in call_host_voltage_config::p9_setup_evid");
// Create IStep error log and cross reference occurred error
l_stepError.addErrorDetails( l_err );
// Commit Error
errlCommit( l_err, ISTEP_COMP_ID );
continue;
}
} // PROC for-loop
// If we hit an error from p9_setup_evid, quit
if( l_err )
{
break;
}
// set the frequency system targets
l_sys->setAttr<ATTR_NOMINAL_FREQ_MHZ>( l_nominalFreq );
l_sys->setAttr<ATTR_MIN_FREQ_MHZ>( l_floorFreq );
l_sys->setAttr<ATTR_FREQ_CORE_CEILING_MHZ>( l_ceilingFreq );
l_sys->setAttr<ATTR_FREQ_CORE_MAX>( l_turboFreq );
l_sys->setAttr<ATTR_ULTRA_TURBO_FREQ_MHZ>(l_ultraTurboFreq);
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"Setting System Frequency Attributes: "
"Nominal = %d, Floor = %d, Ceiling = %d, "
"Turbo = %d, UltraTurbo = %d",
l_nominalFreq, l_floorFreq, l_ceilingFreq,
l_turboFreq, l_ultraTurboFreq );
// Setup the remaining attributes that are based on PB/Nest
SBE::setNestFreqAttributes(l_nestFreq);
//NEST_PLL_BUCKET
for( size_t l_bucket = 1; l_bucket <= NEST_PLL_FREQ_BUCKETS; l_bucket++ )
{
// The nest PLL bucket IDs are numbered 1 - 5. Subtract 1 to
// take zero-based indexing into account.
if( NEST_PLL_FREQ_LIST[l_bucket-1] == l_nestFreq )
{
TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
"ATTR_NEST_PLL_BUCKET getting set to %x",
l_bucket);
l_sys->setAttr<TARGETING::ATTR_NEST_PLL_BUCKET>(l_bucket);
break;
}
}
} while( 0 );
if( l_err )
{
// Create IStep error log and cross reference occurred error
l_stepError.addErrorDetails( l_err );
// Commit Error
errlCommit( l_err, ISTEP_COMP_ID );
}
TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
"call_host_voltage_config exit" );
return l_stepError.getErrorHandle();
}
};
<|endoftext|> |
<commit_before>/*
* Copyright 2006-2008 The FLWOR Foundation.
*
* 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 <algorithm>
#include "util/less.h"
#include "wn_types.h"
using namespace std;
namespace zorba {
namespace wordnet {
///////////////////////////////////////////////////////////////////////////////
namespace part_of_speech {
type find( char pos ) {
switch ( pos ) {
case adjective:
case adverb:
case noun:
case verb:
return static_cast<type>( pos );
default:
return unknown;
}
}
} // namespace part_of_speech
///////////////////////////////////////////////////////////////////////////////
#define DEF_END(CHAR_ARRAY) \
static char const *const *const end = \
CHAR_ARRAY + sizeof( CHAR_ARRAY ) / sizeof( char* );
#define FIND(what) \
static_cast<type>( find_index( string_of, end, what ) )
/**
* A less-verbose way to use std::lower_bound.
*/
inline int find_index( char const *const *begin, char const *const *end,
char const *s ) {
char const *const *const entry =
::lower_bound( begin, end, s, less<char const*>() );
return entry != end && ::strcmp( s, *entry ) == 0 ? entry - begin : 0;
}
namespace pointer {
char const *const string_of[] = {
"#UNKNOWN",
"also see",
"antonym",
"attribute",
"cause",
"derivationally related form",
"derived from adjective",
"domain of synset region",
"domain of synset topic",
"domain of synset usage",
"entailment",
"hypernym",
"hyponym",
"instance hypernym",
"instance hyponym",
"member holonym",
"member meronym",
"member of domain region",
"member of domain topic",
"member of domain usage",
"part holonym",
"part meronym",
"participle of verb",
"pertainym",
"similar to",
"substance holonym",
"substance meronym",
"verb group"
};
type find( char ptr_symbol ) {
switch ( ptr_symbol ) {
case 'A' /* ! */: return antonym;
case 'a' /* = */: return attribute;
case 'C' /* > */: return cause;
case 'D' /* \ */: return derived_from_adjective;
case 'E' /* @ */: return hypernym;
case 'e' /* @i */: return instance_hypernym;
case 'F' /* + */: return derivationally_related_form;
case 'G' /* $ */: return verb_group;
case 'H' /* #m */: return member_holonym;
case 'h' /* #p */: return part_holonym;
case 'i' /* #s */: return substance_holonym;
case 'L' /* * */: return entailment;
case 'M' /* %m */: return member_meronym;
case 'm' /* %p */: return part_meronym;
case 'n' /* %s */: return substance_meronym;
case 'O' /* ~ */: return hyponym;
case 'o' /* ~i */: return instance_hyponym;
case 'P' /* \ */: return pertainym;
case 'R' /* ;r */: return domain_of_synset_region;
case 'r' /* -r */: return member_of_domain_region;
case 'S' /* ^ */: return also_see;
case 'T' /* ;c */: return domain_of_synset_topic;
case 't' /* -c */: return member_of_domain_topic;
case 'U' /* ;u */: return domain_of_synset_usage;
case 'u' /* -u */: return member_of_domain_usage;
case 'V' /* < */: return participle_of_verb;
case '~' /* & */: return similar_to;
default : return unknown;
}
}
type find( char const *relationship ) {
DEF_END( string_of );
return FIND( relationship );
}
type map_iso_rel( iso2788::rel_type iso_rel ) {
switch ( iso_rel ) {
case iso2788::BT : return hypernym;
case iso2788::BTG:
case iso2788::BTP:
case iso2788::NT : return hyponym;
case iso2788::NTG:
case iso2788::NTP:
case iso2788::RT : return similar_to;
case iso2788::TT :
case iso2788::UF :
case iso2788::USE:
default : return unknown;
}
}
} // namespace pointer
///////////////////////////////////////////////////////////////////////////////
} // namespace wordnet
} // namespace zorba
/* vim:set et sw=2 ts=2: */
<commit_msg>Comment addition.<commit_after>/*
* Copyright 2006-2008 The FLWOR Foundation.
*
* 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 <algorithm> /* for lower_bound */
#include "util/less.h"
#include "wn_types.h"
using namespace std;
namespace zorba {
namespace wordnet {
///////////////////////////////////////////////////////////////////////////////
namespace part_of_speech {
type find( char pos ) {
switch ( pos ) {
case adjective:
case adverb:
case noun:
case verb:
return static_cast<type>( pos );
default:
return unknown;
}
}
} // namespace part_of_speech
///////////////////////////////////////////////////////////////////////////////
#define DEF_END(CHAR_ARRAY) \
static char const *const *const end = \
CHAR_ARRAY + sizeof( CHAR_ARRAY ) / sizeof( char* );
#define FIND(what) \
static_cast<type>( find_index( string_of, end, what ) )
/**
* A less-verbose way to use std::lower_bound.
*/
inline int find_index( char const *const *begin, char const *const *end,
char const *s ) {
char const *const *const entry =
::lower_bound( begin, end, s, less<char const*>() );
return entry != end && ::strcmp( s, *entry ) == 0 ? entry - begin : 0;
}
namespace pointer {
char const *const string_of[] = {
"#UNKNOWN",
"also see",
"antonym",
"attribute",
"cause",
"derivationally related form",
"derived from adjective",
"domain of synset region",
"domain of synset topic",
"domain of synset usage",
"entailment",
"hypernym",
"hyponym",
"instance hypernym",
"instance hyponym",
"member holonym",
"member meronym",
"member of domain region",
"member of domain topic",
"member of domain usage",
"part holonym",
"part meronym",
"participle of verb",
"pertainym",
"similar to",
"substance holonym",
"substance meronym",
"verb group"
};
type find( char ptr_symbol ) {
switch ( ptr_symbol ) {
case 'A' /* ! */: return antonym;
case 'a' /* = */: return attribute;
case 'C' /* > */: return cause;
case 'D' /* \ */: return derived_from_adjective;
case 'E' /* @ */: return hypernym;
case 'e' /* @i */: return instance_hypernym;
case 'F' /* + */: return derivationally_related_form;
case 'G' /* $ */: return verb_group;
case 'H' /* #m */: return member_holonym;
case 'h' /* #p */: return part_holonym;
case 'i' /* #s */: return substance_holonym;
case 'L' /* * */: return entailment;
case 'M' /* %m */: return member_meronym;
case 'm' /* %p */: return part_meronym;
case 'n' /* %s */: return substance_meronym;
case 'O' /* ~ */: return hyponym;
case 'o' /* ~i */: return instance_hyponym;
case 'P' /* \ */: return pertainym;
case 'R' /* ;r */: return domain_of_synset_region;
case 'r' /* -r */: return member_of_domain_region;
case 'S' /* ^ */: return also_see;
case 'T' /* ;c */: return domain_of_synset_topic;
case 't' /* -c */: return member_of_domain_topic;
case 'U' /* ;u */: return domain_of_synset_usage;
case 'u' /* -u */: return member_of_domain_usage;
case 'V' /* < */: return participle_of_verb;
case '~' /* & */: return similar_to;
default : return unknown;
}
}
type find( char const *relationship ) {
DEF_END( string_of );
return FIND( relationship );
}
type map_iso_rel( iso2788::rel_type iso_rel ) {
switch ( iso_rel ) {
case iso2788::BT : return hypernym;
case iso2788::BTG:
case iso2788::BTP:
case iso2788::NT : return hyponym;
case iso2788::NTG:
case iso2788::NTP:
case iso2788::RT : return similar_to;
case iso2788::TT :
case iso2788::UF :
case iso2788::USE:
default : return unknown;
}
}
} // namespace pointer
///////////////////////////////////////////////////////////////////////////////
} // namespace wordnet
} // namespace zorba
/* vim:set et sw=2 ts=2: */
<|endoftext|> |
<commit_before>#include <adios2.h>
#include <fstream>
#include <gtest/gtest.h>
TEST(ADIOS2ReadNonBPFile, ShortBadFile)
{
std::ofstream of{"foo.bp"};
of << "Hello, world!\n";
of.close();
adios2::ADIOS adios;
adios2::IO io = adios.DeclareIO("Test");
EXPECT_THROW(io.Open("foo.bp", adios2::Mode::Read), std::exception);
std::remove("foo.bp");
}
TEST(ADIOS2ReadNonBPFile, LongBadFile)
{
std::ofstream of{"foo.bp"};
of << "hellohellohellohellohellohellohellohellohellohellohellohellohello\n";
of.close();
adios2::ADIOS adios;
adios2::IO io = adios.DeclareIO("Test");
// auto bpReader = io.Open("foo.bp", adios2::Mode::Read);
EXPECT_THROW(io.Open("foo.bp", adios2::Mode::Read), std::exception);
std::remove("foo.bp");
}
TEST(ADIOS2ReadNonBPFile, LongBadFileWithValidEndianness)
{
std::ofstream of("foo.bp", std::ios::out | std::ios::binary);
char a = 0x00;
for (size_t i = 0; i < 100; ++i)
{
of.write(static_cast<char *>(&a), 1);
}
of.close();
adios2::ADIOS adios;
adios2::IO io = adios.DeclareIO("Test");
EXPECT_THROW(io.Open("foo.bp", adios2::Mode::Read), std::exception);
std::remove("foo.bp");
}
int main(int argc, char **argv)
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}<commit_msg>testing: Add newline on last line of TestReadNonBPFile.cpp<commit_after>#include <adios2.h>
#include <fstream>
#include <gtest/gtest.h>
TEST(ADIOS2ReadNonBPFile, ShortBadFile)
{
std::ofstream of{"foo.bp"};
of << "Hello, world!\n";
of.close();
adios2::ADIOS adios;
adios2::IO io = adios.DeclareIO("Test");
EXPECT_THROW(io.Open("foo.bp", adios2::Mode::Read), std::exception);
std::remove("foo.bp");
}
TEST(ADIOS2ReadNonBPFile, LongBadFile)
{
std::ofstream of{"foo.bp"};
of << "hellohellohellohellohellohellohellohellohellohellohellohellohello\n";
of.close();
adios2::ADIOS adios;
adios2::IO io = adios.DeclareIO("Test");
// auto bpReader = io.Open("foo.bp", adios2::Mode::Read);
EXPECT_THROW(io.Open("foo.bp", adios2::Mode::Read), std::exception);
std::remove("foo.bp");
}
TEST(ADIOS2ReadNonBPFile, LongBadFileWithValidEndianness)
{
std::ofstream of("foo.bp", std::ios::out | std::ios::binary);
char a = 0x00;
for (size_t i = 0; i < 100; ++i)
{
of.write(static_cast<char *>(&a), 1);
}
of.close();
adios2::ADIOS adios;
adios2::IO io = adios.DeclareIO("Test");
EXPECT_THROW(io.Open("foo.bp", adios2::Mode::Read), std::exception);
std::remove("foo.bp");
}
int main(int argc, char **argv)
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2014-2015 Daniel Nicoletti <dantti12@gmail.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "multipartformdataparser_p.h"
#include "upload_p.h"
#include "common.h"
#include <QRegularExpression>
#include <QStringBuilder>
using namespace Cutelyst;
Uploads MultiPartFormDataParser::parse(QIODevice *body, const QString &contentType, int bufferSize)
{
MultiPartFormDataParserPrivate *d;
static QRegularExpression staticRE(QStringLiteral("boundary=\"?([^\";]+)\"?"));
QRegularExpression re = staticRE;
QRegularExpressionMatch match = re.match(contentType);
if (match.hasMatch()) {
QString boundary = match.captured(1);
if (boundary.isEmpty()) {
qCWarning(CUTELYST_MULTIPART) << "Boudary matched empty string" << contentType;
return Uploads();
}
boundary.prepend(QLatin1String("--"));
d = new MultiPartFormDataParserPrivate;
d->boundary = qstrdup(boundary.toLatin1().data());
d->boundaryLength = boundary.size();
} else {
qCWarning(CUTELYST_MULTIPART) << "No boudary match" << contentType;
return Uploads();
}
d->body = body;
int buffer_size = qMin(bufferSize, 1024);
// qCDebug(CUTELYST_MULTIPART) << "Boudary:" << d->boundary << d->boundaryLength;
Uploads ret;
char *buffer = new char[buffer_size];
qint64 origPos = d->body->pos();
d->body->seek(0);
ret = d->execute(buffer, buffer_size);
d->body->seek(origPos);
delete [] buffer;
delete [] d->boundary;
delete d;
return ret;
}
Uploads MultiPartFormDataParserPrivate::execute(char *buffer, int bufferSize)
{
Uploads ret;
QByteArray header;
Headers headers;
qint64 startOffset;
int boundaryPos = 0;
ParserState state = FindBoundary;
while (!body->atEnd()) {
qint64 len = body->read(buffer, bufferSize);
int i = 0;
while (i < len) {
switch (state) {
case FindBoundary:
i += findBoundary(buffer + i, len - i, state, boundaryPos);
break;
case EndBoundaryCR:
// TODO the "--" case
if (buffer[i] != '\r') {
// qCDebug(CUTELYST_MULTIPART) << "EndBoundaryCR return!";
return ret;
}
state = EndBoundaryLF;
break;
case EndBoundaryLF:
if (buffer[i] != '\n') {
// qCDebug(CUTELYST_MULTIPART) << "EndBoundaryLF return!";
return ret;
}
header.clear();
state = StartHeaders;
break;
case StartHeaders:
// qCDebug(CUTELYST_MULTIPART) << "StartHeaders" << body->pos() - len + i;
if (buffer[i] == '\r') {
state = EndHeaders;
} else if (buffer[i] == '-') {
// qCDebug(CUTELYST_MULTIPART) << "StartHeaders return!";
return ret;
} else {
char *pch = strchr(buffer + i, '\r');
if (pch == NULL) {
header.append(buffer + i, len - i);
i = len;
} else {
header.append(buffer + i, pch - buffer - i);
i = pch - buffer;
state = FinishHeader;
}
}
break;
case FinishHeader:
// qCDebug(CUTELYST_MULTIPART) << "FinishHeader" << header;
if (buffer[i] == '\n') {
int dotdot = header.indexOf(':');
headers.setHeader(QString::fromLatin1(header.left(dotdot)),
QString::fromLatin1(header.mid(dotdot + 1).trimmed()));
header.clear();
state = StartHeaders;
} else {
// qCDebug(CUTELYST_MULTIPART) << "FinishHeader return!";
return ret;
}
break;
case EndHeaders:
// qCDebug(CUTELYST_MULTIPART) << "EndHeaders";
if (buffer[i] == '\n') {
state = StartData;
} else {
// qCDebug(CUTELYST_MULTIPART) << "EndHeaders return!";
return ret;
}
break;
case StartData:
// qCDebug(CUTELYST_MULTIPART) << "StartData" << body->pos() - len + i;
startOffset = body->pos() - len + i;
state = EndData;
case EndData:
i += findBoundary(buffer + i, len - i, state, boundaryPos);
if (state == EndBoundaryCR) {
// qCDebug(CUTELYST_MULTIPART) << "EndData" << body->pos() - len + i - boundaryLength - 1;
UploadPrivate *priv = new UploadPrivate(body);
priv->headers = headers;
headers.clear();
priv->startOffset = startOffset;
priv->endOffset = body->pos() - len + i - boundaryLength - 1;
ret << new Upload(priv);
}
}
++i;
}
}
return ret;
}
int MultiPartFormDataParserPrivate::findBoundary(char *buffer, int len, MultiPartFormDataParserPrivate::ParserState &state, int &boundaryPos)
{
int i = 0;
while (i < len) {
if (buffer[i] == boundary[boundaryPos]) {
if (++boundaryPos == boundaryLength) {
// qCDebug(CUTELYST_MULTIPART) << "FindBoundary:" << body->pos() - len + i;
boundaryPos = 0;
state = EndBoundaryCR;
return i;
}
} else {
boundaryPos = 0;
}
++i;
}
return i;
}
<commit_msg>Match the boundary string with indexOf which matches up to 5x faster than with QRegularExpression<commit_after>/*
* Copyright (C) 2014-2015 Daniel Nicoletti <dantti12@gmail.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "multipartformdataparser_p.h"
#include "upload_p.h"
#include "common.h"
#include <QStringBuilder>
using namespace Cutelyst;
Uploads MultiPartFormDataParser::parse(QIODevice *body, const QString &contentType, int bufferSize)
{
MultiPartFormDataParserPrivate *d;
int start = contentType.indexOf(QLatin1String("boundary=\""));
if (start != -1) {
start += 10;
QString boundary;
int end = contentType.indexOf(QLatin1String("\""), start);
if (end != -1) {
boundary = contentType.mid(start, end - start);
} else {
qCWarning(CUTELYST_MULTIPART) << "No boudary match" << contentType;
return Uploads();
}
boundary.prepend(QLatin1String("--"));
d = new MultiPartFormDataParserPrivate;
d->boundary = qstrdup(boundary.toLatin1().data());
d->boundaryLength = boundary.size();
} else {
qCWarning(CUTELYST_MULTIPART) << "No boudary match" << contentType;
return Uploads();
}
d->body = body;
int buffer_size = qMin(bufferSize, 1024);
// qCDebug(CUTELYST_MULTIPART) << "Boudary:" << d->boundary << d->boundaryLength;
Uploads ret;
char *buffer = new char[buffer_size];
qint64 origPos = d->body->pos();
d->body->seek(0);
ret = d->execute(buffer, buffer_size);
d->body->seek(origPos);
delete [] buffer;
delete [] d->boundary;
delete d;
return ret;
}
Uploads MultiPartFormDataParserPrivate::execute(char *buffer, int bufferSize)
{
Uploads ret;
QByteArray header;
Headers headers;
qint64 startOffset;
int boundaryPos = 0;
ParserState state = FindBoundary;
while (!body->atEnd()) {
qint64 len = body->read(buffer, bufferSize);
int i = 0;
while (i < len) {
switch (state) {
case FindBoundary:
i += findBoundary(buffer + i, len - i, state, boundaryPos);
break;
case EndBoundaryCR:
// TODO the "--" case
if (buffer[i] != '\r') {
// qCDebug(CUTELYST_MULTIPART) << "EndBoundaryCR return!";
return ret;
}
state = EndBoundaryLF;
break;
case EndBoundaryLF:
if (buffer[i] != '\n') {
// qCDebug(CUTELYST_MULTIPART) << "EndBoundaryLF return!";
return ret;
}
header.clear();
state = StartHeaders;
break;
case StartHeaders:
// qCDebug(CUTELYST_MULTIPART) << "StartHeaders" << body->pos() - len + i;
if (buffer[i] == '\r') {
state = EndHeaders;
} else if (buffer[i] == '-') {
// qCDebug(CUTELYST_MULTIPART) << "StartHeaders return!";
return ret;
} else {
char *pch = strchr(buffer + i, '\r');
if (pch == NULL) {
header.append(buffer + i, len - i);
i = len;
} else {
header.append(buffer + i, pch - buffer - i);
i = pch - buffer;
state = FinishHeader;
}
}
break;
case FinishHeader:
// qCDebug(CUTELYST_MULTIPART) << "FinishHeader" << header;
if (buffer[i] == '\n') {
int dotdot = header.indexOf(':');
headers.setHeader(QString::fromLatin1(header.left(dotdot)),
QString::fromLatin1(header.mid(dotdot + 1).trimmed()));
header.clear();
state = StartHeaders;
} else {
// qCDebug(CUTELYST_MULTIPART) << "FinishHeader return!";
return ret;
}
break;
case EndHeaders:
// qCDebug(CUTELYST_MULTIPART) << "EndHeaders";
if (buffer[i] == '\n') {
state = StartData;
} else {
// qCDebug(CUTELYST_MULTIPART) << "EndHeaders return!";
return ret;
}
break;
case StartData:
// qCDebug(CUTELYST_MULTIPART) << "StartData" << body->pos() - len + i;
startOffset = body->pos() - len + i;
state = EndData;
case EndData:
i += findBoundary(buffer + i, len - i, state, boundaryPos);
if (state == EndBoundaryCR) {
// qCDebug(CUTELYST_MULTIPART) << "EndData" << body->pos() - len + i - boundaryLength - 1;
UploadPrivate *priv = new UploadPrivate(body);
priv->headers = headers;
headers.clear();
priv->startOffset = startOffset;
priv->endOffset = body->pos() - len + i - boundaryLength - 1;
ret << new Upload(priv);
}
}
++i;
}
}
return ret;
}
int MultiPartFormDataParserPrivate::findBoundary(char *buffer, int len, MultiPartFormDataParserPrivate::ParserState &state, int &boundaryPos)
{
int i = 0;
while (i < len) {
if (buffer[i] == boundary[boundaryPos]) {
if (++boundaryPos == boundaryLength) {
// qCDebug(CUTELYST_MULTIPART) << "FindBoundary:" << body->pos() - len + i;
boundaryPos = 0;
state = EndBoundaryCR;
return i;
}
} else {
boundaryPos = 0;
}
++i;
}
return i;
}
<|endoftext|> |
<commit_before>// Copyright Hugh Perkins 2015 hughperkins at gmail
//
// 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 <iostream>
#include <string>
#include <cstring>
#include <fstream>
#include <stdexcept>
#include "util/FileHelper.h"
#include "util/stringhelper.h"
#include "ManifestLoaderv1.h"
#include "util/JpegHelper.h"
#include "DeepCLDllExport.h"
using namespace std;
#undef STATIC
#undef VIRTUAL
#define STATIC
#define VIRTUAL
PUBLIC STATIC bool ManifestLoaderv1::isFormatFor(std::string imagesFilepath) {
cout << "ManifestLoaderv1 checking format for " << imagesFilepath << endl;
string sigString = "# format=deepcl-jpeg-list-v1 ";
char *headerBytes = FileHelper::readBinaryChunk(imagesFilepath, 0, sigString.length() + 1);
headerBytes[sigString.length()] = 0;
bool matched = string(headerBytes) == sigString;
cout << "matched: " << matched << endl;
return matched;
}
PUBLIC ManifestLoaderv1::ManifestLoaderv1(std::string imagesFilepath) {
init(imagesFilepath);
}
PRIVATE void ManifestLoaderv1::init(std::string imagesFilepath) {
this->imagesFilepath = imagesFilepath;
// by reading the number of lines in the manifest, we can get the number of examples, *p_N
// number of planes is .... 1
// imageSize is ...
if(!isFormatFor(imagesFilepath) ) {
throw runtime_error("file " + imagesFilepath + " is not a deepcl-jpeg-list-v1 manifest file");
}
ifstream infile(imagesFilepath);
char lineChars[1024];
infile.getline(lineChars, 1024); // skip first, header, line
string firstLine = string(lineChars);
// cout << "firstline: [" << firstLine << "]" << endl;
vector<string> splitLine = split(firstLine, " ");
N = readIntValue(splitLine, "N");
planes = readIntValue(splitLine, "planes");
size = readIntValue(splitLine, "width");
int imageSizeRepeated = readIntValue(splitLine, "height");
if(size != imageSizeRepeated) {
throw runtime_error("file " + imagesFilepath + " contains non-square images. Not handled for now.");
}
// now we should load into memory, since the file is not fixed-size records, and cannot be loaded partially easily
files = new string[N];
labels = 0;
int n = 0;
hasLabels = false;
while(infile) {
infile.getline(lineChars, 1024);
if(!infile) {
break;
}
string line = string(lineChars);
if(line == "") {
continue;
}
vector<string> splitLine = split(line, " ");
if((int)splitLine.size() == 0) {
continue;
}
if(n == 0) {
int lineSize = (int)splitLine.size();
if(lineSize == 2) {
hasLabels = true;
labels = new int[N];
}
}
if(!hasLabels && (int)splitLine.size() != 1) {
throw runtime_error("Error reading " + imagesFilepath + ". Following line not parseable:\n" + line);
}
if(hasLabels && (int)splitLine.size() != 2) {
throw runtime_error("Error reading " + imagesFilepath + ". Following line not parseable:\n" + line);
}
string jpegFile = splitLine[0];
#ifdef _WIN32
if(jpegFile[1] != ':' && jpegFile[0] != '\\') { // I guess this means its a relative path?
vector<string> splitManifestPath = split(imagesFilepath, "\\");
string dirPath = replace(imagesFilepath, splitManifestPath[splitManifestPath.size()-1], "");
jpegFile = dirPath + jpegFile;
}
#else
if(jpegFile[0] != '/') { // this is a bit hacky, but at least handles linux and mac for now...
vector<string> splitManifestPath = split(imagesFilepath, "/");
string dirPath = replace(imagesFilepath, splitManifestPath[splitManifestPath.size()-1], "");
jpegFile = dirPath + jpegFile;
}
#endif
files[n] = jpegFile;
if(hasLabels) {
int label = atoi(splitLine[1]);
labels[n] = label;
}
// cout << "file " << jpegFile << " label=" << label << endl;
n++;
}
infile.close();
if(n != N) {
throw runtime_error("Error: number of images declared in manifest " + to_string(N) + " doesnt match number actually in manifest " + to_string(n));
}
cout << "manifest " << imagesFilepath << " read. N=" << N << " planes=" << planes << " size=" << size << " labels? " << hasLabels << endl;
}
PUBLIC VIRTUAL std::string ManifestLoaderv1::getType() {
return "ManifestLoaderv1";
}
PUBLIC VIRTUAL int ManifestLoaderv1::getImageCubeSize() {
return planes * size * size;
}
PUBLIC VIRTUAL int ManifestLoaderv1::getN() {
return N;
}
PUBLIC VIRTUAL int ManifestLoaderv1::getPlanes() {
return planes;
}
PUBLIC VIRTUAL int ManifestLoaderv1::getImageSize() {
return size;
}
int ManifestLoaderv1::readIntValue(std::vector< std::string > splitLine, std::string key) {
for(int i = 0; i < (int)splitLine.size(); i++) {
vector<string> splitPair = split(splitLine[i], "=");
if((int)splitPair.size() == 2) {
if(splitPair[0] == key) {
return atoi(splitPair[1]);
}
}
}
throw runtime_error("Key " + key + " not found in file header");
}
PUBLIC VIRTUAL void ManifestLoaderv1::load(unsigned char *data, int *labels, int startRecord, int numRecords) {
int imageCubeSize = planes * size * size;
// cout << "ManifestLoaderv1, loading " << numRecords << " jpegs" << endl;
for(int localN = 0; localN < numRecords; localN++) {
int globalN = localN + startRecord;
if(globalN >= N) {
return;
}
JpegHelper::read(files[globalN], planes, size, size, data + localN * imageCubeSize);
if(labels != 0) {
if(!hasLabels) {
throw runtime_error("ManifestLoaderv1: labels reqested in load() method, but none found in file");
}
labels[localN] = this->labels[globalN];
}
}
}
<commit_msg>to_string => toString<commit_after>// Copyright Hugh Perkins 2015 hughperkins at gmail
//
// 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 <iostream>
#include <string>
#include <cstring>
#include <fstream>
#include <stdexcept>
#include "util/FileHelper.h"
#include "util/stringhelper.h"
#include "ManifestLoaderv1.h"
#include "util/JpegHelper.h"
#include "DeepCLDllExport.h"
using namespace std;
#undef STATIC
#undef VIRTUAL
#define STATIC
#define VIRTUAL
PUBLIC STATIC bool ManifestLoaderv1::isFormatFor(std::string imagesFilepath) {
cout << "ManifestLoaderv1 checking format for " << imagesFilepath << endl;
string sigString = "# format=deepcl-jpeg-list-v1 ";
char *headerBytes = FileHelper::readBinaryChunk(imagesFilepath, 0, sigString.length() + 1);
headerBytes[sigString.length()] = 0;
bool matched = string(headerBytes) == sigString;
cout << "matched: " << matched << endl;
return matched;
}
PUBLIC ManifestLoaderv1::ManifestLoaderv1(std::string imagesFilepath) {
init(imagesFilepath);
}
PRIVATE void ManifestLoaderv1::init(std::string imagesFilepath) {
this->imagesFilepath = imagesFilepath;
// by reading the number of lines in the manifest, we can get the number of examples, *p_N
// number of planes is .... 1
// imageSize is ...
if(!isFormatFor(imagesFilepath) ) {
throw runtime_error("file " + imagesFilepath + " is not a deepcl-jpeg-list-v1 manifest file");
}
ifstream infile(imagesFilepath);
char lineChars[1024];
infile.getline(lineChars, 1024); // skip first, header, line
string firstLine = string(lineChars);
// cout << "firstline: [" << firstLine << "]" << endl;
vector<string> splitLine = split(firstLine, " ");
N = readIntValue(splitLine, "N");
planes = readIntValue(splitLine, "planes");
size = readIntValue(splitLine, "width");
int imageSizeRepeated = readIntValue(splitLine, "height");
if(size != imageSizeRepeated) {
throw runtime_error("file " + imagesFilepath + " contains non-square images. Not handled for now.");
}
// now we should load into memory, since the file is not fixed-size records, and cannot be loaded partially easily
files = new string[N];
labels = 0;
int n = 0;
hasLabels = false;
while(infile) {
infile.getline(lineChars, 1024);
if(!infile) {
break;
}
string line = string(lineChars);
if(line == "") {
continue;
}
vector<string> splitLine = split(line, " ");
if((int)splitLine.size() == 0) {
continue;
}
if(n == 0) {
int lineSize = (int)splitLine.size();
if(lineSize == 2) {
hasLabels = true;
labels = new int[N];
}
}
if(!hasLabels && (int)splitLine.size() != 1) {
throw runtime_error("Error reading " + imagesFilepath + ". Following line not parseable:\n" + line);
}
if(hasLabels && (int)splitLine.size() != 2) {
throw runtime_error("Error reading " + imagesFilepath + ". Following line not parseable:\n" + line);
}
string jpegFile = splitLine[0];
#ifdef _WIN32
if(jpegFile[1] != ':' && jpegFile[0] != '\\') { // I guess this means its a relative path?
vector<string> splitManifestPath = split(imagesFilepath, "\\");
string dirPath = replace(imagesFilepath, splitManifestPath[splitManifestPath.size()-1], "");
jpegFile = dirPath + jpegFile;
}
#else
if(jpegFile[0] != '/') { // this is a bit hacky, but at least handles linux and mac for now...
vector<string> splitManifestPath = split(imagesFilepath, "/");
string dirPath = replace(imagesFilepath, splitManifestPath[splitManifestPath.size()-1], "");
jpegFile = dirPath + jpegFile;
}
#endif
files[n] = jpegFile;
if(hasLabels) {
int label = atoi(splitLine[1]);
labels[n] = label;
}
// cout << "file " << jpegFile << " label=" << label << endl;
n++;
}
infile.close();
if(n != N) {
throw runtime_error("Error: number of images declared in manifest " + toString(N) + " doesnt match number actually in manifest " + to_string(n));
}
cout << "manifest " << imagesFilepath << " read. N=" << N << " planes=" << planes << " size=" << size << " labels? " << hasLabels << endl;
}
PUBLIC VIRTUAL std::string ManifestLoaderv1::getType() {
return "ManifestLoaderv1";
}
PUBLIC VIRTUAL int ManifestLoaderv1::getImageCubeSize() {
return planes * size * size;
}
PUBLIC VIRTUAL int ManifestLoaderv1::getN() {
return N;
}
PUBLIC VIRTUAL int ManifestLoaderv1::getPlanes() {
return planes;
}
PUBLIC VIRTUAL int ManifestLoaderv1::getImageSize() {
return size;
}
int ManifestLoaderv1::readIntValue(std::vector< std::string > splitLine, std::string key) {
for(int i = 0; i < (int)splitLine.size(); i++) {
vector<string> splitPair = split(splitLine[i], "=");
if((int)splitPair.size() == 2) {
if(splitPair[0] == key) {
return atoi(splitPair[1]);
}
}
}
throw runtime_error("Key " + key + " not found in file header");
}
PUBLIC VIRTUAL void ManifestLoaderv1::load(unsigned char *data, int *labels, int startRecord, int numRecords) {
int imageCubeSize = planes * size * size;
// cout << "ManifestLoaderv1, loading " << numRecords << " jpegs" << endl;
for(int localN = 0; localN < numRecords; localN++) {
int globalN = localN + startRecord;
if(globalN >= N) {
return;
}
JpegHelper::read(files[globalN], planes, size, size, data + localN * imageCubeSize);
if(labels != 0) {
if(!hasLabels) {
throw runtime_error("ManifestLoaderv1: labels reqested in load() method, but none found in file");
}
labels[localN] = this->labels[globalN];
}
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2007,2008,2009 Red Hat, Inc.
*
* This is part of HarfBuzz, an OpenType Layout engine library.
*
* Permission is hereby granted, without written agreement and without
* license or royalty fees, to use, copy, modify, and distribute this
* software and its documentation for any purpose, provided that the
* above copyright notice and the following two paragraphs appear in
* all copies of this software.
*
* IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR
* DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
* ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
* IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*
* THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
* ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO
* PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*
* Red Hat Author(s): Behdad Esfahbod
*/
#ifndef HB_OPEN_FILE_PRIVATE_HH
#define HB_OPEN_FILE_PRIVATE_HH
#include "hb-open-type-private.hh"
/*
*
* The OpenType Font File
*
*/
/*
* Organization of an OpenType Font
*/
struct OpenTypeFontFile;
struct OffsetTable;
struct TTCHeader;
typedef struct TableDirectory
{
inline bool sanitize (SANITIZE_ARG_DEF, const void *base) {
SANITIZE_DEBUG ();
return SANITIZE_SELF () && SANITIZE (tag) &&
SANITIZE_MEM (CONST_CHARP(base) + (unsigned long) offset, length);
}
Tag tag; /* 4-byte identifier. */
CheckSum checkSum; /* CheckSum for this table. */
ULONG offset; /* Offset from beginning of TrueType font
* file. */
ULONG length; /* Length of this table. */
} OpenTypeTable;
ASSERT_SIZE (TableDirectory, 16);
typedef struct OffsetTable
{
friend struct OpenTypeFontFile;
friend struct TTCHeader;
STATIC_DEFINE_GET_FOR_DATA (OffsetTable);
DEFINE_TAG_ARRAY_INTERFACE (OpenTypeTable, table); /* get_table_count(), get_table(i), get_table_tag(i) */
DEFINE_TAG_FIND_INTERFACE (OpenTypeTable, table); /* find_table_index(tag), get_table_by_tag(tag) */
unsigned int get_face_count (void) const { return 1; }
private:
/* OpenTypeTables, in no particular order */
DEFINE_ARRAY_TYPE (TableDirectory, tableDir, numTables);
public:
inline bool sanitize (SANITIZE_ARG_DEF, const void *base) {
SANITIZE_DEBUG ();
if (!(SANITIZE_SELF () && SANITIZE_MEM (tableDir, sizeof (tableDir[0]) * numTables))) return false;
unsigned int count = numTables;
for (unsigned int i = 0; i < count; i++)
if (!SANITIZE_BASE (tableDir[i], base))
return false;
return true;
}
private:
Tag sfnt_version; /* '\0\001\0\00' if TrueType / 'OTTO' if CFF */
USHORT numTables; /* Number of tables. */
USHORT searchRange; /* (Maximum power of 2 <= numTables) x 16 */
USHORT entrySelector; /* Log2(maximum power of 2 <= numTables). */
USHORT rangeShift; /* NumTables x 16-searchRange. */
TableDirectory tableDir[]; /* TableDirectory entries. numTables items */
} OpenTypeFontFace;
ASSERT_SIZE (OffsetTable, 12);
/*
* TrueType Collections
*/
struct TTCHeader
{
friend struct OpenTypeFontFile;
STATIC_DEFINE_GET_FOR_DATA_CHECK_MAJOR_VERSION (TTCHeader, 1, 2);
unsigned int get_face_count (void) const { return table.len; }
const OpenTypeFontFace& get_face (unsigned int i) const
{
return this+table[i];
}
bool sanitize (SANITIZE_ARG_DEF) {
SANITIZE_DEBUG ();
if (!SANITIZE (version)) return false;
if (version.major < 1 || version.major > 2) return true;
/* XXX Maybe we shouldn't NEUTER these offsets, they may cause a full copy of
* the whole font right now. */
return table.sanitize (SANITIZE_ARG, CONST_CHARP(this), CONST_CHARP(this));
}
private:
Tag ttcTag; /* TrueType Collection ID string: 'ttcf' */
FixedVersion version; /* Version of the TTC Header (1.0 or 2.0),
* 0x00010000 or 0x00020000 */
LongOffsetLongArrayOf<OffsetTable>
table; /* Array of offsets to the OffsetTable for each font
* from the beginning of the file */
};
ASSERT_SIZE (TTCHeader, 12);
/*
* OpenType Font File
*/
struct OpenTypeFontFile
{
static const hb_tag_t TrueTypeTag = HB_TAG ( 0 , 1 , 0 , 0 );
static const hb_tag_t CFFTag = HB_TAG ('O','T','T','O');
static const hb_tag_t TTCTag = HB_TAG ('t','t','c','f');
STATIC_DEFINE_GET_FOR_DATA (OpenTypeFontFile);
unsigned int get_face_count (void) const
{
switch (tag) {
default: return 0;
case TrueTypeTag: case CFFTag: return OffsetTable::get_for_data (CONST_CHARP(this)).get_face_count ();
case TTCTag: return TTCHeader::get_for_data (CONST_CHARP(this)).get_face_count ();
}
}
const OpenTypeFontFace& get_face (unsigned int i) const
{
switch (tag) {
default: return Null(OpenTypeFontFace);
/* Note: for non-collection SFNT data we ignore index. This is because
* Apple dfont container is a container of SFNT's. So each SFNT is a
* non-TTC, but the index is more than zero. */
case TrueTypeTag: case CFFTag: return OffsetTable::get_for_data (CONST_CHARP(this));
case TTCTag: return TTCHeader::get_for_data (CONST_CHARP(this)).get_face (i);
}
}
/* This is how you get a table */
inline const char* get_table_data (const OpenTypeTable& table) const
{
if (HB_UNLIKELY (table.offset == 0)) return NULL;
return ((const char*) this) + table.offset;
}
bool sanitize (SANITIZE_ARG_DEF) {
SANITIZE_DEBUG ();
if (!SANITIZE_SELF ()) return false;
switch (tag) {
default: return true;
case TrueTypeTag: case CFFTag: return SANITIZE_THIS (CAST (OffsetTable, *this, 0));
case TTCTag: return SANITIZE (CAST (TTCHeader, *this, 0));
}
}
Tag tag; /* 4-byte identifier. */
};
ASSERT_SIZE (OpenTypeFontFile, 4);
#endif /* HB_OPEN_FILE_PRIVATE_HH */
<commit_msg>[HB] Rebrand XXX as TODO<commit_after>/*
* Copyright (C) 2007,2008,2009 Red Hat, Inc.
*
* This is part of HarfBuzz, an OpenType Layout engine library.
*
* Permission is hereby granted, without written agreement and without
* license or royalty fees, to use, copy, modify, and distribute this
* software and its documentation for any purpose, provided that the
* above copyright notice and the following two paragraphs appear in
* all copies of this software.
*
* IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR
* DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
* ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
* IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*
* THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
* ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO
* PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*
* Red Hat Author(s): Behdad Esfahbod
*/
#ifndef HB_OPEN_FILE_PRIVATE_HH
#define HB_OPEN_FILE_PRIVATE_HH
#include "hb-open-type-private.hh"
/*
*
* The OpenType Font File
*
*/
/*
* Organization of an OpenType Font
*/
struct OpenTypeFontFile;
struct OffsetTable;
struct TTCHeader;
typedef struct TableDirectory
{
inline bool sanitize (SANITIZE_ARG_DEF, const void *base) {
SANITIZE_DEBUG ();
return SANITIZE_SELF () && SANITIZE (tag) &&
SANITIZE_MEM (CONST_CHARP(base) + (unsigned long) offset, length);
}
Tag tag; /* 4-byte identifier. */
CheckSum checkSum; /* CheckSum for this table. */
ULONG offset; /* Offset from beginning of TrueType font
* file. */
ULONG length; /* Length of this table. */
} OpenTypeTable;
ASSERT_SIZE (TableDirectory, 16);
typedef struct OffsetTable
{
friend struct OpenTypeFontFile;
friend struct TTCHeader;
STATIC_DEFINE_GET_FOR_DATA (OffsetTable);
DEFINE_TAG_ARRAY_INTERFACE (OpenTypeTable, table); /* get_table_count(), get_table(i), get_table_tag(i) */
DEFINE_TAG_FIND_INTERFACE (OpenTypeTable, table); /* find_table_index(tag), get_table_by_tag(tag) */
unsigned int get_face_count (void) const { return 1; }
private:
/* OpenTypeTables, in no particular order */
DEFINE_ARRAY_TYPE (TableDirectory, tableDir, numTables);
public:
inline bool sanitize (SANITIZE_ARG_DEF, const void *base) {
SANITIZE_DEBUG ();
if (!(SANITIZE_SELF () && SANITIZE_MEM (tableDir, sizeof (tableDir[0]) * numTables))) return false;
unsigned int count = numTables;
for (unsigned int i = 0; i < count; i++)
if (!SANITIZE_BASE (tableDir[i], base))
return false;
return true;
}
private:
Tag sfnt_version; /* '\0\001\0\00' if TrueType / 'OTTO' if CFF */
USHORT numTables; /* Number of tables. */
USHORT searchRange; /* (Maximum power of 2 <= numTables) x 16 */
USHORT entrySelector; /* Log2(maximum power of 2 <= numTables). */
USHORT rangeShift; /* NumTables x 16-searchRange. */
TableDirectory tableDir[]; /* TableDirectory entries. numTables items */
} OpenTypeFontFace;
ASSERT_SIZE (OffsetTable, 12);
/*
* TrueType Collections
*/
struct TTCHeader
{
friend struct OpenTypeFontFile;
STATIC_DEFINE_GET_FOR_DATA_CHECK_MAJOR_VERSION (TTCHeader, 1, 2);
unsigned int get_face_count (void) const { return table.len; }
const OpenTypeFontFace& get_face (unsigned int i) const
{
return this+table[i];
}
bool sanitize (SANITIZE_ARG_DEF) {
SANITIZE_DEBUG ();
if (!SANITIZE (version)) return false;
if (version.major < 1 || version.major > 2) return true;
/* TODO Maybe we shouldn't NEUTER these offsets, they may cause a full copy
* of the whole font right now. */
return table.sanitize (SANITIZE_ARG, CONST_CHARP(this), CONST_CHARP(this));
}
private:
Tag ttcTag; /* TrueType Collection ID string: 'ttcf' */
FixedVersion version; /* Version of the TTC Header (1.0 or 2.0),
* 0x00010000 or 0x00020000 */
LongOffsetLongArrayOf<OffsetTable>
table; /* Array of offsets to the OffsetTable for each font
* from the beginning of the file */
};
ASSERT_SIZE (TTCHeader, 12);
/*
* OpenType Font File
*/
struct OpenTypeFontFile
{
static const hb_tag_t TrueTypeTag = HB_TAG ( 0 , 1 , 0 , 0 );
static const hb_tag_t CFFTag = HB_TAG ('O','T','T','O');
static const hb_tag_t TTCTag = HB_TAG ('t','t','c','f');
STATIC_DEFINE_GET_FOR_DATA (OpenTypeFontFile);
unsigned int get_face_count (void) const
{
switch (tag) {
default: return 0;
case TrueTypeTag: case CFFTag: return OffsetTable::get_for_data (CONST_CHARP(this)).get_face_count ();
case TTCTag: return TTCHeader::get_for_data (CONST_CHARP(this)).get_face_count ();
}
}
const OpenTypeFontFace& get_face (unsigned int i) const
{
switch (tag) {
default: return Null(OpenTypeFontFace);
/* Note: for non-collection SFNT data we ignore index. This is because
* Apple dfont container is a container of SFNT's. So each SFNT is a
* non-TTC, but the index is more than zero. */
case TrueTypeTag: case CFFTag: return OffsetTable::get_for_data (CONST_CHARP(this));
case TTCTag: return TTCHeader::get_for_data (CONST_CHARP(this)).get_face (i);
}
}
/* This is how you get a table */
inline const char* get_table_data (const OpenTypeTable& table) const
{
if (HB_UNLIKELY (table.offset == 0)) return NULL;
return ((const char*) this) + table.offset;
}
bool sanitize (SANITIZE_ARG_DEF) {
SANITIZE_DEBUG ();
if (!SANITIZE_SELF ()) return false;
switch (tag) {
default: return true;
case TrueTypeTag: case CFFTag: return SANITIZE_THIS (CAST (OffsetTable, *this, 0));
case TTCTag: return SANITIZE (CAST (TTCHeader, *this, 0));
}
}
Tag tag; /* 4-byte identifier. */
};
ASSERT_SIZE (OpenTypeFontFile, 4);
#endif /* HB_OPEN_FILE_PRIVATE_HH */
<|endoftext|> |
<commit_before>// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#include "platform/globals.h"
#if defined(TARGET_OS_FUCHSIA)
#include "bin/crypto.h"
#include <magenta/syscalls.h>
namespace dart {
namespace bin {
bool Crypto::GetRandomBytes(intptr_t count, uint8_t* buffer) {
intptr_t read = 0;
while (read < count) {
const intptr_t remaining = count - read;
const intptr_t len =
(MX_CPRNG_DRAW_MAX_LEN < remaining) ? MX_CPRNG_DRAW_MAX_LEN
: remaining;
const mx_ssize_t res = mx_cprng_draw(buffer + read, len);
if (res == ERR_INVALID_ARGS) {
return false;
}
read += res;
}
return true;
}
} // namespace bin
} // namespace dart
#endif // defined(TARGET_OS_FUCHSIA)
<commit_msg>Use the new argument ordering for mx_cprng_draw<commit_after>// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#include "platform/globals.h"
#if defined(TARGET_OS_FUCHSIA)
#include "bin/crypto.h"
#include <magenta/syscalls.h>
namespace dart {
namespace bin {
bool Crypto::GetRandomBytes(intptr_t count, uint8_t* buffer) {
intptr_t read = 0;
while (read < count) {
const intptr_t remaining = count - read;
const intptr_t len =
(MX_CPRNG_DRAW_MAX_LEN < remaining) ? MX_CPRNG_DRAW_MAX_LEN
: remaining;
mx_size_t res = 0;
const mx_status_t status = mx_cprng_draw(buffer + read, len, &res);
if (status != NO_ERROR) {
return false;
}
read += res;
}
return true;
}
} // namespace bin
} // namespace dart
#endif // defined(TARGET_OS_FUCHSIA)
<|endoftext|> |
<commit_before>/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include "kernel/yosys.h"
#include "kernel/sigtools.h"
USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN
struct PortlistPass : public Pass {
PortlistPass() : Pass("portlist", "list (top-level) ports") { }
void help() YS_OVERRIDE
{
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" portlist [options] [selection]\n");
log("\n");
log("This command lists all module ports found in the selected modules.\n");
log("\n");
log("If no selection is provided then it lists the ports on the top module.\n");
log("\n");
}
void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
{
size_t argidx;
for (argidx = 1; argidx < args.size(); argidx++) {
// if (args[argidx] == "-ltr") {
// config.ltr = true;
// continue;
// }
break;
}
auto handle_module = [&](RTLIL::Module *module) {
for (auto port : module->ports) {
auto *w = module->wire(port);
log("%s [%d:%d] %s\n", w->port_input ? w->port_output ? "inout" : "input" : "output",
w->upto ? w->start_offset : w->start_offset + w->width - 1,
w->upto ? w->start_offset + w->width - 1 : w->start_offset,
log_id(w));
}
};
if (argidx == args.size())
{
auto *top = design->top_module();
if (top == nullptr)
log_error("Can't find top module in current design!\n");
handle_module(top);
}
else
{
extra_args(args, argidx, design);
for (auto module : design->selected_modules())
handle_module(module);
}
}
} PortlistPass;
PRIVATE_NAMESPACE_END
<commit_msg>Improve "portlist" command<commit_after>/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include "kernel/yosys.h"
#include "kernel/sigtools.h"
USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN
struct PortlistPass : public Pass {
PortlistPass() : Pass("portlist", "list (top-level) ports") { }
void help() YS_OVERRIDE
{
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" portlist [options] [selection]\n");
log("\n");
log("This command lists all module ports found in the selected modules.\n");
log("\n");
log("If no selection is provided then it lists the ports on the top module.\n");
log("\n");
log(" -m\n");
log(" print verilog blackbox module definitions instead of port lists\n");
log("\n");
}
void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
{
bool m_mode = false;
size_t argidx;
for (argidx = 1; argidx < args.size(); argidx++) {
if (args[argidx] == "-m") {
m_mode = true;
continue;
}
break;
}
bool first_module = true;
auto handle_module = [&](RTLIL::Module *module) {
vector<string> ports;
if (first_module)
first_module = false;
else
log("\n");
for (auto port : module->ports) {
auto *w = module->wire(port);
ports.push_back(stringf("%s [%d:%d] %s", w->port_input ? w->port_output ? "inout" : "input" : "output",
w->upto ? w->start_offset : w->start_offset + w->width - 1,
w->upto ? w->start_offset + w->width - 1 : w->start_offset,
log_id(w)));
}
log("module %s%s\n", log_id(module), m_mode ? " (" : "");
for (int i = 0; i < GetSize(ports); i++)
log("%s%s\n", ports[i].c_str(), m_mode && i+1 < GetSize(ports) ? "," : "");
if (m_mode)
log(");\nendmodule\n");
};
if (argidx == args.size())
{
auto *top = design->top_module();
if (top == nullptr)
log_cmd_error("Can't find top module in current design!\n");
handle_module(top);
}
else
{
extra_args(args, argidx, design);
for (auto module : design->selected_modules())
handle_module(module);
}
}
} PortlistPass;
PRIVATE_NAMESPACE_END
<|endoftext|> |
<commit_before>/**
* This file is part of the "FnordMetric" project
* Copyright (c) 2014 Paul Asmuth, Google Inc.
*
* FnordMetric is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License v3.0. 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 <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <unistd.h>
#include "fnord-base/exception.h"
#include "fnord-base/inspect.h"
#include "fnord-base/net/tcpserver.h"
namespace fnord {
namespace net {
TCPServer::TCPServer(
TaskScheduler* scheduler) :
scheduler_(scheduler),
on_connection_cb_(nullptr) {}
void TCPServer::onConnection(
std::function<void (std::unique_ptr<TCPConnection>)> callback) {
on_connection_cb_ = callback;
}
void TCPServer::accept() {
int conn_fd = ::accept(ssock_, NULL, NULL);
if (conn_fd < 0) {
RAISE_ERRNO(kIOError, "accept() failed");
}
if (on_connection_cb_) {
scheduler_->run([this, conn_fd] () {
on_connection_cb_(
std::unique_ptr<TCPConnection>(new TCPConnection(conn_fd)));
});
}
scheduler_->runOnReadable(std::bind(&TCPServer::accept, this), ssock_);
}
void TCPServer::listen(int port) {
ssock_ = socket(AF_INET, SOCK_STREAM, 0);
if (ssock_ == 0) {
RAISE_ERRNO(kIOError, "create socket() failed");
}
int opt = 1;
if (setsockopt(ssock_, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) < 0) {
RAISE_ERRNO(kIOError, "setsockopt(SO_REUSEADDR) failed");
return;
}
int flags = fcntl(ssock_, F_GETFL, 0);
flags = flags | O_NONBLOCK;
if (fcntl(ssock_, F_SETFL, flags) != 0) {
RAISE_ERRNO(kIOError, "fnctl(%i) failed", ssock_);
}
struct sockaddr_in addr;
memset((char *) &addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port = htons(port);
if (::bind(ssock_, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
RAISE_ERRNO(kIOError, "bind() failed");
}
if (::listen(ssock_, 1024) == -1) {
RAISE_ERRNO(kIOError, "listen() failed");
}
scheduler_->runOnReadable(std::bind(&TCPServer::accept, this), ssock_);
}
}
}
<commit_msg>allow SO_REUSEPORT<commit_after>/**
* This file is part of the "FnordMetric" project
* Copyright (c) 2014 Paul Asmuth, Google Inc.
*
* FnordMetric is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License v3.0. 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 <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <unistd.h>
#include "fnord-base/exception.h"
#include "fnord-base/inspect.h"
#include "fnord-base/net/tcpserver.h"
namespace fnord {
namespace net {
TCPServer::TCPServer(
TaskScheduler* scheduler) :
scheduler_(scheduler),
on_connection_cb_(nullptr) {}
void TCPServer::onConnection(
std::function<void (std::unique_ptr<TCPConnection>)> callback) {
on_connection_cb_ = callback;
}
void TCPServer::accept() {
int conn_fd = ::accept(ssock_, NULL, NULL);
if (conn_fd < 0) {
RAISE_ERRNO(kIOError, "accept() failed");
}
if (on_connection_cb_) {
scheduler_->run([this, conn_fd] () {
on_connection_cb_(
std::unique_ptr<TCPConnection>(new TCPConnection(conn_fd)));
});
}
scheduler_->runOnReadable(std::bind(&TCPServer::accept, this), ssock_);
}
void TCPServer::listen(int port) {
ssock_ = socket(AF_INET, SOCK_STREAM, 0);
if (ssock_ == 0) {
RAISE_ERRNO(kIOError, "create socket() failed");
}
int opt = 1;
if (setsockopt(ssock_, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) < 0) {
RAISE_ERRNO(kIOError, "setsockopt(SO_REUSEADDR) failed");
return;
}
opt = 1;
if (setsockopt(ssock_, SOL_SOCKET, SO_REUSEPORT, &opt, sizeof(opt)) < 0) {
RAISE_ERRNO(kIOError, "setsockopt(SO_REUSEPORT) failed");
return;
}
int flags = fcntl(ssock_, F_GETFL, 0);
flags = flags | O_NONBLOCK;
if (fcntl(ssock_, F_SETFL, flags) != 0) {
RAISE_ERRNO(kIOError, "fnctl(%i) failed", ssock_);
}
struct sockaddr_in addr;
memset((char *) &addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port = htons(port);
if (::bind(ssock_, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
RAISE_ERRNO(kIOError, "bind() failed");
}
if (::listen(ssock_, 1024) == -1) {
RAISE_ERRNO(kIOError, "listen() failed");
}
scheduler_->runOnReadable(std::bind(&TCPServer::accept, this), ssock_);
}
}
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** If you have questions regarding the use of this file, please
** contact Nokia at http://www.qtsoftware.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qcontactabstractrequest.h"
#include "qcontactabstractrequest_p.h"
#include "qcontactmanager.h"
#include "qcontactmanager_p.h"
#include "qcontactmanagerengine.h"
QContactAbstractRequest::QContactAbstractRequest(QContactAbstractRequestPrivate* otherd)
: d_ptr(otherd)
{
}
QContactAbstractRequest::~QContactAbstractRequest()
{
// manager->engine->destroyRequest(this) ?
}
bool QContactAbstractRequest::isActive() const
{
return (d_ptr->m_status == QContactAbstractRequest::Active
|| d_ptr->m_status == QContactAbstractRequest::Cancelling);
}
bool QContactAbstractRequest::isFinished() const
{
return (d_ptr->m_status == QContactAbstractRequest::Finished
|| d_ptr->m_status == QContactAbstractRequest::Cancelled);
}
QContactManager::Error QContactAbstractRequest::error() const
{
return d_ptr->m_error;
}
QContactAbstractRequest::Status QContactAbstractRequest::status() const
{
return d_ptr->m_status;
}
QContactManager* QContactAbstractRequest::manager() const
{
return d_ptr->m_manager;
}
void QContactAbstractRequest::setManager(QContactManager* manager)
{
d_ptr->m_manager = manager;
}
bool QContactAbstractRequest::start()
{
if (status() != QContactAbstractRequest::Inactive
&& status() != QContactAbstractRequest::Cancelled
&& status() != QContactAbstractRequest::Finished) {
return false; // unable to start operation; another operation already in progress.
}
QContactManagerEngine *engine = QContactManagerData::engine(d_ptr->m_manager);
if (engine)
engine->startRequest(this);
return true;
}
bool QContactAbstractRequest::cancel()
{
if (status() != QContactAbstractRequest::Active) {
return false; // unable to cancel operation; operation not in progress.
}
QContactManagerEngine *engine = QContactManagerData::engine(d_ptr->m_manager);
if (engine)
engine->cancelRequest(this);
return true;
}
bool QContactAbstractRequest::waitForFinished(int msecs)
{
if (status() != QContactAbstractRequest::Active) {
return false; // unable to wait for operation; not in progress.
}
QContactManagerEngine *engine = QContactManagerData::engine(d_ptr->m_manager);
if (engine)
return engine->waitForRequestFinished(this, msecs);
return false;
}
bool QContactAbstractRequest::waitForProgress(int msecs)
{
if (status() != QContactAbstractRequest::Active) {
return false; // unable to wait for operation; not in progress.
}
QContactManagerEngine *engine = QContactManagerData::engine(d_ptr->m_manager);
if (engine)
return engine->waitForRequestProgress(this, msecs);
return false;
}
<commit_msg>Inform the engine of request destruction when required<commit_after>/****************************************************************************
**
** Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** If you have questions regarding the use of this file, please
** contact Nokia at http://www.qtsoftware.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qcontactabstractrequest.h"
#include "qcontactabstractrequest_p.h"
#include "qcontactmanager.h"
#include "qcontactmanager_p.h"
#include "qcontactmanagerengine.h"
QContactAbstractRequest::QContactAbstractRequest(QContactAbstractRequestPrivate* otherd)
: d_ptr(otherd)
{
}
QContactAbstractRequest::~QContactAbstractRequest()
{
QContactManagerEngine *engine = QContactManagerData::engine(d_ptr->m_manager);
if (engine)
engine->requestDestroyed(this);
}
bool QContactAbstractRequest::isActive() const
{
return (d_ptr->m_status == QContactAbstractRequest::Active
|| d_ptr->m_status == QContactAbstractRequest::Cancelling);
}
bool QContactAbstractRequest::isFinished() const
{
return (d_ptr->m_status == QContactAbstractRequest::Finished
|| d_ptr->m_status == QContactAbstractRequest::Cancelled);
}
QContactManager::Error QContactAbstractRequest::error() const
{
return d_ptr->m_error;
}
QContactAbstractRequest::Status QContactAbstractRequest::status() const
{
return d_ptr->m_status;
}
QContactManager* QContactAbstractRequest::manager() const
{
return d_ptr->m_manager;
}
void QContactAbstractRequest::setManager(QContactManager* manager)
{
d_ptr->m_manager = manager;
}
bool QContactAbstractRequest::start()
{
if (status() != QContactAbstractRequest::Inactive
&& status() != QContactAbstractRequest::Cancelled
&& status() != QContactAbstractRequest::Finished) {
return false; // unable to start operation; another operation already in progress.
}
QContactManagerEngine *engine = QContactManagerData::engine(d_ptr->m_manager);
if (engine)
engine->startRequest(this);
return true;
}
bool QContactAbstractRequest::cancel()
{
if (status() != QContactAbstractRequest::Active) {
return false; // unable to cancel operation; operation not in progress.
}
QContactManagerEngine *engine = QContactManagerData::engine(d_ptr->m_manager);
if (engine)
engine->cancelRequest(this);
return true;
}
bool QContactAbstractRequest::waitForFinished(int msecs)
{
if (status() != QContactAbstractRequest::Active) {
return false; // unable to wait for operation; not in progress.
}
QContactManagerEngine *engine = QContactManagerData::engine(d_ptr->m_manager);
if (engine)
return engine->waitForRequestFinished(this, msecs);
return false;
}
bool QContactAbstractRequest::waitForProgress(int msecs)
{
if (status() != QContactAbstractRequest::Active) {
return false; // unable to wait for operation; not in progress.
}
QContactManagerEngine *engine = QContactManagerData::engine(d_ptr->m_manager);
if (engine)
return engine->waitForRequestProgress(this, msecs);
return false;
}
<|endoftext|> |
<commit_before>/* libwpd2
* Copyright (C) 2002 William Lachance (william.lachance@sympatico.ca)
* Copyright (C) 2002 Marc Maurer (j.m.maurer@student.utwente.nl)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* For further information visit http://libwpd.sourceforge.net
*/
/* "This product is not manufactured, approved, or supported by
* Corel Corporation or Corel Corporation Limited."
*/
#include "libwpd.h"
#include "WP60Header.h"
#include "WP6FileStructure.h"
#include "libwpd_internal.h"
WP60Header::WP60Header(GsfInput * input)
: WP6Header(input)
{
guint16 documentEncrypted;
WPD_CHECK_FILE_SEEK_ERROR(gsf_input_seek(input, WP6_HEADER_ENCRYPTION_OFFSET, G_SEEK_SET));
m_documentEncryption = *(const guint16 *)gsf_input_read(input, sizeof(guint16), NULL);
WPD_CHECK_FILE_SEEK_ERROR(gsf_input_seek(input, WP6_HEADER_INDEX_HEADER_POINTER_OFFSET, G_SEEK_SET));
guint16 m_indexHeaderOffset = *(const guint16 *)gsf_input_read(input, sizeof(guint16), NULL);
// according to the WP6.0 specs, if the index header offset variable is less than 16, it is 16
if (m_indexHeaderOffset < 16)
m_indexHeaderOffset = 16;
WPD_DEBUG_MSG(("WordPerfect: Index Header Position = 0x%x (%i)\n",(int)m_indexHeaderOffset));
WPD_DEBUG_MSG(("WordPerfect: Document Encryption = 0x%x \n",(int)m_documentEncryption));
// TODO:
/* we do not handle encrypted documents */
/*if (m_documentEncryption != 0)
return FALSE;*/
/* sanity check */
/*if (documentOffset > m_iDocumentSize)
return FALSE;*/
// read the Index Header (Header #0)
// skip the Flags = 2 and the Reserved byte = 0
guint16 numIndices;
WPD_CHECK_FILE_SEEK_ERROR(gsf_input_seek(input, m_indexHeaderOffset + WP6_INDEX_HEADER_NUM_INDICES_POSITION, G_SEEK_SET));
m_numPrefixIndices = *(const guint16 *)gsf_input_read(input, sizeof(guint16), NULL);
// ignore the 10 reserved bytes that follow (jump to the offset of the Index Header #1, where we can resume parsing)
WPD_CHECK_FILE_SEEK_ERROR(gsf_input_seek(input, m_indexHeaderOffset + WP6_INDEX_HEADER_INDICES_POSITION, G_SEEK_SET));
}
WP60Header::~WP60Header()
{
}
<commit_msg>fix remnant of a type<commit_after>/* libwpd2
* Copyright (C) 2002 William Lachance (william.lachance@sympatico.ca)
* Copyright (C) 2002 Marc Maurer (j.m.maurer@student.utwente.nl)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* For further information visit http://libwpd.sourceforge.net
*/
/* "This product is not manufactured, approved, or supported by
* Corel Corporation or Corel Corporation Limited."
*/
#include "libwpd.h"
#include "WP60Header.h"
#include "WP6FileStructure.h"
#include "libwpd_internal.h"
WP60Header::WP60Header(GsfInput * input)
: WP6Header(input)
{
guint16 documentEncrypted;
WPD_CHECK_FILE_SEEK_ERROR(gsf_input_seek(input, WP6_HEADER_ENCRYPTION_OFFSET, G_SEEK_SET));
m_documentEncryption = *(const guint16 *)gsf_input_read(input, sizeof(guint16), NULL);
WPD_CHECK_FILE_SEEK_ERROR(gsf_input_seek(input, WP6_HEADER_INDEX_HEADER_POINTER_OFFSET, G_SEEK_SET));
m_indexHeaderOffset = *(const guint16 *)gsf_input_read(input, sizeof(guint16), NULL);
// according to the WP6.0 specs, if the index header offset variable is less than 16, it is 16
if (m_indexHeaderOffset < 16)
m_indexHeaderOffset = 16;
WPD_DEBUG_MSG(("WordPerfect: Index Header Position = 0x%x (%i)\n",(int)m_indexHeaderOffset));
WPD_DEBUG_MSG(("WordPerfect: Document Encryption = 0x%x \n",(int)m_documentEncryption));
// TODO:
/* we do not handle encrypted documents */
/*if (m_documentEncryption != 0)
return FALSE;*/
/* sanity check */
/*if (documentOffset > m_iDocumentSize)
return FALSE;*/
// read the Index Header (Header #0)
// skip the Flags = 2 and the Reserved byte = 0
guint16 numIndices;
WPD_CHECK_FILE_SEEK_ERROR(gsf_input_seek(input, m_indexHeaderOffset + WP6_INDEX_HEADER_NUM_INDICES_POSITION, G_SEEK_SET));
m_numPrefixIndices = *(const guint16 *)gsf_input_read(input, sizeof(guint16), NULL);
// ignore the 10 reserved bytes that follow (jump to the offset of the Index Header #1, where we can resume parsing)
WPD_CHECK_FILE_SEEK_ERROR(gsf_input_seek(input, m_indexHeaderOffset + WP6_INDEX_HEADER_INDICES_POSITION, G_SEEK_SET));
}
WP60Header::~WP60Header()
{
}
<|endoftext|> |
<commit_before>#include "../Positive_Matrix_With_Prefactor.hxx"
#include "../Boost_Float.hxx"
#include "../../Timers.hxx"
#include "../../sdp_convert.hxx"
#include <boost/filesystem.hpp>
#include <algorithm>
std::vector<Polynomial> bilinear_basis(const Damped_Rational &damped_rational,
const size_t &half_max_degree);
std::vector<Boost_Float> sample_points(const size_t &num_points);
void write_output(const boost::filesystem::path &output_dir,
const std::vector<El::BigFloat> &objectives,
const std::vector<El::BigFloat> &normalization,
const std::vector<Positive_Matrix_With_Prefactor> &matrices,
Timers &timers)
{
auto &objectives_timer(timers.add_and_start("write_output.objectives"));
auto max_normalization(
std::max_element(normalization.begin(), normalization.end()));
size_t max_index(std::distance(normalization.begin(), max_normalization));
El::BigFloat objective_const(objectives.at(max_index)
/ normalization.at(max_index));
std::vector<El::BigFloat> dual_objective_b;
dual_objective_b.reserve(normalization.size() - 1);
for(size_t index = 0; index < normalization.size(); ++index)
{
if(index != max_index)
{
dual_objective_b.push_back(
objectives.at(index) - normalization.at(index) * objective_const);
}
}
objectives_timer.stop();
auto &matrices_timer(timers.add_and_start("write_output.matrices"));
std::vector<Dual_Constraint_Group> dual_constraint_groups;
int rank(El::mpi::Rank(El::mpi::COMM_WORLD)),
num_procs(El::mpi::Size(El::mpi::COMM_WORLD));
std::vector<size_t> indices;
for(size_t index = rank; index < matrices.size(); index += num_procs)
{
indices.push_back(index);
}
for(auto &index : indices)
{
auto &scalings_timer(timers.add_and_start(
"write_output.matrices.scalings_" + std::to_string(index)));
const size_t max_degree([&]() {
int64_t result(0);
for(auto &pvv : matrices[index].polynomials)
for(auto &pv : pvv)
for(auto &polynomial : pv)
{
result = std::max(result, polynomial.degree());
}
return result;
}());
std::vector<Boost_Float> points(sample_points(max_degree + 1)),
sample_scalings;
sample_scalings.reserve(points.size());
for(auto &point : points)
{
Boost_Float numerator(
matrices[index].damped_rational.constant
* pow(matrices[index].damped_rational.base, point));
Boost_Float denominator(1);
for(auto &pole : matrices[index].damped_rational.poles)
{
denominator *= (point - pole);
}
sample_scalings.push_back(numerator / denominator);
}
scalings_timer.stop();
Polynomial_Vector_Matrix pvm;
pvm.rows = matrices[index].polynomials.size();
pvm.cols = matrices[index].polynomials.front().size();
auto &bilinear_basis_timer(timers.add_and_start(
"write_output.matrices.bilinear_basis_" + std::to_string(index)));
pvm.bilinear_basis
= bilinear_basis(matrices[index].damped_rational, max_degree / 2);
bilinear_basis_timer.stop();
pvm.sample_points.reserve(points.size());
for(auto &point : points)
{
pvm.sample_points.emplace_back(to_string(point));
}
pvm.sample_scalings.reserve(sample_scalings.size());
for(auto &scaling : sample_scalings)
{
pvm.sample_scalings.emplace_back(to_string(scaling));
}
auto &pvm_timer(timers.add_and_start("write_output.matrices.pvm_"
+ std::to_string(index)));
pvm.elements.reserve(pvm.rows * pvm.cols);
for(auto &pvv : matrices[index].polynomials)
for(auto &pv : pvv)
{
pvm.elements.emplace_back();
auto &pvm_polynomials(pvm.elements.back());
pvm_polynomials.reserve(pv.size());
pvm_polynomials.push_back(pv.at(max_index)
/ normalization.at(max_index));
auto &pvm_constant(pvm_polynomials.back());
for(size_t index = 0; index < normalization.size(); ++index)
{
if(index != max_index)
{
pvm_polynomials.emplace_back(0, 0);
auto &pvm_poly(pvm_polynomials.back());
pvm_poly.coefficients.reserve(pv.at(index).degree() + 1);
size_t coefficient(0);
for(; coefficient < pv.at(index).coefficients.size()
&& coefficient < pvm_constant.coefficients.size();
++coefficient)
{
pvm_poly.coefficients.push_back(
pv.at(index).coefficients[coefficient]
- normalization.at(index)
* pvm_constant.coefficients[coefficient]);
}
for(; coefficient < pv.at(index).coefficients.size();
++coefficient)
{
pvm_poly.coefficients.push_back(
pv.at(index).coefficients[coefficient]);
}
for(; coefficient < pvm_constant.coefficients.size();
++coefficient)
{
pvm_poly.coefficients.push_back(
-normalization.at(index)
* pvm_polynomials.at(0).coefficients[coefficient]);
}
}
}
}
pvm_timer.stop();
auto &dual_constraint_timer(timers.add_and_start(
"write_output.matrices.dual_constraint_" + std::to_string(index)));
dual_constraint_groups.emplace_back(pvm);
dual_constraint_timer.stop();
}
matrices_timer.stop();
auto &write_timer(timers.add_and_start("write_output.write"));
write_sdpb_input_files(output_dir, rank, num_procs, indices, objective_const,
dual_objective_b, dual_constraint_groups);
write_timer.stop();
}
<commit_msg>Fix normalization in sdp2input<commit_after>#include "../Positive_Matrix_With_Prefactor.hxx"
#include "../Boost_Float.hxx"
#include "../../Timers.hxx"
#include "../../sdp_convert.hxx"
#include <boost/filesystem.hpp>
#include <algorithm>
std::vector<Polynomial> bilinear_basis(const Damped_Rational &damped_rational,
const size_t &half_max_degree);
std::vector<Boost_Float> sample_points(const size_t &num_points);
void write_output(const boost::filesystem::path &output_dir,
const std::vector<El::BigFloat> &objectives,
const std::vector<El::BigFloat> &normalization,
const std::vector<Positive_Matrix_With_Prefactor> &matrices,
Timers &timers)
{
auto &objectives_timer(timers.add_and_start("write_output.objectives"));
auto max_normalization(normalization.begin());
for(auto n(normalization.begin()); n!=normalization.end(); ++n)
{
if(Abs(*n)>Abs(*max_normalization))
{
max_normalization=n;
}
}
size_t max_index(std::distance(normalization.begin(), max_normalization));
El::BigFloat objective_const(objectives.at(max_index)
/ normalization.at(max_index));
std::vector<El::BigFloat> dual_objective_b;
dual_objective_b.reserve(normalization.size() - 1);
for(size_t index = 0; index < normalization.size(); ++index)
{
if(index != max_index)
{
dual_objective_b.push_back(
objectives.at(index) - normalization.at(index) * objective_const);
}
}
objectives_timer.stop();
auto &matrices_timer(timers.add_and_start("write_output.matrices"));
std::vector<Dual_Constraint_Group> dual_constraint_groups;
int rank(El::mpi::Rank(El::mpi::COMM_WORLD)),
num_procs(El::mpi::Size(El::mpi::COMM_WORLD));
std::vector<size_t> indices;
for(size_t index = rank; index < matrices.size(); index += num_procs)
{
indices.push_back(index);
}
for(auto &index : indices)
{
auto &scalings_timer(timers.add_and_start(
"write_output.matrices.scalings_" + std::to_string(index)));
const size_t max_degree([&]() {
int64_t result(0);
for(auto &pvv : matrices[index].polynomials)
for(auto &pv : pvv)
for(auto &polynomial : pv)
{
result = std::max(result, polynomial.degree());
}
return result;
}());
std::vector<Boost_Float> points(sample_points(max_degree + 1)),
sample_scalings;
sample_scalings.reserve(points.size());
for(auto &point : points)
{
Boost_Float numerator(
matrices[index].damped_rational.constant
* pow(matrices[index].damped_rational.base, point));
Boost_Float denominator(1);
for(auto &pole : matrices[index].damped_rational.poles)
{
denominator *= (point - pole);
}
sample_scalings.push_back(numerator / denominator);
}
scalings_timer.stop();
Polynomial_Vector_Matrix pvm;
pvm.rows = matrices[index].polynomials.size();
pvm.cols = matrices[index].polynomials.front().size();
auto &bilinear_basis_timer(timers.add_and_start(
"write_output.matrices.bilinear_basis_" + std::to_string(index)));
pvm.bilinear_basis
= bilinear_basis(matrices[index].damped_rational, max_degree / 2);
bilinear_basis_timer.stop();
pvm.sample_points.reserve(points.size());
for(auto &point : points)
{
pvm.sample_points.emplace_back(to_string(point));
}
pvm.sample_scalings.reserve(sample_scalings.size());
for(auto &scaling : sample_scalings)
{
pvm.sample_scalings.emplace_back(to_string(scaling));
}
auto &pvm_timer(timers.add_and_start("write_output.matrices.pvm_"
+ std::to_string(index)));
pvm.elements.reserve(pvm.rows * pvm.cols);
for(auto &pvv : matrices[index].polynomials)
for(auto &pv : pvv)
{
pvm.elements.emplace_back();
auto &pvm_polynomials(pvm.elements.back());
pvm_polynomials.reserve(pv.size());
pvm_polynomials.push_back(pv.at(max_index)
/ normalization.at(max_index));
auto &pvm_constant(pvm_polynomials.back());
// if(pvm.elements.size() == 5)
// {
// std::cout.precision(50);
// std::cout << "elements: " << max_index << " "
// << normalization.size() << " "
// << pv.at(0).coefficients[0] << " "
// << normalization.at(0) << " "
// << pvm_constant.coefficients[0] << " "
// << pv.at(0).coefficients.size() << " "
// << pvm_constant.coefficients.size() << " "
// << (pv.at(0).coefficients[0]
// - normalization.at(0)
// * pvm_constant.coefficients[0])
// << " "
// << (pv.at(max_index)
// / normalization.at(max_index)) << " "
// << pv.at(max_index) << " "
// << normalization.at(max_index) << " "
// << "\n";
// }
for(size_t index = 0; index < normalization.size(); ++index)
{
if(index != max_index)
{
pvm_polynomials.emplace_back(0, 0);
auto &pvm_poly(pvm_polynomials.back());
pvm_poly.coefficients.reserve(pv.at(index).degree() + 1);
size_t coefficient(0);
for(; coefficient < pv.at(index).coefficients.size()
&& coefficient < pvm_constant.coefficients.size();
++coefficient)
{
pvm_poly.coefficients.push_back(
pv.at(index).coefficients[coefficient]
- normalization.at(index)
* pvm_constant.coefficients[coefficient]);
// if(index==0 && pvm.elements.size() == 5)
// {
// std::cout << "diff: " << pvm_polynomials.size() << " "
// << coefficient << " "
// << pvm_poly.coefficients.back()
// << "\n";
// }
}
for(; coefficient < pv.at(index).coefficients.size();
++coefficient)
{
// if(index==0 && pvm.elements.size() == 5)
// {
// std::cout << "first: " << coefficient << "\n";
// }
pvm_poly.coefficients.push_back(
pv.at(index).coefficients[coefficient]);
}
for(; coefficient < pvm_constant.coefficients.size();
++coefficient)
{
// if(index==0 && pvm.elements.size() == 5)
// {
// std::cout << "second: " << coefficient << "\n";
// }
pvm_poly.coefficients.push_back(
-normalization.at(index)
* pvm_polynomials.at(0).coefficients[coefficient]);
}
}
}
}
pvm_timer.stop();
// std::cout.precision(50);
// // for(auto &p: pvm.elt(0,0))
// // std::cout << "poly 0 0: " << p.coefficients.at(0) << "\n";
// // for(auto &p: pvm.elt(0,1))
// // std::cout << "poly 0 1: " << p.coefficients.at(0) << "\n";
// // for(auto &p: pvm.elt(0,2))
// // std::cout << "poly 0 2: " << p.coefficients.at(0) << "\n";
// // for(auto &p: pvm.elt(1,0))
// // std::cout << "poly 1 0: " << p.coefficients.at(0) << "\n";
// // for(auto &p : pvm.elt(1, 1))
// // std::cout << "poly 1 1: " << p.coefficients.at(0) << "\n";
// std::cout << "poly 1 1: " << pvm.elt(1, 1).front().coefficients.at(0) << "\n";
// std::cout << "poly 1 1: " << pvm.elements.at(4).at(1).coefficients.at(0) << "\n";
// exit(0);
auto &dual_constraint_timer(timers.add_and_start(
"write_output.matrices.dual_constraint_" + std::to_string(index)));
dual_constraint_groups.emplace_back(pvm);
dual_constraint_timer.stop();
}
matrices_timer.stop();
auto &write_timer(timers.add_and_start("write_output.write"));
write_sdpb_input_files(output_dir, rank, num_procs, indices, objective_const,
dual_objective_b, dual_constraint_groups);
write_timer.stop();
}
<|endoftext|> |
<commit_before>#include <sqlite3.h>
#include <algorithm>
#include "ace/OS_NS_sys_time.h"
#include "log.h"
#include "json/reader.h"
#include "json/value.h"
#include "DataStore.h"
#include "QueryHandlerFactory.h"
#include "QueryHandler.h"
#include "DataStoreConstants.h"
using namespace ammo::gateway;
DataStoreReceiver::DataStoreReceiver (void)
: db_ (0),
stmt_ (0)
{
}
DataStoreReceiver::~DataStoreReceiver (void)
{
LOG_DEBUG ("Closing Data Store Service database...");
sqlite3_close (db_);
}
void
DataStoreReceiver::onConnect (GatewayConnector * /* sender */)
{
}
void
DataStoreReceiver::onDisconnect (GatewayConnector * /* sender */)
{
}
void
DataStoreReceiver::onPushDataReceived (GatewayConnector * /* sender */,
PushData &pushData)
{
LOG_TRACE ("Received " << pushData);
bool good_data_store = true;
if (pushData.mimeType.find (PVT_CONTACTS_DATA_TYPE) == 0)
{
good_data_store = this->pushContactData (pushData);
}
else
{
good_data_store = this->pushGeneralData (pushData);
}
if (good_data_store)
{
LOG_DEBUG ("data store successful");
}
}
void
DataStoreReceiver::onPullRequestReceived (GatewayConnector *sender,
PullRequest &pullReq)
{
LOG_TRACE ("pull request received");
if (sender == 0)
{
LOG_WARN ("Sender is null, no responses will be sent");
}
LOG_DEBUG ("Data type: " << pullReq.mimeType);
LOG_DEBUG ("query string: " << pullReq.query);
QueryHandlerFactory factory;
QueryHandler *handler = factory.createHandler (db_, sender, pullReq);
handler->handleQuery ();
delete handler;
handler = 0;
}
void
DataStoreReceiver::db_filepath (const std::string &path)
{
db_filepath_ = path;
}
bool
DataStoreReceiver::init (void)
{
std::string filepath (db_filepath_);
filepath += "DataStore_db.sql3";
// LOG_DEBUG ("full path = " << filepath.c_str ());
int status = sqlite3_open (filepath.c_str (), &db_);
if (status != 0)
{
LOG_ERROR ("Data Store Service - " << sqlite3_errmsg (db_));
return false;
}
const char *data_tbl_str =
"CREATE TABLE IF NOT EXISTS data_table ("
"uri TEXT,"
"mime_type TEXT,"
"origin_user TEXT,"
"tv_sec INTEGER NOT NULL,"
"tv_usec INTEGER,"
"data BLOB)";
return this->createTable (data_tbl_str, "data");
}
bool
DataStoreReceiver::pushContactData (const ammo::gateway::PushData &pushData)
{
Json::Value root;
if (!this->parseJson (pushData.data, root))
{
return false;
}
PrivateContact info;
this->contactFromJson (root, info);
// SQL table names can't contain '.', so we append the chars of
// the arg we use for the table name to the query string,
// while replacing '.' with '_'.
std::string tbl_name = pushData.originUsername;
std::replace_if (tbl_name.begin (),
tbl_name.end (),
std::bind2nd (std::equal_to<char> (), '.'),
'_');
// 2011-06-21 - not using the last 2 columns at this point.
std::string contacts_tbl_str ("CREATE TABLE IF NOT EXISTS ");
contacts_tbl_str += tbl_name;
contacts_tbl_str += " ("
"uri TEXT,"
"first_name TEXT,"
"middle_initial TEXT,"
"last_name TEXT,"
"rank TEXT,"
"call_sign TEXT,"
"branch TEXT,"
"unit TEXT,"
"email TEXT,"
"phone TEXT,"
"photo BLOB,"
"insignia BLOB)";
if (!this->createTable (contacts_tbl_str.c_str (), "contacts"))
{
return false;
}
std::string insert_str ("insert into ");
insert_str += tbl_name;
insert_str += " values (?,?,?,?,?,?,?,?,?,?,?,?)";
int status =
sqlite3_prepare (db_, insert_str.c_str (), -1, &stmt_, 0);
if (status != SQLITE_OK)
{
LOG_ERROR ("Private contact push - "
<< "prep of sqlite statement failed: "
<< sqlite3_errmsg (db_));
return false;
}
const char *insert_type = "Private contact";
bool good_binds =
this->bind_text (1, pushData.uri, insert_type, "uri")
&& this->bind_text (2, info.first_name, insert_type, "first name")
&& this->bind_text (3, info.middle_initial, insert_type, "middle initial")
&& this->bind_text (4, info.last_name, insert_type, "last name")
&& this->bind_text (5, info.rank, insert_type, "rank")
&& this->bind_text (6, info.call_sign, insert_type, "call sign")
&& this->bind_text (7, info.branch, insert_type, "branch")
&& this->bind_text (8, info.unit, insert_type, "unit")
&& this->bind_text (9, info.email, insert_type, "email")
&& this->bind_text (10, info.phone, insert_type, "phone");
if (good_binds)
{
status = sqlite3_step (stmt_);
if (status != SQLITE_DONE)
{
LOG_ERROR ("Private contact push - "
<< "insert operation failed: "
<< sqlite3_errmsg (db_));
return false;
}
}
return good_binds;
}
bool
DataStoreReceiver::pushGeneralData (const ammo::gateway::PushData &pushData)
{
ACE_Time_Value tv (ACE_OS::gettimeofday ());
int status =
sqlite3_prepare (db_,
"insert into data_table values (?,?,?,?,?,?)",
-1,
&stmt_,
0);
if (status != SQLITE_OK)
{
LOG_ERROR ("Data push - "
<< "prep of sqlite statement failed: "
<< sqlite3_errmsg (db_));
return false;
}
const char *insert_type = "Data";
bool good_binds =
this->bind_text (1, pushData.uri, insert_type, "URI")
&& this->bind_text (2, pushData.mimeType, insert_type, "data type")
&& this->bind_text (3, pushData.originUsername, insert_type, "origin user")
&& this->bind_int (4, tv.sec (), insert_type, "timestamp sec")
&& this->bind_int (5, tv.usec (), insert_type, "timestamp usec")
&& this->bind_blob (6,
pushData.data.data (),
pushData.data.length (),
insert_type,
"data");
if (good_binds)
{
status = sqlite3_step (stmt_);
if (status != SQLITE_DONE)
{
LOG_ERROR ("Data push - "
<< "insert operation failed: "
<< sqlite3_errmsg (db_));
return false;
}
}
return true;
}
bool
DataStoreReceiver::parseJson (const std::string &input,
Json::Value& root)
{
Json::Reader jsonReader;
bool parseSuccess = jsonReader.parse (input, root);
if (!parseSuccess)
{
LOG_ERROR ("JSON parsing error:"
<< jsonReader.getFormatedErrorMessages ());
return parseSuccess;
}
LOG_DEBUG ("Parsed JSON: " << root.toStyledString ());
return parseSuccess;
}
void
DataStoreReceiver::contactFromJson (const Json::Value &jsonRoot,
PrivateContact &info)
{
info.first_name = jsonRoot["first_name"].asString ();
info.middle_initial = jsonRoot["middle_initial"].asString ();
info.last_name = jsonRoot["last_name"].asString ();
info.rank = jsonRoot["rank"].asString ();
info.call_sign = jsonRoot["call_sign"].asString ();
info.branch = jsonRoot["branch"].asString ();
info.unit = jsonRoot["unit"].asString ();
info.email = jsonRoot["email"].asString ();
info.phone = jsonRoot["phone"].asString ();
}
bool
DataStoreReceiver::createTable (const char *tbl_string,
const char *msg)
{
char *db_err = 0;
sqlite3_exec (db_, tbl_string, 0, 0, &db_err);
if (db_err != 0)
{
LOG_ERROR ("Data Store Service " << msg << " table - " << db_err);
return false;
}
LOG_DEBUG ("Data Store Service " << msg << " table opened successfully...");
return true;
}
bool
DataStoreReceiver::bind_text (int column,
const std::string &text,
const char *push_type,
const char *column_name)
{
// Must make sure that stmt_ is prepared before this call.
int status =
sqlite3_bind_text (stmt_,
column,
text.c_str (),
text.length (),
SQLITE_STATIC);
if (status != SQLITE_OK)
{
LOG_ERROR (push_type << " push - "
<< column_name << " bind failed: "
<< sqlite3_errmsg (db_));
return false;
}
return true;
}
bool
DataStoreReceiver::bind_int (int column,
int val,
const char *push_type,
const char *column_name)
{
// Must make sure that stmt_ is prepared before this call.
int status = sqlite3_bind_int (stmt_, column, val);
if (status != SQLITE_OK)
{
LOG_ERROR (push_type << " push - "
<< column_name << " bind failed: "
<< sqlite3_errmsg (db_));
return false;
}
return true;
}
bool
DataStoreReceiver::bind_blob (int column,
const void *val,
int size,
const char *push_type,
const char *column_name)
{
int status =
sqlite3_bind_blob (stmt_,
column,
val,
size,
SQLITE_STATIC);
if (status != SQLITE_OK)
{
LOG_ERROR (push_type << " push - "
<< column_name << " bind failed: "
<< sqlite3_errmsg (db_));
return false;
}
return true;
}
<commit_msg>added append of forward slash to DataStore db filename path if not already supplied<commit_after>#include <sqlite3.h>
#include <algorithm>
#include "ace/OS_NS_sys_time.h"
#include "log.h"
#include "json/reader.h"
#include "json/value.h"
#include "DataStore.h"
#include "QueryHandlerFactory.h"
#include "QueryHandler.h"
#include "DataStoreConstants.h"
using namespace ammo::gateway;
DataStoreReceiver::DataStoreReceiver (void)
: db_ (0),
stmt_ (0)
{
}
DataStoreReceiver::~DataStoreReceiver (void)
{
LOG_DEBUG ("Closing Data Store Service database...");
sqlite3_close (db_);
}
void
DataStoreReceiver::onConnect (GatewayConnector * /* sender */)
{
}
void
DataStoreReceiver::onDisconnect (GatewayConnector * /* sender */)
{
}
void
DataStoreReceiver::onPushDataReceived (GatewayConnector * /* sender */,
PushData &pushData)
{
LOG_TRACE ("Received " << pushData);
bool good_data_store = true;
if (pushData.mimeType.find (PVT_CONTACTS_DATA_TYPE) == 0)
{
good_data_store = this->pushContactData (pushData);
}
else
{
good_data_store = this->pushGeneralData (pushData);
}
if (good_data_store)
{
LOG_DEBUG ("data store successful");
}
}
void
DataStoreReceiver::onPullRequestReceived (GatewayConnector *sender,
PullRequest &pullReq)
{
LOG_TRACE ("pull request received");
if (sender == 0)
{
LOG_WARN ("Sender is null, no responses will be sent");
}
LOG_DEBUG ("Data type: " << pullReq.mimeType);
LOG_DEBUG ("query string: " << pullReq.query);
QueryHandlerFactory factory;
QueryHandler *handler = factory.createHandler (db_, sender, pullReq);
handler->handleQuery ();
delete handler;
handler = 0;
}
void
DataStoreReceiver::db_filepath (const std::string &path)
{
db_filepath_ = path;
if (db_filepath_[db_filepath_.size () - 1] != '/')
{
db_filepath_.push_back ('/');
}
}
bool
DataStoreReceiver::init (void)
{
std::string filepath (db_filepath_);
filepath += "DataStore_db.sql3";
// LOG_DEBUG ("full path = " << filepath.c_str ());
int status = sqlite3_open (filepath.c_str (), &db_);
if (status != 0)
{
LOG_ERROR ("Data Store Service - " << sqlite3_errmsg (db_));
return false;
}
const char *data_tbl_str =
"CREATE TABLE IF NOT EXISTS data_table ("
"uri TEXT,"
"mime_type TEXT,"
"origin_user TEXT,"
"tv_sec INTEGER NOT NULL,"
"tv_usec INTEGER,"
"data BLOB)";
return this->createTable (data_tbl_str, "data");
}
bool
DataStoreReceiver::pushContactData (const ammo::gateway::PushData &pushData)
{
Json::Value root;
if (!this->parseJson (pushData.data, root))
{
return false;
}
PrivateContact info;
this->contactFromJson (root, info);
// SQL table names can't contain '.', so we append the chars of
// the arg we use for the table name to the query string,
// while replacing '.' with '_'.
std::string tbl_name = pushData.originUsername;
std::replace_if (tbl_name.begin (),
tbl_name.end (),
std::bind2nd (std::equal_to<char> (), '.'),
'_');
// 2011-06-21 - not using the last 2 columns at this point.
std::string contacts_tbl_str ("CREATE TABLE IF NOT EXISTS ");
contacts_tbl_str += tbl_name;
contacts_tbl_str += " ("
"uri TEXT,"
"first_name TEXT,"
"middle_initial TEXT,"
"last_name TEXT,"
"rank TEXT,"
"call_sign TEXT,"
"branch TEXT,"
"unit TEXT,"
"email TEXT,"
"phone TEXT,"
"photo BLOB,"
"insignia BLOB)";
if (!this->createTable (contacts_tbl_str.c_str (), "contacts"))
{
return false;
}
std::string insert_str ("insert into ");
insert_str += tbl_name;
insert_str += " values (?,?,?,?,?,?,?,?,?,?,?,?)";
int status =
sqlite3_prepare (db_, insert_str.c_str (), -1, &stmt_, 0);
if (status != SQLITE_OK)
{
LOG_ERROR ("Private contact push - "
<< "prep of sqlite statement failed: "
<< sqlite3_errmsg (db_));
return false;
}
const char *insert_type = "Private contact";
bool good_binds =
this->bind_text (1, pushData.uri, insert_type, "uri")
&& this->bind_text (2, info.first_name, insert_type, "first name")
&& this->bind_text (3, info.middle_initial, insert_type, "middle initial")
&& this->bind_text (4, info.last_name, insert_type, "last name")
&& this->bind_text (5, info.rank, insert_type, "rank")
&& this->bind_text (6, info.call_sign, insert_type, "call sign")
&& this->bind_text (7, info.branch, insert_type, "branch")
&& this->bind_text (8, info.unit, insert_type, "unit")
&& this->bind_text (9, info.email, insert_type, "email")
&& this->bind_text (10, info.phone, insert_type, "phone");
if (good_binds)
{
status = sqlite3_step (stmt_);
if (status != SQLITE_DONE)
{
LOG_ERROR ("Private contact push - "
<< "insert operation failed: "
<< sqlite3_errmsg (db_));
return false;
}
}
return good_binds;
}
bool
DataStoreReceiver::pushGeneralData (const ammo::gateway::PushData &pushData)
{
ACE_Time_Value tv (ACE_OS::gettimeofday ());
int status =
sqlite3_prepare (db_,
"insert into data_table values (?,?,?,?,?,?)",
-1,
&stmt_,
0);
if (status != SQLITE_OK)
{
LOG_ERROR ("Data push - "
<< "prep of sqlite statement failed: "
<< sqlite3_errmsg (db_));
return false;
}
const char *insert_type = "Data";
bool good_binds =
this->bind_text (1, pushData.uri, insert_type, "URI")
&& this->bind_text (2, pushData.mimeType, insert_type, "data type")
&& this->bind_text (3, pushData.originUsername, insert_type, "origin user")
&& this->bind_int (4, tv.sec (), insert_type, "timestamp sec")
&& this->bind_int (5, tv.usec (), insert_type, "timestamp usec")
&& this->bind_blob (6,
pushData.data.data (),
pushData.data.length (),
insert_type,
"data");
if (good_binds)
{
status = sqlite3_step (stmt_);
if (status != SQLITE_DONE)
{
LOG_ERROR ("Data push - "
<< "insert operation failed: "
<< sqlite3_errmsg (db_));
return false;
}
}
return true;
}
bool
DataStoreReceiver::parseJson (const std::string &input,
Json::Value& root)
{
Json::Reader jsonReader;
bool parseSuccess = jsonReader.parse (input, root);
if (!parseSuccess)
{
LOG_ERROR ("JSON parsing error:"
<< jsonReader.getFormatedErrorMessages ());
return parseSuccess;
}
LOG_DEBUG ("Parsed JSON: " << root.toStyledString ());
return parseSuccess;
}
void
DataStoreReceiver::contactFromJson (const Json::Value &jsonRoot,
PrivateContact &info)
{
info.first_name = jsonRoot["first_name"].asString ();
info.middle_initial = jsonRoot["middle_initial"].asString ();
info.last_name = jsonRoot["last_name"].asString ();
info.rank = jsonRoot["rank"].asString ();
info.call_sign = jsonRoot["call_sign"].asString ();
info.branch = jsonRoot["branch"].asString ();
info.unit = jsonRoot["unit"].asString ();
info.email = jsonRoot["email"].asString ();
info.phone = jsonRoot["phone"].asString ();
}
bool
DataStoreReceiver::createTable (const char *tbl_string,
const char *msg)
{
char *db_err = 0;
sqlite3_exec (db_, tbl_string, 0, 0, &db_err);
if (db_err != 0)
{
LOG_ERROR ("Data Store Service " << msg << " table - " << db_err);
return false;
}
LOG_DEBUG ("Data Store Service " << msg << " table opened successfully...");
return true;
}
bool
DataStoreReceiver::bind_text (int column,
const std::string &text,
const char *push_type,
const char *column_name)
{
// Must make sure that stmt_ is prepared before this call.
int status =
sqlite3_bind_text (stmt_,
column,
text.c_str (),
text.length (),
SQLITE_STATIC);
if (status != SQLITE_OK)
{
LOG_ERROR (push_type << " push - "
<< column_name << " bind failed: "
<< sqlite3_errmsg (db_));
return false;
}
return true;
}
bool
DataStoreReceiver::bind_int (int column,
int val,
const char *push_type,
const char *column_name)
{
// Must make sure that stmt_ is prepared before this call.
int status = sqlite3_bind_int (stmt_, column, val);
if (status != SQLITE_OK)
{
LOG_ERROR (push_type << " push - "
<< column_name << " bind failed: "
<< sqlite3_errmsg (db_));
return false;
}
return true;
}
bool
DataStoreReceiver::bind_blob (int column,
const void *val,
int size,
const char *push_type,
const char *column_name)
{
int status =
sqlite3_bind_blob (stmt_,
column,
val,
size,
SQLITE_STATIC);
if (status != SQLITE_OK)
{
LOG_ERROR (push_type << " push - "
<< column_name << " bind failed: "
<< sqlite3_errmsg (db_));
return false;
}
return true;
}
<|endoftext|> |
<commit_before>#include <functional>
#include <initializer_list>
#include <string>
#include <vector>
#include <unordered_map>
#include <algorithm>
#include <iostream>
#include <memory>
namespace parser{
class Sign_{
std::string name_;
bool isTerm_;
public:
Sign_(std::string n, bool t){
name_ = n;
isTerm_ = t;
}
Sign_(std::string n){
name_ = n;
isTerm_ = true;
}
Sign_(){
name_ ="";
isTerm_ = true;
}
bool isTerm(){
return isTerm_;
}
std::string name(){
return name_;
}
operator std::string() const{
return name_;
}
};
using Sign = std::shared_ptr<Sign_>;
class Item{
public:
Sign left;
std::vector<Sign> rights;
int pos;
Item(Sign l, std::initializer_list<Sign> const & r){
left = l;
rights.insert(rights.end(),r.begin(), r.end());
}
Sign nextSign(){
return rights[pos];
}
void next(){
if(rights.size() > pos+1)
pos++;
}
friend std::ostream& operator<<(std::ostream &out, const Item &i){
out << std::string(*i.left) <<" => ";
for(auto s : i.rights){
out << std::string(*s) <<" ";
}
out << "\n";
return out;
}
};
Sign mS(std::string name){
return Sign(new Sign_(name,false));
}
Sign mtS(std::string name){
return Sign(new Sign_(name));
}
auto E = mS("E");
auto Eq = mS("Eq");
auto T = mS("T");
auto Tq = mS("Tq");
auto F = mS("F");
auto Eps = mtS("Epsilon");
auto Fin = mtS("Fin");
std::vector<Item> rules;
std::vector<Item> getItems(Sign s){
//std::cout << std::string(*s) << std::endl;
std::vector<Item> res;
for(auto& i : rules){
if(i.left->name() == s->name()){
res.push_back(i);
}
}
return res;
}
std::vector<Sign> first(Sign sign){
if(sign->isTerm()){
return {sign};
}
std::vector<Sign> res;
auto items = getItems( sign );
if(items.size() == 0)
return res;
for(auto& i : items){
//std::cout << std::string( *i.left ) << " " << i.rights.size() <<std::endl;
auto ext = first(i.rights[0]);
if(find(ext.begin(), ext.end(), Eps) != ext.end()){
//std::cout <<"Eps!\n";
ext.erase(remove(ext.begin(), ext.end(), Eps), ext.end());
res.insert(res.end(), ext.begin(), ext.end());
if(i.rights.size() >= 2){
auto nxt = first(i.rights[1]);
res.insert(res.end(), nxt.begin(), nxt.end());
}else{
res.push_back( Eps);
}
}else{
res.insert(res.end(), ext.begin(), ext.end());
}
}
return res;
}
/*
std::vector<Sing> first(initializer_list<Sign>& l){
if(l.size() == 0)
return {Sign("Epsilon")};
std::vector<Rule> res;
auto it = l.begin();
if(*it == Sign("Epsilon")) return {Sign("Epsilon")};
if((*it)->isTerm()) return {*it};
auto ext = first(*it);
if(find(ext.begin(), ext.end(), Sign("Epsilon")) != ext.end()){
ext.erase(remove(ext.begin(), ext.end(), Sign("Epsilon")), ext.end());
res.insert(res.end(), ext.begin(), ext.end());
if(l.size() >= 2 ){
it++;
auto next = first(*it);
res.insert(res.end(), next.begin(), next.end());
}
return res;
}else{
return ext;
}
}
*/
std::vector<Sign> follow(Sign& s){
std::cout<< std::string(*s) << std::endl;
std::vector<Sign> res;
if(s == E){
res.push_back(Fin);
}
for(auto rit = rules.cbegin(); rit != rules.cend(); ++rit){
auto ls = rit->left;
if(ls == s) continue;
auto rs = rit->rights;
for(size_t i = 1; i < rs.size(); i++){
if(rs[i] == s){
if(i + 1 < rs.size()){
auto ext = first(rs[i+1]);
if(find(ext.begin(), ext.end(), Eps) != ext.end()){
auto left = follow(ls);
res.insert(res.end(), left.begin(), left.end());
}
ext.erase(remove(ext.begin(), ext.end(), Eps), ext.end());
res.insert(res.end(), ext.begin(), ext.end());
}else{
auto left = follow(ls);
res.insert(res.end(), left.begin(), left.end());
}
}
}
}
return res;
}
void closure(std::vector<Item>& I){
int size = I.size();
std::vector<Sign> alreadys;
auto Ib = I;
do{
size = I.size();
//std::cout<<"LOOP\n";
for(auto i : Ib){
//std::cout<< i << std::endl;
auto X = getItems( i.nextSign() );
//std::cout<<"item \n";
for(auto x : X){
//std::cout<< "#######\n" << x <<"\n";
if(find(alreadys.begin(), alreadys.end(), x.left) != alreadys.end()){
//std::cout<<":CON\n";
continue;
}
//std::cout<<"loop\n";
x.next();
//std::cout<<"push X\n";
I.push_back(x);
alreadys.push_back(x.left);
}
}
//std::cout<< size <<" "<<I.size() << "\n";
}while( size != I.size() );
}
std::vector<Item> Goto(std::vector<Item> I,Sign X){
std::vector<Item> J;
closure(J);
return J;
}
void setup(){
rules.push_back(Item( E,
{ T, Eq }
));
rules.push_back(Item( Eq,
{mtS("+"), T, Eq }
));
rules.push_back(Item( Eq,
{ Eps }
));
rules.push_back(Item( T,
{ F, Tq}
));
rules.push_back(Item( Tq,
{ mtS("*"), F, Tq }
));
rules.push_back(Item( Tq,
{ Eps }
));
rules.push_back(Item( F,
{ mtS("("), E, mtS(")")}
));
rules.push_back(Item( F,
{ mtS("i")}
));
}
using namespace std;
void test(Sign S){
std::cout << "==== "<<std::string(*S)<< " ===\n";
for(auto& s: first(S)){
std::cout << std::string(*s) << std::endl;
}
std::cout<<"===\n";
for(auto& r: follow(S)){
std::cout << std::string(*r) << std::endl;
}
}
void parser(){
setup();
/*
test(E);
test(Eq);
test(T);
test(Tq);
test(F);
*/
std::cout<<"===\n";
std::vector<Item> items = { Item( mS("S"), { E, Fin}) };
closure(items);
std::cout<<"~~~~~~~~~~~~~~~\n";
for(auto i : items)
std::cout << i;
//delete items;
//create_dfa();
//for(auto rit = rule_table.begin(); rit != rule_table.end(); ++rit){
// if(rit->second)
// rit->second.reset();
//}
}
}
int main(){
parser::parser();
return 0;
}
/*
* ==== T ===
* (
* i
* ===
* FIN
* )
* +
* ==== Tq ===
* *
* Epsilon
* ===
* FIN
* )
* +
* ==== F ===
* (
* i
* ===
* FIN
* )
* +
* *
* ===
*/
<commit_msg>[Fix] DFA generator compile error.<commit_after>#include <functional>
#include <initializer_list>
#include <string>
#include <vector>
#include <unordered_map>
#include <algorithm>
#include <iostream>
#include <memory>
namespace parser{
class Sign_{
std::string name_;
bool isTerm_;
public:
Sign_(std::string n, bool t){
name_ = n;
isTerm_ = t;
}
Sign_(std::string n){
name_ = n;
isTerm_ = true;
}
Sign_(){
name_ ="";
isTerm_ = true;
}
bool isTerm(){
return isTerm_;
}
std::string name(){
return name_;
}
operator std::string() const{
return name_;
}
};
using Sign = std::shared_ptr<Sign_>;
class Item{
public:
Sign left;
std::vector<Sign> rights;
int pos;
Item(Sign l, std::initializer_list<Sign> const & r){
left = l;
rights.insert(rights.end(),r.begin(), r.end());
}
Sign nextSign(){
return rights[pos];
}
void next(){
if(rights.size() > pos+1)
pos++;
}
friend std::ostream& operator<<(std::ostream &out, const Item &i){
out << std::string(*i.left) <<" => ";
for(auto s : i.rights){
out << std::string(*s) <<" ";
}
out << "\n";
return out;
}
};
Sign mS(std::string name){
return Sign(new Sign_(name,false));
}
Sign mtS(std::string name){
return Sign(new Sign_(name));
}
auto E = mS("E");
auto Eq = mS("Eq");
auto T = mS("T");
auto Tq = mS("Tq");
auto F = mS("F");
auto Eps = mtS("Epsilon");
auto Fin = mtS("Fin");
std::vector<Item> rules;
std::vector<Item> getItems(Sign s){
//std::cout << std::string(*s) << std::endl;
std::vector<Item> res;
for(auto& i : rules){
if(i.left->name() == s->name()){
res.push_back(i);
}
}
return res;
}
std::vector<Sign> first(Sign sign){
if(sign->isTerm()){
return {sign};
}
std::vector<Sign> res;
auto items = getItems( sign );
if(items.size() == 0)
return res;
for(auto& i : items){
//std::cout << std::string( *i.left ) << " " << i.rights.size() <<std::endl;
auto ext = first(i.rights[0]);
if(find(ext.begin(), ext.end(), Eps) != ext.end()){
//std::cout <<"Eps!\n";
ext.erase(remove(ext.begin(), ext.end(), Eps), ext.end());
res.insert(res.end(), ext.begin(), ext.end());
if(i.rights.size() >= 2){
auto nxt = first(i.rights[1]);
res.insert(res.end(), nxt.begin(), nxt.end());
}else{
res.push_back( Eps);
}
}else{
res.insert(res.end(), ext.begin(), ext.end());
}
}
return res;
}
/*
std::vector<Sing> first(initializer_list<Sign>& l){
if(l.size() == 0)
return {Sign("Epsilon")};
std::vector<Rule> res;
auto it = l.begin();
if(*it == Sign("Epsilon")) return {Sign("Epsilon")};
if((*it)->isTerm()) return {*it};
auto ext = first(*it);
if(find(ext.begin(), ext.end(), Sign("Epsilon")) != ext.end()){
ext.erase(remove(ext.begin(), ext.end(), Sign("Epsilon")), ext.end());
res.insert(res.end(), ext.begin(), ext.end());
if(l.size() >= 2 ){
it++;
auto next = first(*it);
res.insert(res.end(), next.begin(), next.end());
}
return res;
}else{
return ext;
}
}
*/
std::vector<Sign> follow(Sign& s){
std::cout<< std::string(*s) << std::endl;
std::vector<Sign> res;
if(s == E){
res.push_back(Fin);
}
for(auto rit = rules.cbegin(); rit != rules.cend(); ++rit){
auto ls = rit->left;
if(ls == s) continue;
auto rs = rit->rights;
for(size_t i = 1; i < rs.size(); i++){
if(rs[i] == s){
if(i + 1 < rs.size()){
auto ext = first(rs[i+1]);
if(find(ext.begin(), ext.end(), Eps) != ext.end()){
auto left = follow(ls);
res.insert(res.end(), left.begin(), left.end());
}
ext.erase(remove(ext.begin(), ext.end(), Eps), ext.end());
res.insert(res.end(), ext.begin(), ext.end());
}else{
auto left = follow(ls);
res.insert(res.end(), left.begin(), left.end());
}
}
}
}
return res;
}
void closure(std::vector<Item>& I){
int size = I.size();
std::vector<Sign> alreadys;
auto Ib = I;
do{
size = I.size();
//std::cout<<"LOOP\n";
for(auto i : Ib){
//std::cout<< i << std::endl;
auto X = getItems( i.nextSign() );
//std::cout<<"item \n";
for(auto x : X){
//std::cout<< "#######\n" << x <<"\n";
if(find(alreadys.begin(), alreadys.end(), x.left) != alreadys.end()){
//std::cout<<":CON\n";
continue;
}
//std::cout<<"loop\n";
x.next();
//std::cout<<"push X\n";
I.push_back(x);
alreadys.push_back(x.left);
}
}
//std::cout<< size <<" "<<I.size() << "\n";
}while( size != I.size() );
}
std::vector<Item> Goto(std::vector<Item> I,Sign X){
std::vector<Item> J;
for(auto i : I){
i.next();
J.push_back(i);
}
closure(J);
return J;
}
void DFA(){
std::vector<std::vector<Item>> T;
std::vector<Item> f({ Item( mS("S"),{ E, Fin}) });
closure(f);
T.push_back(f);
for(auto t : T){
for(auto i : t){
auto J = Goto( t, i.nextSign());
T.push_back(J);
}
}
}
void setup(){
rules.push_back(Item( E,
{ T, Eq }
));
rules.push_back(Item( Eq,
{mtS("+"), T, Eq }
));
rules.push_back(Item( Eq,
{ Eps }
));
rules.push_back(Item( T,
{ F, Tq}
));
rules.push_back(Item( Tq,
{ mtS("*"), F, Tq }
));
rules.push_back(Item( Tq,
{ Eps }
));
rules.push_back(Item( F,
{ mtS("("), E, mtS(")")}
));
rules.push_back(Item( F,
{ mtS("i")}
));
}
using namespace std;
void test(Sign S){
std::cout << "==== "<<std::string(*S)<< " ===\n";
for(auto& s: first(S)){
std::cout << std::string(*s) << std::endl;
}
std::cout<<"===\n";
for(auto& r: follow(S)){
std::cout << std::string(*r) << std::endl;
}
}
void parser(){
setup();
/*
test(E);
test(Eq);
test(T);
test(Tq);
test(F);
*/
std::cout<<"===\n";
std::vector<Item> items = { Item( mS("S"), { E, Fin}) };
closure(items);
std::cout<<"~~~~~~~~~~~~~~~\n";
for(auto i : items)
std::cout << i;
//delete items;
//create_dfa();
//for(auto rit = rule_table.begin(); rit != rule_table.end(); ++rit){
// if(rit->second)
// rit->second.reset();
//}
}
}
int main(){
parser::parser();
return 0;
}
/*
* ==== T ===
* (
* i
* ===
* FIN
* )
* +
* ==== Tq ===
* *
* Epsilon
* ===
* FIN
* )
* +
* ==== F ===
* (
* i
* ===
* FIN
* )
* +
* *
* ===
*/
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: updateinfo.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2007-07-06 14:38:45 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _UPDATE_INFO_INCLUDED_
#define _UPDATE_INFO_INCLUDED_
#include <rtl/ustring.hxx>
#include <vector>
struct DownloadSource
{
bool IsDirect;
rtl::OUString URL;
DownloadSource(bool bIsDirect, const rtl::OUString& aURL) : IsDirect(bIsDirect), URL(aURL) {};
DownloadSource(const DownloadSource& ds) : IsDirect(ds.IsDirect), URL(ds.URL) {};
DownloadSource & operator=( const DownloadSource & ds ) { IsDirect = ds.IsDirect; URL = ds.URL; return *this; };
};
struct ReleaseNote
{
sal_uInt8 Pos;
rtl::OUString URL;
sal_uInt8 Pos2;
rtl::OUString URL2;
ReleaseNote(sal_uInt8 pos, const rtl::OUString aURL) : Pos(pos), URL(aURL), Pos2(0), URL2() {};
ReleaseNote(sal_uInt8 pos, const rtl::OUString aURL, sal_uInt8 pos2, const rtl::OUString aURL2) : Pos(pos), URL(aURL), Pos2(pos2), URL2(aURL2) {};
ReleaseNote(const ReleaseNote& rn) :Pos(rn.Pos), URL(rn.URL), Pos2(rn.Pos2), URL2(rn.URL2) {};
ReleaseNote & operator=( const ReleaseNote& rn) { Pos=rn.Pos; URL=rn.URL; Pos2=rn.Pos2; URL2=rn.URL2; return *this; };
};
struct UpdateInfo
{
rtl::OUString BuildId;
rtl::OUString Version;
rtl::OUString Description;
std::vector< DownloadSource > Sources;
std::vector< ReleaseNote > ReleaseNotes;
UpdateInfo() : BuildId(), Version(), Description(), Sources(), ReleaseNotes() {};
UpdateInfo(const UpdateInfo& ui) : BuildId(ui.BuildId), Version(ui.Version), Description(ui.Description), Sources(ui.Sources), ReleaseNotes(ui.ReleaseNotes) {};
inline UpdateInfo & operator=( const UpdateInfo& ui );
};
UpdateInfo & UpdateInfo::operator=( const UpdateInfo& ui )
{
BuildId = ui.BuildId;
Version = ui.Version;
Description = ui.Description;
Sources = ui.Sources;
ReleaseNotes = ui.ReleaseNotes;
return *this;
}
// Returns the URL of the release note for the given position
rtl::OUString getReleaseNote(const UpdateInfo& rInfo, sal_uInt8 pos, bool autoDownloadEnabled=false);
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.2.132); FILE MERGED 2008/03/31 12:32:17 rt 1.2.132.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: updateinfo.hxx,v $
* $Revision: 1.3 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _UPDATE_INFO_INCLUDED_
#define _UPDATE_INFO_INCLUDED_
#include <rtl/ustring.hxx>
#include <vector>
struct DownloadSource
{
bool IsDirect;
rtl::OUString URL;
DownloadSource(bool bIsDirect, const rtl::OUString& aURL) : IsDirect(bIsDirect), URL(aURL) {};
DownloadSource(const DownloadSource& ds) : IsDirect(ds.IsDirect), URL(ds.URL) {};
DownloadSource & operator=( const DownloadSource & ds ) { IsDirect = ds.IsDirect; URL = ds.URL; return *this; };
};
struct ReleaseNote
{
sal_uInt8 Pos;
rtl::OUString URL;
sal_uInt8 Pos2;
rtl::OUString URL2;
ReleaseNote(sal_uInt8 pos, const rtl::OUString aURL) : Pos(pos), URL(aURL), Pos2(0), URL2() {};
ReleaseNote(sal_uInt8 pos, const rtl::OUString aURL, sal_uInt8 pos2, const rtl::OUString aURL2) : Pos(pos), URL(aURL), Pos2(pos2), URL2(aURL2) {};
ReleaseNote(const ReleaseNote& rn) :Pos(rn.Pos), URL(rn.URL), Pos2(rn.Pos2), URL2(rn.URL2) {};
ReleaseNote & operator=( const ReleaseNote& rn) { Pos=rn.Pos; URL=rn.URL; Pos2=rn.Pos2; URL2=rn.URL2; return *this; };
};
struct UpdateInfo
{
rtl::OUString BuildId;
rtl::OUString Version;
rtl::OUString Description;
std::vector< DownloadSource > Sources;
std::vector< ReleaseNote > ReleaseNotes;
UpdateInfo() : BuildId(), Version(), Description(), Sources(), ReleaseNotes() {};
UpdateInfo(const UpdateInfo& ui) : BuildId(ui.BuildId), Version(ui.Version), Description(ui.Description), Sources(ui.Sources), ReleaseNotes(ui.ReleaseNotes) {};
inline UpdateInfo & operator=( const UpdateInfo& ui );
};
UpdateInfo & UpdateInfo::operator=( const UpdateInfo& ui )
{
BuildId = ui.BuildId;
Version = ui.Version;
Description = ui.Description;
Sources = ui.Sources;
ReleaseNotes = ui.ReleaseNotes;
return *this;
}
// Returns the URL of the release note for the given position
rtl::OUString getReleaseNote(const UpdateInfo& rInfo, sal_uInt8 pos, bool autoDownloadEnabled=false);
#endif
<|endoftext|> |
<commit_before>/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
file Copyright.txt or https://opensource.org/licenses/BSD-3-Clause for
details. */
#include <cctype>
#include "parser.h"
struct CMakeParser {
CMakeParser(const std::string &content, std::vector<Span> &spans);
void skip_ws();
Command parse_command_invocation();
Span parse_identifier();
void parse_lparen();
void parse_rparen();
void parse_dollar_sign_expression();
Span parse_quoted_argument();
Span parse_unquoted_argument();
void expect(bool condition, const std::string &description);
const std::string &content;
size_t p{0};
std::vector<Span> &spans;
};
static bool isIdentifierStart(char c) {
return std::isalpha(c) || c == '_';
}
static bool isIdentifier(char c) {
return std::isalnum(c) || c == '_';
}
void CMakeParser::expect(bool condition, const std::string &description) {
if (!condition) {
throw parseexception("FAILURE: Expected " + description + " at " + std::to_string(p) +
", got:\n" + content.substr(p, p + 50));
}
}
CMakeParser::CMakeParser(const std::string &content_, std::vector<Span> &spans_)
: content(content_), spans(spans_) {
}
Span CMakeParser::parse_identifier() {
expect(isIdentifierStart(content[p]), "identifier start");
size_t ident_start = p;
p++;
while (isIdentifier(content[p])) {
p++;
}
return {SpanType::Identifier, content.substr(ident_start, p - ident_start)};
}
void CMakeParser::skip_ws() {
while (true) {
if (content[p] == '\n') {
spans.emplace_back(SpanType::Newline, content.substr(p, 1));
p++;
if (!std::isspace(content[p])) {
// HACK: Make sure newlines are always followed by whitespace, this makes
// transformations easier.
spans.emplace_back(SpanType::Space, "");
}
continue;
}
if (std::isspace(content[p])) {
size_t space_start = p;
while (std::isspace(content[p]) && content[p] != '\n') {
p++;
}
spans.emplace_back(SpanType::Space, content.substr(space_start, p - space_start));
continue;
}
if (content[p] == '#') {
size_t comment_start = p;
while (content[p] != '\n') {
p++;
}
spans.emplace_back(SpanType::Comment, content.substr(comment_start, p - comment_start));
continue;
}
break;
}
}
Command CMakeParser::parse_command_invocation() {
spans.push_back(parse_identifier());
const size_t identifier = spans.size() - 1;
skip_ws();
parse_lparen();
skip_ws();
std::vector<size_t> arguments;
while (true) {
if (content[p] == ')') {
parse_rparen();
break;
} else if (content[p] == '"') {
spans.push_back(parse_quoted_argument());
arguments.push_back(spans.size() - 1);
} else {
spans.push_back(parse_unquoted_argument());
arguments.push_back(spans.size() - 1);
}
skip_ws();
}
return {identifier, arguments};
}
void CMakeParser::parse_lparen() {
expect(content[p] == '(', "left paren");
spans.emplace_back(SpanType::Lparen, content.substr(p, 1));
p++;
}
void CMakeParser::parse_rparen() {
expect(content[p] == ')', "right paren");
if (spans.back().type != SpanType::Space) {
// HACK: Make sure right-parens are always preceded by whitespace, this makes
// transformations easier.
spans.emplace_back(SpanType::Space, "");
}
spans.emplace_back(SpanType::Rparen, content.substr(p, 1));
p++;
}
void CMakeParser::parse_dollar_sign_expression() {
expect(content[p] == '$', "dollar-sign");
p++;
char endbracket;
if (content[p] == '{') {
p++;
endbracket = '}';
} else if (content[p] == '(') {
p++;
endbracket = ')';
} else if (content[p] == '<') {
p++;
endbracket = '>';
} else {
expect(false, "'{', '(', or '<'");
}
while (true) {
// HACK: this is more lenient than the real CMake parser
if (content[p] == '$') {
parse_dollar_sign_expression();
continue;
} else if (content[p] == endbracket) {
p++;
break;
}
p++;
}
}
Span CMakeParser::parse_quoted_argument() {
expect(content[p] == '"', "double-quote");
size_t quoted_argument_start = p;
p++;
while (true) {
if (content[p] == '\\') {
p++;
p++;
} else if (content[p] == '"') {
p++;
break;
} else {
p++;
}
}
return {SpanType::Quoted, content.substr(quoted_argument_start, p - quoted_argument_start)};
}
static bool is_unquoted_element(const char c) {
// TODO: instead of std::isspace, also need to skip anything CMake thinks is
// whitespace (like comments)
return !(std::isspace(c) || c == '\\' || c == '$' || c == '"' || c == '(' || c == ')');
}
Span CMakeParser::parse_unquoted_argument() {
size_t unquoted_argument_start = p;
size_t parens_level = 0;
while (true) {
if (content[p] == '\\') {
p += 2;
continue;
}
if (content[p] == '$') {
parse_dollar_sign_expression();
continue;
}
if (content[p] == '"') {
parse_quoted_argument();
continue;
}
if (content[p] == '(') {
parens_level++;
p++;
continue;
}
if (content[p] == ')' && parens_level > 0) {
parens_level--;
p++;
continue;
}
if (is_unquoted_element(content[p])) {
while (is_unquoted_element(content[p])) {
p++;
}
continue;
}
break;
}
if (unquoted_argument_start == p) {
throw parseexception("expected unquoted argument");
}
return {SpanType::Unquoted,
content.substr(unquoted_argument_start, p - unquoted_argument_start)};
}
parseexception::parseexception(const std::string &message) : std::runtime_error{message} {
}
std::pair<std::vector<Span>, std::vector<Command>> parse(const std::string &content) {
std::vector<Command> commands;
std::vector<Span> spans;
CMakeParser parser{content, spans};
while (true) {
parser.skip_ws();
if (parser.p >= content.size()) {
break;
}
commands.push_back(parser.parse_command_invocation());
}
return std::make_pair(std::move(spans), std::move(commands));
}
<commit_msg>parser.cpp: fix uninitialized variable 'endbracket'<commit_after>/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
file Copyright.txt or https://opensource.org/licenses/BSD-3-Clause for
details. */
#include <cctype>
#include "parser.h"
struct CMakeParser {
CMakeParser(const std::string &content, std::vector<Span> &spans);
void skip_ws();
Command parse_command_invocation();
Span parse_identifier();
void parse_lparen();
void parse_rparen();
void parse_dollar_sign_expression();
Span parse_quoted_argument();
Span parse_unquoted_argument();
void expect(bool condition, const std::string &description);
const std::string &content;
size_t p{0};
std::vector<Span> &spans;
};
static bool isIdentifierStart(char c) {
return std::isalpha(c) || c == '_';
}
static bool isIdentifier(char c) {
return std::isalnum(c) || c == '_';
}
void CMakeParser::expect(bool condition, const std::string &description) {
if (!condition) {
throw parseexception("FAILURE: Expected " + description + " at " + std::to_string(p) +
", got:\n" + content.substr(p, p + 50));
}
}
CMakeParser::CMakeParser(const std::string &content_, std::vector<Span> &spans_)
: content(content_), spans(spans_) {
}
Span CMakeParser::parse_identifier() {
expect(isIdentifierStart(content[p]), "identifier start");
size_t ident_start = p;
p++;
while (isIdentifier(content[p])) {
p++;
}
return {SpanType::Identifier, content.substr(ident_start, p - ident_start)};
}
void CMakeParser::skip_ws() {
while (true) {
if (content[p] == '\n') {
spans.emplace_back(SpanType::Newline, content.substr(p, 1));
p++;
if (!std::isspace(content[p])) {
// HACK: Make sure newlines are always followed by whitespace, this makes
// transformations easier.
spans.emplace_back(SpanType::Space, "");
}
continue;
}
if (std::isspace(content[p])) {
size_t space_start = p;
while (std::isspace(content[p]) && content[p] != '\n') {
p++;
}
spans.emplace_back(SpanType::Space, content.substr(space_start, p - space_start));
continue;
}
if (content[p] == '#') {
size_t comment_start = p;
while (content[p] != '\n') {
p++;
}
spans.emplace_back(SpanType::Comment, content.substr(comment_start, p - comment_start));
continue;
}
break;
}
}
Command CMakeParser::parse_command_invocation() {
spans.push_back(parse_identifier());
const size_t identifier = spans.size() - 1;
skip_ws();
parse_lparen();
skip_ws();
std::vector<size_t> arguments;
while (true) {
if (content[p] == ')') {
parse_rparen();
break;
} else if (content[p] == '"') {
spans.push_back(parse_quoted_argument());
arguments.push_back(spans.size() - 1);
} else {
spans.push_back(parse_unquoted_argument());
arguments.push_back(spans.size() - 1);
}
skip_ws();
}
return {identifier, arguments};
}
void CMakeParser::parse_lparen() {
expect(content[p] == '(', "left paren");
spans.emplace_back(SpanType::Lparen, content.substr(p, 1));
p++;
}
void CMakeParser::parse_rparen() {
expect(content[p] == ')', "right paren");
if (spans.back().type != SpanType::Space) {
// HACK: Make sure right-parens are always preceded by whitespace, this makes
// transformations easier.
spans.emplace_back(SpanType::Space, "");
}
spans.emplace_back(SpanType::Rparen, content.substr(p, 1));
p++;
}
void CMakeParser::parse_dollar_sign_expression() {
expect(content[p] == '$', "dollar-sign");
p++;
char endbracket = 0;
if (content[p] == '{') {
p++;
endbracket = '}';
} else if (content[p] == '(') {
p++;
endbracket = ')';
} else if (content[p] == '<') {
p++;
endbracket = '>';
} else {
expect(false, "'{', '(', or '<'");
}
while (true) {
// HACK: this is more lenient than the real CMake parser
if (content[p] == '$') {
parse_dollar_sign_expression();
continue;
} else if (content[p] == endbracket) {
p++;
break;
}
p++;
}
}
Span CMakeParser::parse_quoted_argument() {
expect(content[p] == '"', "double-quote");
size_t quoted_argument_start = p;
p++;
while (true) {
if (content[p] == '\\') {
p++;
p++;
} else if (content[p] == '"') {
p++;
break;
} else {
p++;
}
}
return {SpanType::Quoted, content.substr(quoted_argument_start, p - quoted_argument_start)};
}
static bool is_unquoted_element(const char c) {
// TODO: instead of std::isspace, also need to skip anything CMake thinks is
// whitespace (like comments)
return !(std::isspace(c) || c == '\\' || c == '$' || c == '"' || c == '(' || c == ')');
}
Span CMakeParser::parse_unquoted_argument() {
size_t unquoted_argument_start = p;
size_t parens_level = 0;
while (true) {
if (content[p] == '\\') {
p += 2;
continue;
}
if (content[p] == '$') {
parse_dollar_sign_expression();
continue;
}
if (content[p] == '"') {
parse_quoted_argument();
continue;
}
if (content[p] == '(') {
parens_level++;
p++;
continue;
}
if (content[p] == ')' && parens_level > 0) {
parens_level--;
p++;
continue;
}
if (is_unquoted_element(content[p])) {
while (is_unquoted_element(content[p])) {
p++;
}
continue;
}
break;
}
if (unquoted_argument_start == p) {
throw parseexception("expected unquoted argument");
}
return {SpanType::Unquoted,
content.substr(unquoted_argument_start, p - unquoted_argument_start)};
}
parseexception::parseexception(const std::string &message) : std::runtime_error{message} {
}
std::pair<std::vector<Span>, std::vector<Command>> parse(const std::string &content) {
std::vector<Command> commands;
std::vector<Span> spans;
CMakeParser parser{content, spans};
while (true) {
parser.skip_ws();
if (parser.p >= content.size()) {
break;
}
commands.push_back(parser.parse_command_invocation());
}
return std::make_pair(std::move(spans), std::move(commands));
}
<|endoftext|> |
<commit_before>#ifndef BFC_PARSER_HPP
#define BFC_PARSER_HPP
#include "lexer.hpp"
#include "result.hpp"
#include "ast/ast.hpp"
namespace bfc {
template <class Source, class Traits = source_traits<Source>>
class parser {
public:
using Lexer = lexer<Source, Traits>;
parser(Lexer lexer) : lexer(std::move(lexer)) {}
ast_node parse() {
/* create result to hold lexer result */
result_type res;
/* create token to pass into lexer */
token tok{};
for(;;) {
res = lexer.next(tok);
switch (res) {
case result_type::OK:
updateAst(tok);
break;
case result_type::DONE:
{
ast_node program(new ast_program(tok.loc, astSeq));
return program;
}
case result_type::FAIL:
default:
break;
}
}
}
private:
Lexer lexer;
/* vector of instructions to return */
ast_seq astSeq;
ast_node updateLoop(source_loc loopPos){
/* create result to hold lexer result */
result_type res = result_type::OK;
/* create token to pass into lexer */
token tok;
/* create vector to use to create ast_loop */
ast_seq loopAst{};
for(;;) {
res = lexer.next(tok);
token::type kind = tok.kind;
source_loc loc = tok.loc;
switch (res) {
case result_type::OK:
switch (kind) {
case token::INC:
{
ast_node add(new ast_add(loc, 0, 1));
loopAst.push_back(add);
break;
}
case token::DEC:
{
ast_node sub(new ast_sub(loc, 0, 1));
loopAst.push_back(sub);
break;
}
case token::MOVE_R:
{
ast_node move_r(new ast_mov(loc, 1));
loopAst.push_back(move_r);
break;
}
case token::MOVE_L:
{
ast_node move_l(new ast_mov(loc, -1));
loopAst.push_back(move_l);
break;
}
case token::LOOP_BEGIN:
{
ast_node innerLoop = updateLoop(loc);
loopAst.push_back(innerLoop);
break;
}
case token::LOOP_END:
{
ast_node loop(new ast_loop(loopPos, loopAst));
return loop;
}
case token::PUT_CHAR:
{
ast_node write(new ast_write(loc, 0));
loopAst.push_back(write);
break;
}
case token::GET_CHAR:
{
ast_node read(new ast_read(loc, 0));
loopAst.push_back(read);
break;
}
default:
break;
}
break; /* result_type::OK */
case result_type::DONE:
case result_type::FAIL:
default:
break;
// Throw Exception (ends without closing loop)
}
}
}
void updateAst(token &tok) {
token::type kind = tok.kind;
source_loc loc = tok.loc;
switch (tok.kind) {
case token::INC:
{
ast_node add(new ast_add(loc, 0, 1));
astSeq.push_back(add);
break;
}
case token::DEC:
{
ast_node sub(new ast_sub(loc, 0, 1));
astSeq.push_back(sub);
break;
}
case token::MOVE_R:
{
ast_node move_r(new ast_mov(loc, 1));
astSeq.push_back(move_r);
break;
}
case token::MOVE_L:
{
ast_node move_l(new ast_mov(loc, -1));
astSeq.push_back(move_l);
break;
}
case token::LOOP_BEGIN:
{
ast_node loop = updateLoop(loc);
astSeq.push_back(loop);
break;
}
case token::LOOP_END:
// Throw Exception (No open loop to close)
break;
case token::PUT_CHAR:
{
ast_node write(new ast_write(loc, 0));
astSeq.push_back(write);
break;
}
case token::GET_CHAR:
{
ast_node read(new ast_read(loc, 0));
astSeq.push_back(read);
break;
}
default:
break;
}
}
};
}
#endif /* !BFC_PARSER_HPP */
<commit_msg>Update parser to use emplace_back<commit_after>#ifndef BFC_PARSER_HPP
#define BFC_PARSER_HPP
#include "lexer.hpp"
#include "result.hpp"
#include "ast/ast.hpp"
namespace bfc {
template <class Source, class Traits = source_traits<Source>>
class parser {
public:
using Lexer = lexer<Source, Traits>;
parser(Lexer lexer) : lexer(std::move(lexer)) {}
ast_node parse() {
/* create result to hold lexer result */
result_type res;
/* create token to pass into lexer */
token tok{};
for(;;) {
res = lexer.next(tok);
switch (res) {
case result_type::OK:
updateAst(tok);
break;
case result_type::DONE:
{
ast_node program(new ast_program(tok.loc, astSeq));
return program;
}
case result_type::FAIL:
default:
break;
}
}
}
private:
Lexer lexer;
/* vector of instructions to return */
ast_seq astSeq;
ast_node updateLoop(source_loc loopPos){
/* create result to hold lexer result */
result_type res = result_type::OK;
/* create token to pass into lexer */
token tok;
/* create vector to use to create ast_loop */
ast_seq loopAst{};
for(;;) {
res = lexer.next(tok);
token::type kind = tok.kind;
source_loc loc = tok.loc;
switch (res) {
case result_type::OK:
switch (kind) {
case token::INC:
{
loopAst.emplace_back(new ast_add(loc, 0, 1));
break;
}
case token::DEC:
{
loopAst.emplace_back(new ast_sub(loc, 0, 1));
break;
}
case token::MOVE_R:
{
loopAst.emplace_back(new ast_mov(loc, 1));
break;
}
case token::MOVE_L:
{
loopAst.emplace_back(new ast_mov(loc, -1));
break;
}
case token::LOOP_BEGIN:
{
ast_node innerLoop = updateLoop(loc);
loopAst.push_back(innerLoop);
break;
}
case token::LOOP_END:
{
ast_node loop(new ast_loop(loopPos, loopAst));
return loop;
}
case token::PUT_CHAR:
{
loopAst.emplace_back(new ast_write(loc, 0));
break;
}
case token::GET_CHAR:
{
loopAst.emplace_back(new ast_read(loc, 0));
break;
}
default:
break;
}
break; /* result_type::OK */
case result_type::DONE:
case result_type::FAIL:
default:
break;
// Throw Exception (ends without closing loop)
}
}
}
void updateAst(token &tok) {
token::type kind = tok.kind;
source_loc loc = tok.loc;
switch (tok.kind) {
case token::INC:
{
astSeq.emplace_back(new ast_add(loc, 0, 1));
break;
}
case token::DEC:
{
astSeq.emplace_back(new ast_sub(loc, 0, 1));
break;
}
case token::MOVE_R:
{
astSeq.emplace_back(new ast_mov(loc, 1));
break;
}
case token::MOVE_L:
{
astSeq.emplace_back(new ast_mov(loc, -1));
break;
}
case token::LOOP_BEGIN:
{
ast_node loop = updateLoop(loc);
astSeq.push_back(loop);
break;
}
case token::LOOP_END:
// Throw Exception (No open loop to close)
break;
case token::PUT_CHAR:
{
astSeq.emplace_back(new ast_write(loc, 0));
break;
}
case token::GET_CHAR:
{
astSeq.emplace_back(new ast_read(loc, 0));
break;
}
default:
break;
}
}
};
}
#endif /* !BFC_PARSER_HPP */
<|endoftext|> |
<commit_before>#include "UnitTester.hpp"
#ifdef RUN_TESTS
using namespace testing;
UnitTester::UnitTester(){}
UnitTester::~UnitTester(){}
void UnitTester::runTests()
{
#ifdef RUN_ALL
utilities();
logging();
resourceGroup();
resourceManager();
INIParser();
#elif
#ifdef TEST_UTILITIES
utilities();
#endif
#ifdef TEST_LOGGING
logging();
#endif
#ifdef TEST_RESOURCE_GROUP
resourceGroup();
#endif
#ifdef TEST_RESOURCE_MANAGER
resourceMananager();
#endif
#ifdef TEST_INI_PARSER
INIParser();
#endif
#endif
}
//PRIVATE FUNCTIONS
void UnitTester::utilities()
{
BOOST_LOG_SEV(testLogger, INFO) << "Now testing: void util::swapChars(char& a, char& b);";
char a = 'a', b = 'b';
util::swapChars(a, b);
if (a != 'b' || b != 'a') { BOOST_LOG_SEV(testLogger, ERROR) << "Input to util::swapChars failed."; }
BOOST_LOG_SEV(testLogger, INFO) << "Now testing: std::string util::reverseString(const std::string& str);";
if (util::reverseString("myString") != "gnirtSym") { BOOST_LOG_SEV(testLogger, ERROR) << "Input to util::reverseString failed. IN: \"myString\""; }
if (util::reverseString("MYSTRING ") != " GNIRTSYM") { BOOST_LOG_SEV(testLogger, ERROR) << "Input to util::reverseString failed. IN: \"MYSTRING \""; }
if (util::reverseString("aaaaaa") != "aaaaaa") { BOOST_LOG_SEV(testLogger, ERROR) << "Input to util::reverseString failed. IN: \"aaaaaa\""; }
if (util::reverseString("This Is An Extended TEST") != "TSET dednetxE nA sI sihT") { BOOST_LOG_SEV(testLogger, ERROR) << "Input to util::reverseString failed. IN: \"This Is An Extended Test\""; }
if (util::reverseString("\"\\\"Escape") != "epacsE\"\\\"") { BOOST_LOG_SEV(testLogger, ERROR) << "Input to util::reverseString failed. IN: \"\"\\\"Escape\""; }
BOOST_LOG_SEV(testLogger, INFO) << "Now testing: std::vector<std::string> util::splitStrAtSubstr(const std::string& str, const std::string& split)";
std::vector<std::string> expected = { "One", "Two", "Three" };
std::vector<std::string> expected2 = { "One", "Three" };
std::vector<std::string> expected3 = { "OneTwoThree" };
if (util::splitStrAtSubstr("One.Two.Three", ".") != expected) { BOOST_LOG_SEV(testLogger, ERROR) << "Input to util::splitStrAtSubstr failed. IN: \"One.Two.Three\", \".\""; }
if (util::splitStrAtSubstr("One\"Two\"Three", "\"") != expected) { BOOST_LOG_SEV(testLogger, ERROR) << "Input to util::splitStrAtSubstr failed. IN: \"One\"Two\"Three\", \"\"\""; }
if (util::splitStrAtSubstr("OneTwoThree", ".") != expected3) { BOOST_LOG_SEV(testLogger, ERROR) << "Input to util::splitStrAtSubstr failed. IN: \"One.Two.Three\", \".\""; }
if (util::splitStrAtSubstr("OneTwoThree", "Two") != expected2) { BOOST_LOG_SEV(testLogger, ERROR) << "Input to util::splitStrAtSubstr failed. IN: \"OneTwoThree\", \"Two\""; }
BOOST_LOG_SEV(testLogger, INFO) << "Now testing: std::string util::vecToStr(const std::vector<std::string>& vec, const std::string& between);";
std::vector<std::string> in1 = {"One", "Two", "Three"}; std::string in12 = "."; std::string out1 = "One.Two.Three";
std::vector<std::string> in2 = {"Hello", "World"}; std::string in22 = " To The "; std::string out2 = "Hello To The World";
std::string out3 = "OneTwoThree";
if (util::vecToStr(in1, in12) != out1){ BOOST_LOG_SEV(testLogger, ERROR) << "Input to util::vecToStr failed. IN: {One, Two, Three}, \".\""; }
if (util::vecToStr(in2, in22) != out2) { BOOST_LOG_SEV(testLogger, ERROR) << "Input to util::vecToStr faile. IN: {Hello, World}, \" To The \""; }
if (util::vecToStr(in1, "") != out3) { BOOST_LOG_SEV(testLogger, ERROR) << "Input to util::vecToStr filed. IN: {One, Two, Three}, NOTHING"; }
int one = 1;
int two = 2;
int three = 3;
BOOST_LOG_SEV(testLogger, INFO) << "Now testing: int util::imax(int& a, int& b);";
if(util::imax(one, two) != 2){ BOOST_LOG_SEV(testLogger, ERROR) << "Input to util::imax failed."; }
BOOST_LOG_SEV(testLogger, INFO) << "Now testing: int util::imin(int& a, int& b);";
if(util::imin(one, two) != 1){ BOOST_LOG_SEV(testLogger, ERROR) << "Input to util::imin failed."; }
BOOST_LOG_SEV(testLogger, INFO) << "Now testing: void util::ibound(int& a, const int& b, const int& c)";
util::ibound(three, two, one);
if(three != 2){ BOOST_LOG_SEV(testLogger, ERROR) << "Input to util::ibound failed."; }
double done = 1.1;
double dtwo = 2.2;
double dthree = 3.3;
BOOST_LOG_SEV(testLogger, INFO) << "Now testing: double util::dmax(double& a, double& b);";
if(util::dmax(done, dtwo) != 2.2){ BOOST_LOG_SEV(testLogger, ERROR) << "Input to util::dmax failed."; }
BOOST_LOG_SEV(testLogger, INFO) << "Now testing: double util::dmin(double& a, double& b);";
if(util::dmin(done, dtwo) != 1.1){ BOOST_LOG_SEV(testLogger, ERROR) << "Input to util::dmin failed."; }
BOOST_LOG_SEV(testLogger, INFO) << "Now testing: void util::dbound(double& a, const double& b, const double& c)";
util::dbound(dthree, dtwo, done);
if(dthree != 2.2){ BOOST_LOG_SEV(testLogger, ERROR) << "Input to util::dbound failed."; }
float fone = 1.1;
float ftwo = 2.2;
float fthree = 3.3;
BOOST_LOG_SEV(testLogger, INFO) << "Now testing: float util::fmax(float& a, float& b);";
if(util::fmax(fone, ftwo) != 2.2){ BOOST_LOG_SEV(testLogger, ERROR) << "Input to util::fmax failed."; }
BOOST_LOG_SEV(testLogger, INFO) << "Now testing: float util::fmin(float& a, float& b);";
if(util::fmin(fone, ftwo) != 1.1){ BOOST_LOG_SEV(testLogger, ERROR) << "Input to util::fmin failed."; }
BOOST_LOG_SEV(testLogger, INFO) << "Now testing: void util::fbound(float& a, const float& b, const float& c)";
util::fbound(fthree, ftwo, fone);
if(fthree != 2.2){ BOOST_LOG_SEV(testLogger, ERROR) << "Input to util::fbound failed."; }
unsigned int uone = 1;
unsigned int utwo = 2;
unsigned int uthree = 3;
BOOST_LOG_SEV(testLogger, INFO) << "Now testing: unsigned int util::uimax(unsigned int& a, unsigned int& b);";
if(util::uimax(uone, utwo) != 2){ BOOST_LOG_SEV(testLogger, ERROR) << "Input to util::uimax failed."; }
BOOST_LOG_SEV(testLogger, INFO) << "Now testing: unsigned int util::uimin(unsigned int& a, unsigned int& b);";
if(util::uimin(uone, utwo) != 1){ BOOST_LOG_SEV(testLogger, ERROR) << "Input to util::uimin failed."; }
BOOST_LOG_SEV(testLogger, INFO) << "Now testing: void util::uibound(unsigned int& a, const unsigned int& b, const unsigned int& c)";
util::uibound(uthree, utwo, uone);
if(uthree != 2){ BOOST_LOG_SEV(testLogger, ERROR) << "Input to util::uibound failed."; }
BOOST_LOG_SEV(testLogger, INFO) << "Now testing: void util::void nullCopyValue(const T& toCopy, T& value);";
float copy = 3.141;
float pie;
util::nullCopyValue<float>(copy, pie);
if(pie != copy){ BOOST_LOG_SEV(testLogger, ERROR) << "Input to util::nullCopyValue failed."; }
BOOST_LOG_SEV(testLogger, INFO) << "Now testing: void nullCopyVector(const std::vector<T>& toCopy, const std::vector<T>& vec);";
int nullInt = NULL;
std::vector<int> mixedVec = { 4, nullInt, 5, nullInt, 124 };
std::vector<int> startingVec = { 3, 5, 8, 5, 1265 };
std::vector<int> expectedVec = { 4, 4, 5, 5, 124 };
util::nullCopyVector<int>(mixedVec, startingVec);
if (startingVec != expectedVec) { BOOST_LOG_SEV(testLogger, ERROR) << "Input to util::nullCopyVector failed. IN: {4, nullInt, 5, nullInt, 124}, {3, 5, 8, 5, 1265}"; }
}
void UnitTester::logging()
{
}
void UnitTester::resourceGroup()
{
}
void UnitTester::resourceManager()
{
}
void UnitTester::INIParser()
{
}
#endif<commit_msg>fixed float comparison<commit_after>#include "UnitTester.hpp"
#ifdef RUN_TESTS
using namespace testing;
UnitTester::UnitTester(){}
UnitTester::~UnitTester(){}
void UnitTester::runTests()
{
#ifdef RUN_ALL
utilities();
logging();
resourceGroup();
resourceManager();
INIParser();
#elif
#ifdef TEST_UTILITIES
utilities();
#endif
#ifdef TEST_LOGGING
logging();
#endif
#ifdef TEST_RESOURCE_GROUP
resourceGroup();
#endif
#ifdef TEST_RESOURCE_MANAGER
resourceMananager();
#endif
#ifdef TEST_INI_PARSER
INIParser();
#endif
#endif
}
//PRIVATE FUNCTIONS
void UnitTester::utilities()
{
BOOST_LOG_SEV(testLogger, INFO) << "Now testing: void util::swapChars(char& a, char& b);";
char a = 'a', b = 'b';
util::swapChars(a, b);
if (a != 'b' || b != 'a') { BOOST_LOG_SEV(testLogger, ERROR) << "Input to util::swapChars failed."; }
BOOST_LOG_SEV(testLogger, INFO) << "Now testing: std::string util::reverseString(const std::string& str);";
if (util::reverseString("myString") != "gnirtSym") { BOOST_LOG_SEV(testLogger, ERROR) << "Input to util::reverseString failed. IN: \"myString\""; }
if (util::reverseString("MYSTRING ") != " GNIRTSYM") { BOOST_LOG_SEV(testLogger, ERROR) << "Input to util::reverseString failed. IN: \"MYSTRING \""; }
if (util::reverseString("aaaaaa") != "aaaaaa") { BOOST_LOG_SEV(testLogger, ERROR) << "Input to util::reverseString failed. IN: \"aaaaaa\""; }
if (util::reverseString("This Is An Extended TEST") != "TSET dednetxE nA sI sihT") { BOOST_LOG_SEV(testLogger, ERROR) << "Input to util::reverseString failed. IN: \"This Is An Extended Test\""; }
if (util::reverseString("\"\\\"Escape") != "epacsE\"\\\"") { BOOST_LOG_SEV(testLogger, ERROR) << "Input to util::reverseString failed. IN: \"\"\\\"Escape\""; }
BOOST_LOG_SEV(testLogger, INFO) << "Now testing: std::vector<std::string> util::splitStrAtSubstr(const std::string& str, const std::string& split)";
std::vector<std::string> expected = { "One", "Two", "Three" };
std::vector<std::string> expected2 = { "One", "Three" };
std::vector<std::string> expected3 = { "OneTwoThree" };
if (util::splitStrAtSubstr("One.Two.Three", ".") != expected) { BOOST_LOG_SEV(testLogger, ERROR) << "Input to util::splitStrAtSubstr failed. IN: \"One.Two.Three\", \".\""; }
if (util::splitStrAtSubstr("One\"Two\"Three", "\"") != expected) { BOOST_LOG_SEV(testLogger, ERROR) << "Input to util::splitStrAtSubstr failed. IN: \"One\"Two\"Three\", \"\"\""; }
if (util::splitStrAtSubstr("OneTwoThree", ".") != expected3) { BOOST_LOG_SEV(testLogger, ERROR) << "Input to util::splitStrAtSubstr failed. IN: \"One.Two.Three\", \".\""; }
if (util::splitStrAtSubstr("OneTwoThree", "Two") != expected2) { BOOST_LOG_SEV(testLogger, ERROR) << "Input to util::splitStrAtSubstr failed. IN: \"OneTwoThree\", \"Two\""; }
BOOST_LOG_SEV(testLogger, INFO) << "Now testing: std::string util::vecToStr(const std::vector<std::string>& vec, const std::string& between);";
std::vector<std::string> in1 = {"One", "Two", "Three"}; std::string in12 = "."; std::string out1 = "One.Two.Three";
std::vector<std::string> in2 = {"Hello", "World"}; std::string in22 = " To The "; std::string out2 = "Hello To The World";
std::string out3 = "OneTwoThree";
if (util::vecToStr(in1, in12) != out1){ BOOST_LOG_SEV(testLogger, ERROR) << "Input to util::vecToStr failed. IN: {One, Two, Three}, \".\""; }
if (util::vecToStr(in2, in22) != out2) { BOOST_LOG_SEV(testLogger, ERROR) << "Input to util::vecToStr faile. IN: {Hello, World}, \" To The \""; }
if (util::vecToStr(in1, "") != out3) { BOOST_LOG_SEV(testLogger, ERROR) << "Input to util::vecToStr filed. IN: {One, Two, Three}, NOTHING"; }
int one = 1;
int two = 2;
int three = 3;
BOOST_LOG_SEV(testLogger, INFO) << "Now testing: int util::imax(int& a, int& b);";
if(util::imax(one, two) != 2){ BOOST_LOG_SEV(testLogger, ERROR) << "Input to util::imax failed."; }
BOOST_LOG_SEV(testLogger, INFO) << "Now testing: int util::imin(int& a, int& b);";
if(util::imin(one, two) != 1){ BOOST_LOG_SEV(testLogger, ERROR) << "Input to util::imin failed."; }
BOOST_LOG_SEV(testLogger, INFO) << "Now testing: void util::ibound(int& a, const int& b, const int& c)";
util::ibound(three, two, one);
if(three != 2){ BOOST_LOG_SEV(testLogger, ERROR) << "Input to util::ibound failed."; }
double done = 1.1;
double dtwo = 2.2;
double dthree = 3.3;
BOOST_LOG_SEV(testLogger, INFO) << "Now testing: double util::dmax(double& a, double& b);";
if(util::dmax(done, dtwo) != 2.2){ BOOST_LOG_SEV(testLogger, ERROR) << "Input to util::dmax failed."; }
BOOST_LOG_SEV(testLogger, INFO) << "Now testing: double util::dmin(double& a, double& b);";
if(util::dmin(done, dtwo) != 1.1){ BOOST_LOG_SEV(testLogger, ERROR) << "Input to util::dmin failed."; }
BOOST_LOG_SEV(testLogger, INFO) << "Now testing: void util::dbound(double& a, const double& b, const double& c)";
util::dbound(dthree, dtwo, done);
if(dthree != 2.2){ BOOST_LOG_SEV(testLogger, ERROR) << "Input to util::dbound failed."; }
float fone = 1.1;
float ftwo = 2.2;
float fthree = 3.3;
BOOST_LOG_SEV(testLogger, INFO) << "Now testing: float util::fmax(float& a, float& b);";
if(util::fmax(fone, ftwo) != ftwo){ BOOST_LOG_SEV(testLogger, ERROR) << "Input to util::fmax failed."; }
BOOST_LOG_SEV(testLogger, INFO) << "Now testing: float util::fmin(float& a, float& b);";
if(util::fmin(fone, ftwo) != fone){ BOOST_LOG_SEV(testLogger, ERROR) << "Input to util::fmin failed."; }
BOOST_LOG_SEV(testLogger, INFO) << "Now testing: void util::fbound(float& a, const float& b, const float& c)";
util::fbound(fthree, ftwo, fone);
if(fthree != ftwo){ BOOST_LOG_SEV(testLogger, ERROR) << "Input to util::fbound failed."; }
unsigned int uone = 1;
unsigned int utwo = 2;
unsigned int uthree = 3;
BOOST_LOG_SEV(testLogger, INFO) << "Now testing: unsigned int util::uimax(unsigned int& a, unsigned int& b);";
if(util::uimax(uone, utwo) != 2){ BOOST_LOG_SEV(testLogger, ERROR) << "Input to util::uimax failed."; }
BOOST_LOG_SEV(testLogger, INFO) << "Now testing: unsigned int util::uimin(unsigned int& a, unsigned int& b);";
if(util::uimin(uone, utwo) != 1){ BOOST_LOG_SEV(testLogger, ERROR) << "Input to util::uimin failed."; }
BOOST_LOG_SEV(testLogger, INFO) << "Now testing: void util::uibound(unsigned int& a, const unsigned int& b, const unsigned int& c)";
util::uibound(uthree, utwo, uone);
if(uthree != 2){ BOOST_LOG_SEV(testLogger, ERROR) << "Input to util::uibound failed."; }
BOOST_LOG_SEV(testLogger, INFO) << "Now testing: void util::void nullCopyValue(const T& toCopy, T& value);";
float copy = 3.141;
float pie;
util::nullCopyValue<float>(copy, pie);
if(pie != copy){ BOOST_LOG_SEV(testLogger, ERROR) << "Input to util::nullCopyValue failed."; }
BOOST_LOG_SEV(testLogger, INFO) << "Now testing: void nullCopyVector(const std::vector<T>& toCopy, const std::vector<T>& vec);";
int nullInt = NULL;
std::vector<int> mixedVec = { 4, nullInt, 5, nullInt, 124 };
std::vector<int> startingVec = { 3, 5, 8, 5, 1265 };
std::vector<int> expectedVec = { 4, 4, 5, 5, 124 };
util::nullCopyVector<int>(mixedVec, startingVec);
if (startingVec != expectedVec) { BOOST_LOG_SEV(testLogger, ERROR) << "Input to util::nullCopyVector failed. IN: {4, nullInt, 5, nullInt, 124}, {3, 5, 8, 5, 1265}"; }
}
void UnitTester::logging()
{
}
void UnitTester::resourceGroup()
{
}
void UnitTester::resourceManager()
{
}
void UnitTester::INIParser()
{
}
#endif<|endoftext|> |
<commit_before>#ifndef __Z2H_PARSER__
#define __Z2H_PARSER__ = 1
#include <cmath>
#include <string>
#include <vector>
#include <fstream>
#include <sstream>
#include <iostream>
#include <stddef.h>
#include <sys/stat.h>
#include <functional>
#include "symbol.hpp"
#include "token.hpp"
#include "binder.hpp"
using namespace std::placeholders;
namespace z2h {
template <typename TParser>
struct Parser : public Binder<TParser> {
std::string source;
size_t position;
std::vector<Token *> tokens;
size_t index;
~Parser() {
while (!tokens.empty())
delete tokens.back(), tokens.pop_back();
}
Parser()
: source("")
, position(0)
, tokens({})
, index(0) {
}
// Exception must be defined by the inheriting parser, throw exceptions defined there
virtual std::exception Exception(const char *file, size_t line, const std::string &message = "") = 0;
// Symbols must be defined by the inheriting parser
virtual std::vector<Symbol *> Symbols() = 0;
// the default for the eof symbol is first in in the list of symbols
virtual Symbol * EofSymbol() {
return Symbols()[0];
}
// the default for the eos symbol is second in in the list of symbols
virtual Symbol * EosSymbol() {
return Symbols()[1];
}
std::string Open(const std::string &filename) {
struct stat buffer;
if (stat(filename.c_str(), &buffer) != 0)
Exception(__FILE__, __LINE__, filename + " doesn't exist or is unreadable");
std::ifstream file(filename);
std::string text((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
return text;
}
std::vector<Token *> TokenizeFile(const std::string &filename) {
auto source = Open(filename);
return Tokenize(source);
}
std::vector<Token *> Tokenize(std::string source) {
this->index = 0;
this->source = source;
auto eof = EofSymbol();
auto token = Consume();
while (*eof != *token->symbol) {
token = Consume();
}
return tokens;
}
virtual std::vector<Ast *> ParseFile(const std::string &filename) {
auto source = Open(filename);
return Parse(source);
}
virtual std::vector<Ast *> Parse(std::string source) {
this->index = 0;
this->source = source;
return {Statement()};
//return Statements(); FIXME: return this back to normal after fixing the bug... -sai
}
virtual Token * Scan() {
auto eof = EofSymbol();
Token *match = nullptr;
if (position < source.length()) {
for (auto symbol : Symbols()) {
auto token = symbol->Scan(symbol, source.substr(position, source.length() - position), position);
if (nullptr == match) {
match = token;
}
else if (nullptr != token && (token->length > match->length || (token->symbol->lbp > match->symbol->lbp && token->length == match->length))) {
delete match;
match = token;
} else {
delete token;
}
}
if (nullptr == match) {
throw Exception(__FILE__, __LINE__, "Parser::Scan: invalid symbol");
}
return match;
}
std::cout << "FAILED SCAN" << std::endl;
return new Token(eof, "EOF", position, 0, false); //eof
}
virtual Token * LookAhead(size_t &distance, bool skips = false) {
Token *token = nullptr;
auto i = index;
while (distance) {
if (i < tokens.size()) {
token = tokens[i];
}
else {
token = Scan();
position += token->length;
tokens.push_back(token);
}
if (skips || !token->skip) {
--distance;
}
++i;
}
distance = i - index;
return token;
}
Token * LookAhead1() {
size_t distance = 1;
return this->LookAhead(distance);
}
Token * LookAhead2() {
size_t distance = 2;
return this->LookAhead(distance);
}
virtual Token * Consume(Symbol *expected = nullptr) {
if (expected) {
return Consume({expected});
}
return Consume({});
}
virtual Token * Consume(std::initializer_list<Symbol *> expectations) {
size_t distance = 1;
auto token = LookAhead(distance);
if (expectations.size()) {
std::cout << "expectations.size()=" << expectations.size() << std::endl;
for (auto expectation : expectations) {
if (expectation) {
std::cout << "expectation = " << *expectation << std::endl;
std::cout << "token->symbol = " << *token->symbol << std::endl;
std::cout << "expectation=" << expectation << " == token->symbol=" << token->symbol << std::endl;
if (expectation == token->symbol) {
index += distance;
return token;
}
}
/*
if (expected && expected == token->symbol) {
index += distance;
return token;
}
*/
}
return nullptr;
}
index += distance;
return token;
}
virtual Ast * Expression(size_t rbp = 0) {
auto *curr = Consume();
size_t distance = 1;
auto *next = LookAhead(distance);
Ast *left = curr->symbol->Nud(curr);
while (rbp < next->symbol->lbp) {
curr = Consume();
if (nullptr == curr->symbol->Led) {
std::cout << __LINE__ << "no Led: curr=" << *curr << std::endl;
std::ostringstream out;
out << "unexpected: nullptr==Led curr=" << *curr;
throw Exception(__FILE__, __LINE__, out.str());
}
left = curr->symbol->Led(left, curr);
size_t distance = 1;
next = LookAhead(distance);
}
return left;
}
virtual Ast * Statement() {
size_t distance = 1;
auto *la1 = LookAhead(distance);
if (nullptr != la1->symbol->Std) {
Consume();
return la1->symbol->Std();
}
auto ast = Expression();
return ast;
}
virtual std::vector<Ast *> Statements() {
std::vector<Ast *> statements;
auto eos = EosSymbol();
auto statement = Statement();
while (statement) {
statements.push_back(statement);
statement = Consume(eos) ? Statement() : nullptr;
}
return statements;
}
size_t Line() {
return 0;
}
size_t Column() {
return 0;
}
};
}
#endif /*__Z2H_PARSER__*/
<commit_msg>removed debug printing... -sai<commit_after>#ifndef __Z2H_PARSER__
#define __Z2H_PARSER__ = 1
#include <cmath>
#include <string>
#include <vector>
#include <fstream>
#include <sstream>
#include <iostream>
#include <stddef.h>
#include <sys/stat.h>
#include <functional>
#include "symbol.hpp"
#include "token.hpp"
#include "binder.hpp"
using namespace std::placeholders;
namespace z2h {
template <typename TParser>
struct Parser : public Binder<TParser> {
std::string source;
size_t position;
std::vector<Token *> tokens;
size_t index;
~Parser() {
while (!tokens.empty())
delete tokens.back(), tokens.pop_back();
}
Parser()
: source("")
, position(0)
, tokens({})
, index(0) {
}
// Exception must be defined by the inheriting parser, throw exceptions defined there
virtual std::exception Exception(const char *file, size_t line, const std::string &message = "") = 0;
// Symbols must be defined by the inheriting parser
virtual std::vector<Symbol *> Symbols() = 0;
// the default for the eof symbol is first in in the list of symbols
virtual Symbol * EofSymbol() {
return Symbols()[0];
}
// the default for the eos symbol is second in in the list of symbols
virtual Symbol * EosSymbol() {
return Symbols()[1];
}
std::string Open(const std::string &filename) {
struct stat buffer;
if (stat(filename.c_str(), &buffer) != 0)
Exception(__FILE__, __LINE__, filename + " doesn't exist or is unreadable");
std::ifstream file(filename);
std::string text((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
return text;
}
std::vector<Token *> TokenizeFile(const std::string &filename) {
auto source = Open(filename);
return Tokenize(source);
}
std::vector<Token *> Tokenize(std::string source) {
this->index = 0;
this->source = source;
auto eof = EofSymbol();
auto token = Consume();
while (*eof != *token->symbol) {
token = Consume();
}
return tokens;
}
virtual std::vector<Ast *> ParseFile(const std::string &filename) {
auto source = Open(filename);
return Parse(source);
}
virtual std::vector<Ast *> Parse(std::string source) {
this->index = 0;
this->source = source;
return {Statement()};
//return Statements(); FIXME: return this back to normal after fixing the bug... -sai
}
virtual Token * Scan() {
auto eof = EofSymbol();
Token *match = nullptr;
if (position < source.length()) {
for (auto symbol : Symbols()) {
auto token = symbol->Scan(symbol, source.substr(position, source.length() - position), position);
if (nullptr == match) {
match = token;
}
else if (nullptr != token && (token->length > match->length || (token->symbol->lbp > match->symbol->lbp && token->length == match->length))) {
delete match;
match = token;
} else {
delete token;
}
}
if (nullptr == match) {
throw Exception(__FILE__, __LINE__, "Parser::Scan: invalid symbol");
}
return match;
}
std::cout << "FAILED SCAN" << std::endl;
return new Token(eof, "EOF", position, 0, false); //eof
}
virtual Token * LookAhead(size_t &distance, bool skips = false) {
Token *token = nullptr;
auto i = index;
while (distance) {
if (i < tokens.size()) {
token = tokens[i];
}
else {
token = Scan();
position += token->length;
tokens.push_back(token);
}
if (skips || !token->skip) {
--distance;
}
++i;
}
distance = i - index;
return token;
}
Token * LookAhead1() {
size_t distance = 1;
return this->LookAhead(distance);
}
Token * LookAhead2() {
size_t distance = 2;
return this->LookAhead(distance);
}
virtual Token * Consume(Symbol *expected = nullptr) {
if (expected) {
return Consume({expected});
}
return Consume({});
}
virtual Token * Consume(std::initializer_list<Symbol *> expectations) {
size_t distance = 1;
auto token = LookAhead(distance);
if (expectations.size()) {
for (auto expectation : expectations) {
if (expectation) {
if (expectation == token->symbol) {
index += distance;
return token;
}
}
/*
if (expected && expected == token->symbol) {
index += distance;
return token;
}
*/
}
return nullptr;
}
index += distance;
return token;
}
virtual Ast * Expression(size_t rbp = 0) {
auto *curr = Consume();
size_t distance = 1;
auto *next = LookAhead(distance);
Ast *left = curr->symbol->Nud(curr);
while (rbp < next->symbol->lbp) {
curr = Consume();
if (nullptr == curr->symbol->Led) {
std::cout << __LINE__ << "no Led: curr=" << *curr << std::endl;
std::ostringstream out;
out << "unexpected: nullptr==Led curr=" << *curr;
throw Exception(__FILE__, __LINE__, out.str());
}
left = curr->symbol->Led(left, curr);
size_t distance = 1;
next = LookAhead(distance);
}
return left;
}
virtual Ast * Statement() {
size_t distance = 1;
auto *la1 = LookAhead(distance);
if (nullptr != la1->symbol->Std) {
Consume();
return la1->symbol->Std();
}
auto ast = Expression();
return ast;
}
virtual std::vector<Ast *> Statements() {
std::vector<Ast *> statements;
auto eos = EosSymbol();
auto statement = Statement();
while (statement) {
statements.push_back(statement);
statement = Consume(eos) ? Statement() : nullptr;
}
return statements;
}
size_t Line() {
return 0;
}
size_t Column() {
return 0;
}
};
}
#endif /*__Z2H_PARSER__*/
<|endoftext|> |
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
// Software Guide : BeginLatex
//
// The following code is an implementation of a small OTB
// program. It tests including header files and linking with OTB
// libraries.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
#include "otbImage.h"
#include <iostream>
int main()
{
typedef otb::Image< unsigned short, 2 > ImageType;
ImageType::Pointer image = ImageType::New();
std::cout << "OTB Hello World !" << std::endl;
return 0;
}
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// This code instantiates an image whose pixels are represented with
// type \code{unsigned short}. The image is then constructed and assigned to a
// \doxygen{itk}{SmartPointer}. Later in the text we will discuss
// \code{SmartPointer} in detail, for now think of it as a handle on an
// instance of an object (see section \ref{sec:SmartPointers} for more
// information).
//
// Software Guide : EndLatex
<commit_msg>Petite correction exemple HelloWorld<commit_after>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
// Software Guide : BeginLatex
//
// The following code is an implementation of a small OTB
// program. It tests including header files and linking with OTB
// libraries.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
#include "otbImage.h"
#include <iostream>
int main()
{
typedef otb::Image< unsigned short, 2 > ImageType;
ImageType::Pointer image = ImageType::New();
std::cout << "OTB Hello World !" << std::endl;
return 0;
}
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// This code instantiates an image whose pixels are represented with
// type \code{unsigned short}. The image is then created and assigned to a
// \doxygen{itk}{SmartPointer}. Later in the text we will discuss
// \code{SmartPointer}s in detail, for now think of it as a handle on an
// instance of an object (see section \ref{sec:SmartPointers} for more
// information).
//
// Software Guide : EndLatex
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: AccessibleStringWrap.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: vg $ $Date: 2003-04-24 16:55:35 $
*
* 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 <algorithm>
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _SV_OUTDEV_HXX
#include <vcl/outdev.hxx>
#endif
#include "svxfont.hxx"
#include "AccessibleStringWrap.hxx"
//------------------------------------------------------------------------
//
// AccessibleStringWrap implementation
//
//------------------------------------------------------------------------
AccessibleStringWrap::AccessibleStringWrap( OutputDevice& rDev, SvxFont& rFont, const String& rText ) :
mrDev( rDev ),
mrFont( rFont ),
maText( rText )
{
}
sal_Bool AccessibleStringWrap::GetCharacterBounds( sal_Int32 nIndex, Rectangle& rRect )
{
DBG_ASSERT(nIndex >= 0 && nIndex <= USHRT_MAX,
"SvxAccessibleStringWrap::GetCharacterBounds: index value overflow");
mrFont.SetPhysFont( &mrDev );
// #108900# Handle virtual position one-past-the end of the string
if( nIndex >= maText.Len() )
{
// create a caret bounding rect that has the height of the
// current font and is one pixel wide.
rRect.Left() = mrDev.GetTextWidth(maText);
rRect.Top() = 0;
rRect.SetSize( Size(mrDev.GetTextHeight(), 1) );
}
else
{
long aXArray[2];
mrDev.GetCaretPositions( maText, aXArray, static_cast< USHORT >(nIndex), 1 );
rRect.Left() = 0;
rRect.Top() = 0;
rRect.SetSize( Size(mrDev.GetTextHeight(), labs(aXArray[0] - aXArray[1])) );
rRect.Move( ::std::min(aXArray[0], aXArray[1]), 0 );
}
if( mrFont.IsVertical() )
{
// #101701# Rotate to vertical
rRect = Rectangle( Point(-rRect.Top(), rRect.Left()),
Point(-rRect.Bottom(), rRect.Right()));
}
return sal_True;
}
sal_Int32 AccessibleStringWrap::GetIndexAtPoint( const Point& rPoint )
{
// search for character bounding box containing given point
Rectangle aRect;
sal_Int32 i, nLen = maText.Len();
for( i=0; i<nLen; ++i )
{
GetCharacterBounds(i, aRect);
if( aRect.IsInside(rPoint) )
return i;
}
return -1;
}
<commit_msg>INTEGRATION: CWS ooo19126 (1.3.1444); FILE MERGED 2005/09/05 14:18:45 rt 1.3.1444.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: AccessibleStringWrap.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-08 20:18:50 $
*
* 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
*
************************************************************************/
#include <algorithm>
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _SV_OUTDEV_HXX
#include <vcl/outdev.hxx>
#endif
#include "svxfont.hxx"
#include "AccessibleStringWrap.hxx"
//------------------------------------------------------------------------
//
// AccessibleStringWrap implementation
//
//------------------------------------------------------------------------
AccessibleStringWrap::AccessibleStringWrap( OutputDevice& rDev, SvxFont& rFont, const String& rText ) :
mrDev( rDev ),
mrFont( rFont ),
maText( rText )
{
}
sal_Bool AccessibleStringWrap::GetCharacterBounds( sal_Int32 nIndex, Rectangle& rRect )
{
DBG_ASSERT(nIndex >= 0 && nIndex <= USHRT_MAX,
"SvxAccessibleStringWrap::GetCharacterBounds: index value overflow");
mrFont.SetPhysFont( &mrDev );
// #108900# Handle virtual position one-past-the end of the string
if( nIndex >= maText.Len() )
{
// create a caret bounding rect that has the height of the
// current font and is one pixel wide.
rRect.Left() = mrDev.GetTextWidth(maText);
rRect.Top() = 0;
rRect.SetSize( Size(mrDev.GetTextHeight(), 1) );
}
else
{
long aXArray[2];
mrDev.GetCaretPositions( maText, aXArray, static_cast< USHORT >(nIndex), 1 );
rRect.Left() = 0;
rRect.Top() = 0;
rRect.SetSize( Size(mrDev.GetTextHeight(), labs(aXArray[0] - aXArray[1])) );
rRect.Move( ::std::min(aXArray[0], aXArray[1]), 0 );
}
if( mrFont.IsVertical() )
{
// #101701# Rotate to vertical
rRect = Rectangle( Point(-rRect.Top(), rRect.Left()),
Point(-rRect.Bottom(), rRect.Right()));
}
return sal_True;
}
sal_Int32 AccessibleStringWrap::GetIndexAtPoint( const Point& rPoint )
{
// search for character bounding box containing given point
Rectangle aRect;
sal_Int32 i, nLen = maText.Len();
for( i=0; i<nLen; ++i )
{
GetCharacterBounds(i, aRect);
if( aRect.IsInside(rPoint) )
return i;
}
return -1;
}
<|endoftext|> |
<commit_before>// @(#)root/peac:$Name: $:$Id: TProofPEAC.cxx,v 1.2 2005/02/08 22:40:36 rdm Exp $
// Author: Maarten Ballintijn 21/10/2004
// Author: Kris Gulbrandsen 21/10/2004
/*************************************************************************
* Copyright (C) 1995-2005, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TProofPEAC //
// //
// This class implements the setup of a PROOF session using PEAC //
// //
//////////////////////////////////////////////////////////////////////////
#include "TClarens.h"
#include "TCondor.h"
#include "TDSet.h"
#include "TEnv.h"
#include "TError.h"
#include "TList.h"
#include "TLM.h"
#include "TMonitor.h"
#include "TProofPEAC.h"
#include "TProofServ.h"
#include "TSlave.h"
#include "TSystem.h"
#include "TTimer.h"
#include "TUrl.h"
ClassImp(TProofPEAC)
//______________________________________________________________________________
TProofPEAC::TProofPEAC(const char *masterurl, const char *sessionid,
const char *confdir, Int_t loglevel)
: fCondor(0), fTimer(0)
{
// Start PEAC proof session
if (!strncasecmp(sessionid, "peac:", 5))
sessionid+=5;
Init(masterurl, sessionid, confdir, loglevel);
}
//______________________________________________________________________________
TProofPEAC::~TProofPEAC()
{
// Destroy PEAC proof session
delete fCondor;
delete fTimer;
if (fLM) {
delete fHeartbeatTimer;
fHeartbeatTimer = 0;
fLM->EndSession(fSession);
delete fLM;
fLM = 0;
}
}
//------------------------------------------------------------------------------
Bool_t TProofPEAC::StartSlaves()
{
if (IsMaster()) {
TClarens::Init();
const Char_t *lmUrl = gEnv->GetValue("PEAC.LmUrl",
"http://localhost:8080/clarens/");
fLM = gClarens->CreateLM(lmUrl);
if (!fLM) {
Error("StartSlaves", "Could not connect to local manager for url '%s'",
lmUrl);
return kFALSE;
}
TUrl url(lmUrl);
TString lm = url.GetHost();
Int_t lmPort = url.GetPort();
fSession = fConfFile;
PDB(kGlobal,1) Info("StartSlaves", "PEAC mode: host: %s port: %d session: %s",
lm.Data(), lmPort, fSession.Data());
TList* config = 0;
if(!fLM->StartSession(fSession, config, fHBPeriod)) {
Error("StartSlaves", "Could not start session '%s' for local manager '%s'",
fSession.Data(), lmUrl);
return kFALSE;
}
TList csl;
TIter NextSlave(config);
Int_t ord = 0;
TString jobad;
while (TLM::TSlaveParams *sp = dynamic_cast<TLM::TSlaveParams*>(NextSlave())) {
PDB(kGlobal,1) Info("StartSlaves", "node: %s", sp->fNode.Data());
// create slave server
if (sp->fType == "inetd") {
TString fullord = TString(gProofServ->GetOrdinal()) + "." + ((Long_t) ord);
ord++;
TSlave *slave = CreateSlave(sp->fNode, fPort, fullord, sp->fPerfidx, sp->fImg, kPROOF_WorkDir);
fSlaves->Add(slave);
if (slave->IsValid()) {
fAllMonitor->Add(slave->GetSocket());
PDB(kGlobal,3)
Info("StartSlaves", "slave on host %s created and added to list",
sp->fNode.Data());
} else {
fBadSlaves->Add(slave);
PDB(kGlobal,3)
Info("StartSlaves", "slave on host %s created and added to list of bad slaves",
sp->fNode.Data());
}
} else if (sp->fType == "cod") {
if (fCondor == 0) {
fCondor = new TCondor;
jobad = GetJobAd();
fImage = fCondor->GetImage(gSystem->HostName());
if (fImage.Length() == 0) {
Error("StartSlaves", "no image found for node %s",
gSystem->HostName());
delete fCondor;
fCondor = 0;
}
}
if (fCondor != 0) {
TCondorSlave *c = fCondor->Claim(sp->fNode, jobad);
if (c != 0) {
csl.Add(c);
} else {
Info("StartSlaves", "node: %s not claimed", sp->fNode.Data());
}
}
} else {
Error("StartSlaves", "unknown slave type (%s)", sp->fType.Data());
}
}
delete config;
TIter next(&csl);
TCondorSlave *cs;
while ((cs = (TCondorSlave*)next()) != 0) {
// Get slave FQDN ...
TString SlaveFqdn;
TInetAddress SlaveAddr = gSystem->GetHostByName((const char *)cs->fHostname);
if (SlaveAddr.IsValid()) {
SlaveFqdn = SlaveAddr.GetHostName();
if (SlaveFqdn == "UnNamedHost")
SlaveFqdn = SlaveAddr.GetHostAddress();
}
// who do we believe for perf & img, Condor for the moment
TString fullord = TString(gProofServ->GetOrdinal()) + "." + ((Long_t) ord);
ord++;
TSlave *slave = CreateSlave(cs->fHostname, cs->fPort, fullord,
cs->fPerfIdx, cs->fImage, kPROOF_WorkDir);
fSlaves->Add(slave);
if (slave->IsValid()) {
fAllMonitor->Add(slave->GetSocket());
PDB(kGlobal,3)
Info("StartSlaves", "slave on host %s created and added to list (port %d)",
cs->fHostname.Data(),cs->fPort);
} else {
fBadSlaves->Add(slave);
PDB(kGlobal,3)
Info("StartSlaves", "slave on host %s created and added to list of bad slaves (port %d)",
cs->fHostname.Data(),cs->fPort);
}
}
//create and start heartbeat timer
fHeartbeatTimer = new TTimer;
fHeartbeatTimer->Connect("Timeout()", "TProofPEAC", this, "SendHeartbeat()");
fHeartbeatTimer->Start(fHBPeriod*1000, kFALSE);
} else {
return TProof::StartSlaves(kTRUE);
}
return kTRUE;
}
//______________________________________________________________________________
void TProofPEAC::Close(Option_t *option)
{
TProof::Close(option);
if (fLM) {
delete fHeartbeatTimer;
fHeartbeatTimer = 0;
fLM->EndSession(fSession);
delete fLM;
fLM = 0;
}
}
//______________________________________________________________________________
void TProofPEAC::SetActive(Bool_t active)
{
// Suspend or resume PROOF via Condor.
if (fCondor) {
if (fTimer == 0) {
fTimer = new TTimer();
}
if (active) {
PDB(kCondor,1) Info("SetActive","-- Condor Resume --");
fTimer->Stop();
if (fCondor->GetState() == TCondor::kSuspended)
fCondor->Resume();
} else {
Int_t delay = 10000; // milli seconds
PDB(kCondor,1) Info("SetActive","-- Delayed Condor Suspend (%d msec) --", delay);
fTimer->Connect("Timeout()", "TCondor", fCondor, "Suspend()");
fTimer->Start(10000, kTRUE); // single shot
}
}
}
//______________________________________________________________________________
TString TProofPEAC::GetJobAd()
{
TString ad;
ad = "JobUniverse = 5\n"; // vanilla
ad += Form("Cmd = \"%s/bin/proofd\"\n", GetConfDir());
ad += "Iwd = \"/tmp\"\n";
ad += "In = \"/dev/null\"\n";
ad += "Out = \"/tmp/proofd.out.$(Port)\"\n";
ad += "Err = \"/tmp/proofd.err.$(Port)\"\n";
ad += Form("Args = \"-f -p $(Port) -d %d %s\"\n", GetLogLevel(), GetConfDir());
return ad;
}
//______________________________________________________________________________
Bool_t TProofPEAC::IsDataReady(Long64_t &totalbytes, Long64_t &bytesready)
{
Bool_t dataready = kFALSE;
if (IsMaster()) {
dataready = fLM ? fLM->DataReady(fSession, bytesready, totalbytes) : kFALSE;
////// for testing
//static Long64_t total = 10;
//static Long64_t ready = -1;
//ready++;
//totalbytes=total;
//bytesready=ready;
if (totalbytes>bytesready) dataready=kFALSE;
//////
} else {
dataready = TProof::IsDataReady(totalbytes, bytesready);
}
return dataready;
}
//______________________________________________________________________________
void TProofPEAC::SendHeartbeat()
{
if (fLM) fLM->Heartbeat(fSession);
}
<commit_msg>From Chirstian Holm: fix changed CreateSlave() calling sequence.<commit_after>// @(#)root/peac:$Name: $:$Id: TProofPEAC.cxx,v 1.3 2005/05/26 13:40:07 rdm Exp $
// Author: Maarten Ballintijn 21/10/2004
// Author: Kris Gulbrandsen 21/10/2004
/*************************************************************************
* Copyright (C) 1995-2005, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TProofPEAC //
// //
// This class implements the setup of a PROOF session using PEAC //
// //
//////////////////////////////////////////////////////////////////////////
#include "TClarens.h"
#include "TCondor.h"
#include "TDSet.h"
#include "TEnv.h"
#include "TError.h"
#include "TList.h"
#include "TLM.h"
#include "TMonitor.h"
#include "TProofPEAC.h"
#include "TProofServ.h"
#include "TSlave.h"
#include "TSystem.h"
#include "TTimer.h"
#include "TUrl.h"
ClassImp(TProofPEAC)
//______________________________________________________________________________
TProofPEAC::TProofPEAC(const char *masterurl, const char *sessionid,
const char *confdir, Int_t loglevel)
: fCondor(0), fTimer(0)
{
// Start PEAC proof session
if (!strncasecmp(sessionid, "peac:", 5))
sessionid+=5;
Init(masterurl, sessionid, confdir, loglevel);
}
//______________________________________________________________________________
TProofPEAC::~TProofPEAC()
{
// Destroy PEAC proof session
delete fCondor;
delete fTimer;
if (fLM) {
delete fHeartbeatTimer;
fHeartbeatTimer = 0;
fLM->EndSession(fSession);
delete fLM;
fLM = 0;
}
}
//------------------------------------------------------------------------------
Bool_t TProofPEAC::StartSlaves()
{
if (IsMaster()) {
TClarens::Init();
const Char_t *lmUrl = gEnv->GetValue("PEAC.LmUrl",
"http://localhost:8080/clarens/");
fLM = gClarens->CreateLM(lmUrl);
if (!fLM) {
Error("StartSlaves", "Could not connect to local manager for url '%s'",
lmUrl);
return kFALSE;
}
TUrl url(lmUrl);
TString lm = url.GetHost();
Int_t lmPort = url.GetPort();
fSession = fConfFile;
PDB(kGlobal,1) Info("StartSlaves", "PEAC mode: host: %s port: %d session: %s",
lm.Data(), lmPort, fSession.Data());
TList* config = 0;
if(!fLM->StartSession(fSession, config, fHBPeriod)) {
Error("StartSlaves", "Could not start session '%s' for local manager '%s'",
fSession.Data(), lmUrl);
return kFALSE;
}
TList csl;
TIter NextSlave(config);
Int_t ord = 0;
TString jobad;
while (TLM::TSlaveParams *sp = dynamic_cast<TLM::TSlaveParams*>(NextSlave())) {
PDB(kGlobal,1) Info("StartSlaves", "node: %s", sp->fNode.Data());
// create slave server
if (sp->fType == "inetd") {
TString fullord = TString(gProofServ->GetOrdinal()) + "." + ((Long_t) ord);
ord++;
TSlave *slave = CreateSlave(sp->fNode, fullord, sp->fPerfidx, sp->fImg, kPROOF_WorkDir);
fSlaves->Add(slave);
if (slave->IsValid()) {
fAllMonitor->Add(slave->GetSocket());
PDB(kGlobal,3)
Info("StartSlaves", "slave on host %s created and added to list",
sp->fNode.Data());
} else {
fBadSlaves->Add(slave);
PDB(kGlobal,3)
Info("StartSlaves", "slave on host %s created and added to list of bad slaves",
sp->fNode.Data());
}
} else if (sp->fType == "cod") {
if (fCondor == 0) {
fCondor = new TCondor;
jobad = GetJobAd();
fImage = fCondor->GetImage(gSystem->HostName());
if (fImage.Length() == 0) {
Error("StartSlaves", "no image found for node %s",
gSystem->HostName());
delete fCondor;
fCondor = 0;
}
}
if (fCondor != 0) {
TCondorSlave *c = fCondor->Claim(sp->fNode, jobad);
if (c != 0) {
csl.Add(c);
} else {
Info("StartSlaves", "node: %s not claimed", sp->fNode.Data());
}
}
} else {
Error("StartSlaves", "unknown slave type (%s)", sp->fType.Data());
}
}
delete config;
TIter next(&csl);
TCondorSlave *cs;
while ((cs = (TCondorSlave*)next()) != 0) {
// Get slave FQDN ...
TString SlaveFqdn;
TInetAddress SlaveAddr = gSystem->GetHostByName((const char *)cs->fHostname);
if (SlaveAddr.IsValid()) {
SlaveFqdn = SlaveAddr.GetHostName();
if (SlaveFqdn == "UnNamedHost")
SlaveFqdn = SlaveAddr.GetHostAddress();
}
// who do we believe for perf & img, Condor for the moment
TString fullord = TString(gProofServ->GetOrdinal()) + "." + ((Long_t) ord);
ord++;
TSlave *slave = CreateSlave(cs->fHostname, fullord,
cs->fPerfIdx, cs->fImage, kPROOF_WorkDir);
fSlaves->Add(slave);
if (slave->IsValid()) {
fAllMonitor->Add(slave->GetSocket());
PDB(kGlobal,3)
Info("StartSlaves", "slave on host %s created and added to list (port %d)",
cs->fHostname.Data(),cs->fPort);
} else {
fBadSlaves->Add(slave);
PDB(kGlobal,3)
Info("StartSlaves", "slave on host %s created and added to list of bad slaves (port %d)",
cs->fHostname.Data(),cs->fPort);
}
}
//create and start heartbeat timer
fHeartbeatTimer = new TTimer;
fHeartbeatTimer->Connect("Timeout()", "TProofPEAC", this, "SendHeartbeat()");
fHeartbeatTimer->Start(fHBPeriod*1000, kFALSE);
} else {
return TProof::StartSlaves(kTRUE);
}
return kTRUE;
}
//______________________________________________________________________________
void TProofPEAC::Close(Option_t *option)
{
TProof::Close(option);
if (fLM) {
delete fHeartbeatTimer;
fHeartbeatTimer = 0;
fLM->EndSession(fSession);
delete fLM;
fLM = 0;
}
}
//______________________________________________________________________________
void TProofPEAC::SetActive(Bool_t active)
{
// Suspend or resume PROOF via Condor.
if (fCondor) {
if (fTimer == 0) {
fTimer = new TTimer();
}
if (active) {
PDB(kCondor,1) Info("SetActive","-- Condor Resume --");
fTimer->Stop();
if (fCondor->GetState() == TCondor::kSuspended)
fCondor->Resume();
} else {
Int_t delay = 10000; // milli seconds
PDB(kCondor,1) Info("SetActive","-- Delayed Condor Suspend (%d msec) --", delay);
fTimer->Connect("Timeout()", "TCondor", fCondor, "Suspend()");
fTimer->Start(10000, kTRUE); // single shot
}
}
}
//______________________________________________________________________________
TString TProofPEAC::GetJobAd()
{
TString ad;
ad = "JobUniverse = 5\n"; // vanilla
ad += Form("Cmd = \"%s/bin/proofd\"\n", GetConfDir());
ad += "Iwd = \"/tmp\"\n";
ad += "In = \"/dev/null\"\n";
ad += "Out = \"/tmp/proofd.out.$(Port)\"\n";
ad += "Err = \"/tmp/proofd.err.$(Port)\"\n";
ad += Form("Args = \"-f -p $(Port) -d %d %s\"\n", GetLogLevel(), GetConfDir());
return ad;
}
//______________________________________________________________________________
Bool_t TProofPEAC::IsDataReady(Long64_t &totalbytes, Long64_t &bytesready)
{
Bool_t dataready = kFALSE;
if (IsMaster()) {
dataready = fLM ? fLM->DataReady(fSession, bytesready, totalbytes) : kFALSE;
////// for testing
//static Long64_t total = 10;
//static Long64_t ready = -1;
//ready++;
//totalbytes=total;
//bytesready=ready;
if (totalbytes>bytesready) dataready=kFALSE;
//////
} else {
dataready = TProof::IsDataReady(totalbytes, bytesready);
}
return dataready;
}
//______________________________________________________________________________
void TProofPEAC::SendHeartbeat()
{
if (fLM) fLM->Heartbeat(fSession);
}
<|endoftext|> |
<commit_before>/*
* This file is part of vaporpp.
*
* vaporpp 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.
*
* vaporpp 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 vaporpp. If not, see <http://www.gnu.org/licenses/>.
*/
#include "rgba_color.hpp"
#include <stdexcept>
#include <cctype>
//private function to convert two hex-characters to a byte:
uint8_t hex_to_byte(char highbyte, char lowbyte);
vlpp::rgba_color::rgba_color(uint8_t R, uint8_t G, uint8_t B, uint8_t A):
r(R), g(G), b(B), alpha(A)
{}
vlpp::rgba_color::rgba_color(std::string colorcode) {
if (!colorcode.empty() && colorcode[0] == '#') {
colorcode.erase(0,1);
}
switch (colorcode.length()) {
case 8:
alpha = hex_to_byte(colorcode[6], colorcode[7]);
//fallthrough
case 6:
r = hex_to_byte(colorcode[0], colorcode[1]);
g = hex_to_byte(colorcode[2], colorcode[3]);
b = hex_to_byte(colorcode[4], colorcode[5]);
break;
default
:
throw std::invalid_argument("invalid colorcode");
}
}
uint8_t hex_to_byte(char highbyte, char lowbyte) {
if (!isxdigit(highbyte) || !isxdigit(lowbyte)) {
throw std::invalid_argument("invalid colorcode");
}
uint8_t returnval = 0;
if (isdigit(highbyte)) {
returnval = ((unsigned char)highbyte - '0') * 0x10;
}
else {
returnval = (10 + (unsigned char)highbyte -'a') * 0x10;
}
if (isdigit(lowbyte)) {
returnval += (lowbyte - '0');
}
else {
returnval += (10 + lowbyte -'a');
}
return returnval;
}
<commit_msg>bugfix for hexconversion<commit_after>/*
* This file is part of vaporpp.
*
* vaporpp 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.
*
* vaporpp 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 vaporpp. If not, see <http://www.gnu.org/licenses/>.
*/
#include "rgba_color.hpp"
#include <stdexcept>
#include <cctype>
//private function to convert two hex-characters to a byte:
uint8_t hex_to_byte(char highbyte, char lowbyte);
vlpp::rgba_color::rgba_color(uint8_t R, uint8_t G, uint8_t B, uint8_t A):
r(R), g(G), b(B), alpha(A)
{}
vlpp::rgba_color::rgba_color(std::string colorcode) {
if (!colorcode.empty() && colorcode[0] == '#') {
colorcode.erase(0,1);
}
switch (colorcode.length()) {
case 8:
alpha = hex_to_byte(colorcode[6], colorcode[7]);
//fallthrough
case 6:
r = hex_to_byte(colorcode[0], colorcode[1]);
g = hex_to_byte(colorcode[2], colorcode[3]);
b = hex_to_byte(colorcode[4], colorcode[5]);
break;
default
:
throw std::invalid_argument("invalid colorcode");
}
}
uint8_t hex_to_byte(char highbyte, char lowbyte) {
if (!isxdigit(highbyte) || !isxdigit(lowbyte)) {
throw std::invalid_argument("invalid colorcode");
}
uint8_t returnval = 0;
if (isdigit(highbyte)) {
returnval = ((unsigned char)highbyte - '0') * 0x10;
}
else {
returnval = (10 + (unsigned char)tolower(highbyte) -'a') * 0x10;
}
if (isdigit(lowbyte)) {
returnval += (lowbyte - '0');
}
else {
returnval += (10 + tolower(lowbyte) -'a');
}
return returnval;
}
<|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 "SampleCode.h"
#include "SkView.h"
#include "SkCanvas.h"
#include "SkTime.h"
#include "SkInterpolator.h"
extern bool is_overview(SkView* view);
static const char gIsTransitionQuery[] = "is-transition";
static const char gReplaceTransitionEvt[] = "replace-transition-view";
static bool is_transition(SkView* view) {
SkEvent isTransition(gIsTransitionQuery);
return view->doQuery(&isTransition);
}
class TransitionView : public SampleView {
public:
TransitionView(SkView* prev, SkView* next, int direction) : fInterp(4, 2){
fAnimationDirection = (Direction)(1 << (direction % 8));
fPrev = prev;
fPrev->setClipToBounds(false);
fPrev->setVisibleP(true);
(void)SampleView::SetUsePipe(fPrev, SkOSMenu::kOffState);
//Not calling unref because fPrev is assumed to have been created, so
//this will result in a transfer of ownership
this->attachChildToBack(fPrev);
fNext = next;
fNext->setClipToBounds(true);
fNext->setVisibleP(true);
(void)SampleView::SetUsePipe(fNext, SkOSMenu::kOffState);
//Calling unref because next is a newly created view and TransitionView
//is now the sole owner of fNext
this->attachChildToFront(fNext)->unref();
fDone = false;
//SkDebugf("--created transition\n");
}
~TransitionView(){
//SkDebugf("--deleted transition\n");
}
virtual void requestMenu(SkOSMenu* menu) {
if (SampleView::IsSampleView(fNext))
((SampleView*)fNext)->requestMenu(menu);
}
protected:
virtual bool onQuery(SkEvent* evt) {
if (SampleCode::TitleQ(*evt)) {
SkString title;
if (SampleCode::RequestTitle(fNext, &title)) {
SampleCode::TitleR(evt, title.c_str());
return true;
}
return false;
}
if (evt->isType(gIsTransitionQuery)) {
return true;
}
return this->INHERITED::onQuery(evt);
}
virtual bool onEvent(const SkEvent& evt) {
if (evt.isType(gReplaceTransitionEvt)) {
fPrev->detachFromParent();
fPrev = (SkView*)SkEventSink::FindSink(evt.getFast32());
(void)SampleView::SetUsePipe(fPrev, SkOSMenu::kOffState);
//attach the new fPrev and call unref to balance the ref in onDraw
this->attachChildToBack(fPrev)->unref();
this->inval(NULL);
return true;
}
if (evt.isType("transition-done")) {
fNext->setLoc(0, 0);
fNext->setClipToBounds(false);
SkEvent* evt = new SkEvent(gReplaceTransitionEvt,
this->getParent()->getSinkID());
evt->setFast32(fNext->getSinkID());
//increate ref count of fNext so it survives detachAllChildren
fNext->ref();
this->detachAllChildren();
evt->post();
return true;
}
return this->INHERITED::onEvent(evt);
}
virtual void onDrawBackground(SkCanvas* canvas) {}
virtual void onDrawContent(SkCanvas* canvas) {
if (fDone)
return;
if (is_overview(fNext) || is_overview(fPrev)) {
fPipeState = SkOSMenu::kOffState;
}
SkScalar values[4];
SkInterpolator::Result result = fInterp.timeToValues(SkTime::GetMSecs(), values);
//SkDebugf("transition %x %d pipe:%d\n", this, result, fUsePipe);
//SkDebugf("%f %f %f %f %d\n", values[0], values[1], values[2], values[3], result);
if (SkInterpolator::kNormal_Result == result) {
fPrev->setLocX(values[kPrevX]);
fPrev->setLocY(values[kPrevY]);
fNext->setLocX(values[kNextX]);
fNext->setLocY(values[kNextY]);
this->inval(NULL);
}
else {
(new SkEvent("transition-done", this->getSinkID()))->post();
fDone = true;
}
}
virtual void onSizeChange() {
this->INHERITED::onSizeChange();
fNext->setSize(this->width(), this->height());
fPrev->setSize(this->width(), this->height());
SkScalar lr = 0, ud = 0;
if (fAnimationDirection & (kLeftDirection|kULDirection|kDLDirection))
lr = this->width();
if (fAnimationDirection & (kRightDirection|kURDirection|kDRDirection))
lr = -this->width();
if (fAnimationDirection & (kUpDirection|kULDirection|kURDirection))
ud = this->height();
if (fAnimationDirection & (kDownDirection|kDLDirection|kDRDirection))
ud = -this->height();
fBegin[kPrevX] = fBegin[kPrevY] = 0;
fBegin[kNextX] = lr;
fBegin[kNextY] = ud;
fNext->setLocX(lr);
fNext->setLocY(ud);
if (is_transition(fPrev))
lr = ud = 0;
fEnd[kPrevX] = -lr;
fEnd[kPrevY] = -ud;
fEnd[kNextX] = fEnd[kNextY] = 0;
SkScalar blend[] = { SkFloatToScalar(0.8f), SkFloatToScalar(0.0f),
SkFloatToScalar(0.0f), SK_Scalar1 };
fInterp.setKeyFrame(0, SkTime::GetMSecs(), fBegin, blend);
fInterp.setKeyFrame(1, SkTime::GetMSecs()+500, fEnd, blend);
}
private:
enum {
kPrevX = 0,
kPrevY = 1,
kNextX = 2,
kNextY = 3
};
SkView* fPrev;
SkView* fNext;
bool fDone;
SkInterpolator fInterp;
enum Direction{
kUpDirection = 1,
kURDirection = 1 << 1,
kRightDirection = 1 << 2,
kDRDirection = 1 << 3,
kDownDirection = 1 << 4,
kDLDirection = 1 << 5,
kLeftDirection = 1 << 6,
kULDirection = 1 << 7
};
Direction fAnimationDirection;
SkScalar fBegin[4];
SkScalar fEnd[4];
typedef SampleView INHERITED;
};
// FIXME: this should go in a header
SkView* create_transition(SkView* prev, SkView* next, int direction);
SkView* create_transition(SkView* prev, SkView* next, int direction) {
return SkNEW_ARGS(TransitionView, (prev, next, direction));
};
<commit_msg>change duration of transition animation to 1, effectively removing it (for now)<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 "SampleCode.h"
#include "SkView.h"
#include "SkCanvas.h"
#include "SkTime.h"
#include "SkInterpolator.h"
extern bool is_overview(SkView* view);
static const char gIsTransitionQuery[] = "is-transition";
static const char gReplaceTransitionEvt[] = "replace-transition-view";
static bool is_transition(SkView* view) {
SkEvent isTransition(gIsTransitionQuery);
return view->doQuery(&isTransition);
}
class TransitionView : public SampleView {
enum {
// kDurationMS = 500
kDurationMS = 1
};
public:
TransitionView(SkView* prev, SkView* next, int direction) : fInterp(4, 2){
fAnimationDirection = (Direction)(1 << (direction % 8));
fPrev = prev;
fPrev->setClipToBounds(false);
fPrev->setVisibleP(true);
(void)SampleView::SetUsePipe(fPrev, SkOSMenu::kOffState);
//Not calling unref because fPrev is assumed to have been created, so
//this will result in a transfer of ownership
this->attachChildToBack(fPrev);
fNext = next;
fNext->setClipToBounds(true);
fNext->setVisibleP(true);
(void)SampleView::SetUsePipe(fNext, SkOSMenu::kOffState);
//Calling unref because next is a newly created view and TransitionView
//is now the sole owner of fNext
this->attachChildToFront(fNext)->unref();
fDone = false;
//SkDebugf("--created transition\n");
}
~TransitionView(){
//SkDebugf("--deleted transition\n");
}
virtual void requestMenu(SkOSMenu* menu) {
if (SampleView::IsSampleView(fNext))
((SampleView*)fNext)->requestMenu(menu);
}
protected:
virtual bool onQuery(SkEvent* evt) {
if (SampleCode::TitleQ(*evt)) {
SkString title;
if (SampleCode::RequestTitle(fNext, &title)) {
SampleCode::TitleR(evt, title.c_str());
return true;
}
return false;
}
if (evt->isType(gIsTransitionQuery)) {
return true;
}
return this->INHERITED::onQuery(evt);
}
virtual bool onEvent(const SkEvent& evt) {
if (evt.isType(gReplaceTransitionEvt)) {
fPrev->detachFromParent();
fPrev = (SkView*)SkEventSink::FindSink(evt.getFast32());
(void)SampleView::SetUsePipe(fPrev, SkOSMenu::kOffState);
//attach the new fPrev and call unref to balance the ref in onDraw
this->attachChildToBack(fPrev)->unref();
this->inval(NULL);
return true;
}
if (evt.isType("transition-done")) {
fNext->setLoc(0, 0);
fNext->setClipToBounds(false);
SkEvent* evt = new SkEvent(gReplaceTransitionEvt,
this->getParent()->getSinkID());
evt->setFast32(fNext->getSinkID());
//increate ref count of fNext so it survives detachAllChildren
fNext->ref();
this->detachAllChildren();
evt->post();
return true;
}
return this->INHERITED::onEvent(evt);
}
virtual void onDrawBackground(SkCanvas* canvas) {}
virtual void onDrawContent(SkCanvas* canvas) {
if (fDone)
return;
if (is_overview(fNext) || is_overview(fPrev)) {
fPipeState = SkOSMenu::kOffState;
}
SkScalar values[4];
SkInterpolator::Result result = fInterp.timeToValues(SkTime::GetMSecs(), values);
//SkDebugf("transition %x %d pipe:%d\n", this, result, fUsePipe);
//SkDebugf("%f %f %f %f %d\n", values[0], values[1], values[2], values[3], result);
if (SkInterpolator::kNormal_Result == result) {
fPrev->setLocX(values[kPrevX]);
fPrev->setLocY(values[kPrevY]);
fNext->setLocX(values[kNextX]);
fNext->setLocY(values[kNextY]);
this->inval(NULL);
}
else {
(new SkEvent("transition-done", this->getSinkID()))->post();
fDone = true;
}
}
virtual void onSizeChange() {
this->INHERITED::onSizeChange();
fNext->setSize(this->width(), this->height());
fPrev->setSize(this->width(), this->height());
SkScalar lr = 0, ud = 0;
if (fAnimationDirection & (kLeftDirection|kULDirection|kDLDirection))
lr = this->width();
if (fAnimationDirection & (kRightDirection|kURDirection|kDRDirection))
lr = -this->width();
if (fAnimationDirection & (kUpDirection|kULDirection|kURDirection))
ud = this->height();
if (fAnimationDirection & (kDownDirection|kDLDirection|kDRDirection))
ud = -this->height();
fBegin[kPrevX] = fBegin[kPrevY] = 0;
fBegin[kNextX] = lr;
fBegin[kNextY] = ud;
fNext->setLocX(lr);
fNext->setLocY(ud);
if (is_transition(fPrev))
lr = ud = 0;
fEnd[kPrevX] = -lr;
fEnd[kPrevY] = -ud;
fEnd[kNextX] = fEnd[kNextY] = 0;
SkScalar blend[] = { SkFloatToScalar(0.8f), SkFloatToScalar(0.0f),
SkFloatToScalar(0.0f), SK_Scalar1 };
fInterp.setKeyFrame(0, SkTime::GetMSecs(), fBegin, blend);
fInterp.setKeyFrame(1, SkTime::GetMSecs()+kDurationMS, fEnd, blend);
}
private:
enum {
kPrevX = 0,
kPrevY = 1,
kNextX = 2,
kNextY = 3
};
SkView* fPrev;
SkView* fNext;
bool fDone;
SkInterpolator fInterp;
enum Direction{
kUpDirection = 1,
kURDirection = 1 << 1,
kRightDirection = 1 << 2,
kDRDirection = 1 << 3,
kDownDirection = 1 << 4,
kDLDirection = 1 << 5,
kLeftDirection = 1 << 6,
kULDirection = 1 << 7
};
Direction fAnimationDirection;
SkScalar fBegin[4];
SkScalar fEnd[4];
typedef SampleView INHERITED;
};
// FIXME: this should go in a header
SkView* create_transition(SkView* prev, SkView* next, int direction);
SkView* create_transition(SkView* prev, SkView* next, int direction) {
return SkNEW_ARGS(TransitionView, (prev, next, direction));
};
<|endoftext|> |
<commit_before>
auto test_internal_system::utilities::printData(_In_ const float* data, _In_ const int dataSize)->void {
/*
No input checking
*/
std::cout << "Begining dump of memory at address: " << &data << std::endl;
for (int i{ 0 }; i != dataSize; ++i)
std::cout << "data[" << i << "] " << data[i] << " at address " << &data[i] << std::endl;
std::cout << "End of memory dump" << std::endl;
}<commit_msg>Delete TestUtilities.inl<commit_after><|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: mtrindlg.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-08 21:37:49 $
*
* 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 SC_MTRINDLG_HXX
#define SC_MTRINDLG_HXX
#ifndef _SV_DIALOG_HXX //autogen
#include <vcl/dialog.hxx>
#endif
#ifndef _SV_FIELD_HXX //autogen
#include <vcl/field.hxx>
#endif
#ifndef _SV_BUTTON_HXX //autogen
#include <vcl/imagebtn.hxx>
#endif
#ifndef _SV_FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif
//------------------------------------------------------------------------
class ScMetricInputDlg : public ModalDialog
{
public:
ScMetricInputDlg( Window* pParent,
USHORT nResId, // Ableitung fuer jeden Dialog!
long nCurrent,
long nDefault,
FieldUnit eFUnit = FUNIT_MM,
USHORT nDecimals = 2,
long nMaximum = 1000,
long nMinimum = 0,
long nFirst = 1,
long nLast = 100 );
~ScMetricInputDlg();
long GetInputValue( FieldUnit eUnit = FUNIT_TWIP ) const;
private:
FixedText aFtEditTitle;
MetricField aEdValue;
CheckBox aBtnDefVal;
OKButton aBtnOk;
CancelButton aBtnCancel;
HelpButton aBtnHelp;
long nDefaultValue;
long nCurrentValue;
void CalcPositions();
DECL_LINK( SetDefValHdl, CheckBox * );
DECL_LINK( ModifyHdl, MetricField * );
};
#endif // SC_MTRINDLG_HXX
<commit_msg>INTEGRATION: CWS changefileheader (1.3.700); FILE MERGED 2008/04/01 15:30:56 thb 1.3.700.2: #i85898# Stripping all external header guards 2008/03/31 17:15:43 rt 1.3.700.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: mtrindlg.hxx,v $
* $Revision: 1.4 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef SC_MTRINDLG_HXX
#define SC_MTRINDLG_HXX
#include <vcl/dialog.hxx>
#include <vcl/field.hxx>
#include <vcl/imagebtn.hxx>
#include <vcl/fixed.hxx>
//------------------------------------------------------------------------
class ScMetricInputDlg : public ModalDialog
{
public:
ScMetricInputDlg( Window* pParent,
USHORT nResId, // Ableitung fuer jeden Dialog!
long nCurrent,
long nDefault,
FieldUnit eFUnit = FUNIT_MM,
USHORT nDecimals = 2,
long nMaximum = 1000,
long nMinimum = 0,
long nFirst = 1,
long nLast = 100 );
~ScMetricInputDlg();
long GetInputValue( FieldUnit eUnit = FUNIT_TWIP ) const;
private:
FixedText aFtEditTitle;
MetricField aEdValue;
CheckBox aBtnDefVal;
OKButton aBtnOk;
CancelButton aBtnCancel;
HelpButton aBtnHelp;
long nDefaultValue;
long nCurrentValue;
void CalcPositions();
DECL_LINK( SetDefValHdl, CheckBox * );
DECL_LINK( ModifyHdl, MetricField * );
};
#endif // SC_MTRINDLG_HXX
<|endoftext|> |
<commit_before>/*************************************************************************/
/* split_container.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2018 Godot Engine contributors (cf. AUTHORS.md) */
/* */
/* 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 "split_container.h"
#include "label.h"
#include "margin_container.h"
Control *SplitContainer::_getch(int p_idx) const {
int idx = 0;
for (int i = 0; i < get_child_count(); i++) {
Control *c = Object::cast_to<Control>(get_child(i));
if (!c || !c->is_visible_in_tree())
continue;
if (c->is_set_as_toplevel())
continue;
if (idx == p_idx)
return c;
idx++;
}
return NULL;
}
void SplitContainer::_resort() {
int axis = vertical ? 1 : 0;
Control *first = _getch(0);
Control *second = _getch(1);
// If we have only one element
if (!first || !second) {
if (first) {
fit_child_in_rect(first, Rect2(Point2(), get_size()));
} else if (second) {
fit_child_in_rect(second, Rect2(Point2(), get_size()));
}
return;
}
// Determine expanded children
bool first_expanded = (vertical ? first->get_v_size_flags() : first->get_h_size_flags()) & SIZE_EXPAND;
bool second_expanded = (vertical ? second->get_v_size_flags() : second->get_h_size_flags()) & SIZE_EXPAND;
// Determine the separation between items
Ref<Texture> g = get_icon("grabber");
int sep = get_constant("separation");
sep = (dragger_visibility != DRAGGER_HIDDEN_COLLAPSED) ? MAX(sep, vertical ? g->get_height() : g->get_width()) : 0;
// Compute the minimum size
Size2 ms_first = first->get_combined_minimum_size();
Size2 ms_second = second->get_combined_minimum_size();
// Compute the separator position without the split offset
float ratio = first->get_stretch_ratio() / (first->get_stretch_ratio() + second->get_stretch_ratio());
int no_offset_middle_sep = 0;
if (first_expanded && second_expanded) {
no_offset_middle_sep = get_size()[axis] * ratio - sep / 2;
} else if (first_expanded) {
no_offset_middle_sep = get_size()[axis] - ms_second[axis] - sep;
} else {
no_offset_middle_sep = ms_first[axis];
}
// Compute the final middle separation
int clamped_split_offset = CLAMP(split_offset, ms_first[axis] - no_offset_middle_sep, (get_size()[axis] - ms_second[axis] - sep) - no_offset_middle_sep);
middle_sep = no_offset_middle_sep + clamped_split_offset;
if (!collapsed && should_clamp_split_offset) {
split_offset = clamped_split_offset;
_change_notify("split_offset");
should_clamp_split_offset = false;
}
if (vertical) {
fit_child_in_rect(first, Rect2(Point2(0, 0), Size2(get_size().width, middle_sep)));
int sofs = middle_sep + sep;
fit_child_in_rect(second, Rect2(Point2(0, sofs), Size2(get_size().width, get_size().height - sofs)));
} else {
fit_child_in_rect(first, Rect2(Point2(0, 0), Size2(middle_sep, get_size().height)));
int sofs = middle_sep + sep;
fit_child_in_rect(second, Rect2(Point2(sofs, 0), Size2(get_size().width - sofs, get_size().height)));
}
update();
}
Size2 SplitContainer::get_minimum_size() const {
/* Calculate MINIMUM SIZE */
Size2i minimum;
Ref<Texture> g = get_icon("grabber");
int sep = get_constant("separation");
sep = (dragger_visibility != DRAGGER_HIDDEN_COLLAPSED) ? MAX(sep, vertical ? g->get_height() : g->get_width()) : 0;
for (int i = 0; i < 2; i++) {
if (!_getch(i))
break;
if (i == 1) {
if (vertical)
minimum.height += sep;
else
minimum.width += sep;
}
Size2 ms = _getch(i)->get_combined_minimum_size();
if (vertical) {
minimum.height += ms.height;
minimum.width = MAX(minimum.width, ms.width);
} else {
minimum.width += ms.width;
minimum.height = MAX(minimum.height, ms.height);
}
}
return minimum;
}
void SplitContainer::_notification(int p_what) {
switch (p_what) {
case NOTIFICATION_SORT_CHILDREN: {
_resort();
} break;
case NOTIFICATION_MOUSE_ENTER: {
mouse_inside = true;
update();
} break;
case NOTIFICATION_MOUSE_EXIT: {
mouse_inside = false;
update();
} break;
case NOTIFICATION_DRAW: {
if (!_getch(0) || !_getch(1))
return;
if (collapsed || (!mouse_inside && get_constant("autohide")))
return;
int sep = dragger_visibility != DRAGGER_HIDDEN_COLLAPSED ? get_constant("separation") : 0;
Ref<Texture> tex = get_icon("grabber");
Size2 size = get_size();
if (dragger_visibility == DRAGGER_VISIBLE) {
if (vertical)
draw_texture(tex, Point2i((size.x - tex->get_width()) / 2, middle_sep + (sep - tex->get_height()) / 2));
else
draw_texture(tex, Point2i(middle_sep + (sep - tex->get_width()) / 2, (size.y - tex->get_height()) / 2));
}
} break;
}
}
void SplitContainer::_gui_input(const Ref<InputEvent> &p_event) {
if (collapsed || !_getch(0) || !_getch(1) || dragger_visibility != DRAGGER_VISIBLE)
return;
Ref<InputEventMouseButton> mb = p_event;
if (mb.is_valid()) {
if (mb->get_button_index() == BUTTON_LEFT) {
if (mb->is_pressed()) {
int sep = get_constant("separation");
if (vertical) {
if (mb->get_position().y > middle_sep && mb->get_position().y < middle_sep + sep) {
dragging = true;
drag_from = mb->get_position().y;
drag_ofs = split_offset;
}
} else {
if (mb->get_position().x > middle_sep && mb->get_position().x < middle_sep + sep) {
dragging = true;
drag_from = mb->get_position().x;
drag_ofs = split_offset;
}
}
} else {
dragging = false;
}
}
}
Ref<InputEventMouseMotion> mm = p_event;
if (mm.is_valid() && dragging) {
split_offset = drag_ofs + ((vertical ? mm->get_position().y : mm->get_position().x) - drag_from);
should_clamp_split_offset = true;
queue_sort();
emit_signal("dragged", get_split_offset());
}
}
Control::CursorShape SplitContainer::get_cursor_shape(const Point2 &p_pos) const {
if (dragging)
return (vertical ? CURSOR_VSIZE : CURSOR_HSIZE);
if (!collapsed && _getch(0) && _getch(1) && dragger_visibility == DRAGGER_VISIBLE) {
int sep = get_constant("separation");
if (vertical) {
if (p_pos.y > middle_sep && p_pos.y < middle_sep + sep)
return CURSOR_VSIZE;
} else {
if (p_pos.x > middle_sep && p_pos.x < middle_sep + sep)
return CURSOR_HSIZE;
}
}
return Control::get_cursor_shape(p_pos);
}
void SplitContainer::set_split_offset(int p_offset) {
if (split_offset == p_offset)
return;
split_offset = p_offset;
queue_sort();
}
int SplitContainer::get_split_offset() const {
return split_offset;
}
void SplitContainer::clamp_split_offset() {
should_clamp_split_offset = true;
queue_sort();
}
void SplitContainer::set_collapsed(bool p_collapsed) {
if (collapsed == p_collapsed)
return;
collapsed = p_collapsed;
queue_sort();
}
void SplitContainer::set_dragger_visibility(DraggerVisibility p_visibility) {
dragger_visibility = p_visibility;
queue_sort();
update();
}
SplitContainer::DraggerVisibility SplitContainer::get_dragger_visibility() const {
return dragger_visibility;
}
bool SplitContainer::is_collapsed() const {
return collapsed;
}
void SplitContainer::_bind_methods() {
ClassDB::bind_method(D_METHOD("_gui_input"), &SplitContainer::_gui_input);
ClassDB::bind_method(D_METHOD("set_split_offset", "offset"), &SplitContainer::set_split_offset);
ClassDB::bind_method(D_METHOD("get_split_offset"), &SplitContainer::get_split_offset);
ClassDB::bind_method(D_METHOD("clamp_split_offset"), &SplitContainer::clamp_split_offset);
ClassDB::bind_method(D_METHOD("set_collapsed", "collapsed"), &SplitContainer::set_collapsed);
ClassDB::bind_method(D_METHOD("is_collapsed"), &SplitContainer::is_collapsed);
ClassDB::bind_method(D_METHOD("set_dragger_visibility", "mode"), &SplitContainer::set_dragger_visibility);
ClassDB::bind_method(D_METHOD("get_dragger_visibility"), &SplitContainer::get_dragger_visibility);
ADD_SIGNAL(MethodInfo("dragged", PropertyInfo(Variant::INT, "offset")));
ADD_PROPERTY(PropertyInfo(Variant::INT, "split_offset"), "set_split_offset", "get_split_offset");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "collapsed"), "set_collapsed", "is_collapsed");
ADD_PROPERTY(PropertyInfo(Variant::INT, "dragger_visibility", PROPERTY_HINT_ENUM, "Visible,Hidden,Hidden & Collapsed"), "set_dragger_visibility", "get_dragger_visibility");
BIND_ENUM_CONSTANT(DRAGGER_VISIBLE);
BIND_ENUM_CONSTANT(DRAGGER_HIDDEN);
BIND_ENUM_CONSTANT(DRAGGER_HIDDEN_COLLAPSED);
}
SplitContainer::SplitContainer(bool p_vertical) {
mouse_inside = false;
split_offset = 0;
should_clamp_split_offset = false;
middle_sep = 0;
vertical = p_vertical;
dragging = false;
collapsed = false;
dragger_visibility = DRAGGER_VISIBLE;
}
<commit_msg>Fixes collapsed SplitContainers<commit_after>/*************************************************************************/
/* split_container.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2018 Godot Engine contributors (cf. AUTHORS.md) */
/* */
/* 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 "split_container.h"
#include "label.h"
#include "margin_container.h"
Control *SplitContainer::_getch(int p_idx) const {
int idx = 0;
for (int i = 0; i < get_child_count(); i++) {
Control *c = Object::cast_to<Control>(get_child(i));
if (!c || !c->is_visible_in_tree())
continue;
if (c->is_set_as_toplevel())
continue;
if (idx == p_idx)
return c;
idx++;
}
return NULL;
}
void SplitContainer::_resort() {
int axis = vertical ? 1 : 0;
Control *first = _getch(0);
Control *second = _getch(1);
// If we have only one element
if (!first || !second) {
if (first) {
fit_child_in_rect(first, Rect2(Point2(), get_size()));
} else if (second) {
fit_child_in_rect(second, Rect2(Point2(), get_size()));
}
return;
}
// Determine expanded children
bool first_expanded = (vertical ? first->get_v_size_flags() : first->get_h_size_flags()) & SIZE_EXPAND;
bool second_expanded = (vertical ? second->get_v_size_flags() : second->get_h_size_flags()) & SIZE_EXPAND;
// Determine the separation between items
Ref<Texture> g = get_icon("grabber");
int sep = get_constant("separation");
sep = (dragger_visibility != DRAGGER_HIDDEN_COLLAPSED) ? MAX(sep, vertical ? g->get_height() : g->get_width()) : 0;
// Compute the minimum size
Size2 ms_first = first->get_combined_minimum_size();
Size2 ms_second = second->get_combined_minimum_size();
// Compute the separator position without the split offset
float ratio = first->get_stretch_ratio() / (first->get_stretch_ratio() + second->get_stretch_ratio());
int no_offset_middle_sep = 0;
if (first_expanded && second_expanded) {
no_offset_middle_sep = get_size()[axis] * ratio - sep / 2;
} else if (first_expanded) {
no_offset_middle_sep = get_size()[axis] - ms_second[axis] - sep;
} else {
no_offset_middle_sep = ms_first[axis];
}
// Compute the final middle separation
middle_sep = no_offset_middle_sep;
if (!collapsed) {
int clamped_split_offset = CLAMP(split_offset, ms_first[axis] - no_offset_middle_sep, (get_size()[axis] - ms_second[axis] - sep) - no_offset_middle_sep);
middle_sep += clamped_split_offset;
if (should_clamp_split_offset) {
split_offset = clamped_split_offset;
_change_notify("split_offset");
should_clamp_split_offset = false;
}
}
if (vertical) {
fit_child_in_rect(first, Rect2(Point2(0, 0), Size2(get_size().width, middle_sep)));
int sofs = middle_sep + sep;
fit_child_in_rect(second, Rect2(Point2(0, sofs), Size2(get_size().width, get_size().height - sofs)));
} else {
fit_child_in_rect(first, Rect2(Point2(0, 0), Size2(middle_sep, get_size().height)));
int sofs = middle_sep + sep;
fit_child_in_rect(second, Rect2(Point2(sofs, 0), Size2(get_size().width - sofs, get_size().height)));
}
update();
}
Size2 SplitContainer::get_minimum_size() const {
/* Calculate MINIMUM SIZE */
Size2i minimum;
Ref<Texture> g = get_icon("grabber");
int sep = get_constant("separation");
sep = (dragger_visibility != DRAGGER_HIDDEN_COLLAPSED) ? MAX(sep, vertical ? g->get_height() : g->get_width()) : 0;
for (int i = 0; i < 2; i++) {
if (!_getch(i))
break;
if (i == 1) {
if (vertical)
minimum.height += sep;
else
minimum.width += sep;
}
Size2 ms = _getch(i)->get_combined_minimum_size();
if (vertical) {
minimum.height += ms.height;
minimum.width = MAX(minimum.width, ms.width);
} else {
minimum.width += ms.width;
minimum.height = MAX(minimum.height, ms.height);
}
}
return minimum;
}
void SplitContainer::_notification(int p_what) {
switch (p_what) {
case NOTIFICATION_SORT_CHILDREN: {
_resort();
} break;
case NOTIFICATION_MOUSE_ENTER: {
mouse_inside = true;
update();
} break;
case NOTIFICATION_MOUSE_EXIT: {
mouse_inside = false;
update();
} break;
case NOTIFICATION_DRAW: {
if (!_getch(0) || !_getch(1))
return;
if (collapsed || (!mouse_inside && get_constant("autohide")))
return;
int sep = dragger_visibility != DRAGGER_HIDDEN_COLLAPSED ? get_constant("separation") : 0;
Ref<Texture> tex = get_icon("grabber");
Size2 size = get_size();
if (dragger_visibility == DRAGGER_VISIBLE) {
if (vertical)
draw_texture(tex, Point2i((size.x - tex->get_width()) / 2, middle_sep + (sep - tex->get_height()) / 2));
else
draw_texture(tex, Point2i(middle_sep + (sep - tex->get_width()) / 2, (size.y - tex->get_height()) / 2));
}
} break;
}
}
void SplitContainer::_gui_input(const Ref<InputEvent> &p_event) {
if (collapsed || !_getch(0) || !_getch(1) || dragger_visibility != DRAGGER_VISIBLE)
return;
Ref<InputEventMouseButton> mb = p_event;
if (mb.is_valid()) {
if (mb->get_button_index() == BUTTON_LEFT) {
if (mb->is_pressed()) {
int sep = get_constant("separation");
if (vertical) {
if (mb->get_position().y > middle_sep && mb->get_position().y < middle_sep + sep) {
dragging = true;
drag_from = mb->get_position().y;
drag_ofs = split_offset;
}
} else {
if (mb->get_position().x > middle_sep && mb->get_position().x < middle_sep + sep) {
dragging = true;
drag_from = mb->get_position().x;
drag_ofs = split_offset;
}
}
} else {
dragging = false;
}
}
}
Ref<InputEventMouseMotion> mm = p_event;
if (mm.is_valid() && dragging) {
split_offset = drag_ofs + ((vertical ? mm->get_position().y : mm->get_position().x) - drag_from);
should_clamp_split_offset = true;
queue_sort();
emit_signal("dragged", get_split_offset());
}
}
Control::CursorShape SplitContainer::get_cursor_shape(const Point2 &p_pos) const {
if (dragging)
return (vertical ? CURSOR_VSIZE : CURSOR_HSIZE);
if (!collapsed && _getch(0) && _getch(1) && dragger_visibility == DRAGGER_VISIBLE) {
int sep = get_constant("separation");
if (vertical) {
if (p_pos.y > middle_sep && p_pos.y < middle_sep + sep)
return CURSOR_VSIZE;
} else {
if (p_pos.x > middle_sep && p_pos.x < middle_sep + sep)
return CURSOR_HSIZE;
}
}
return Control::get_cursor_shape(p_pos);
}
void SplitContainer::set_split_offset(int p_offset) {
if (split_offset == p_offset)
return;
split_offset = p_offset;
queue_sort();
}
int SplitContainer::get_split_offset() const {
return split_offset;
}
void SplitContainer::clamp_split_offset() {
should_clamp_split_offset = true;
queue_sort();
}
void SplitContainer::set_collapsed(bool p_collapsed) {
if (collapsed == p_collapsed)
return;
collapsed = p_collapsed;
queue_sort();
}
void SplitContainer::set_dragger_visibility(DraggerVisibility p_visibility) {
dragger_visibility = p_visibility;
queue_sort();
update();
}
SplitContainer::DraggerVisibility SplitContainer::get_dragger_visibility() const {
return dragger_visibility;
}
bool SplitContainer::is_collapsed() const {
return collapsed;
}
void SplitContainer::_bind_methods() {
ClassDB::bind_method(D_METHOD("_gui_input"), &SplitContainer::_gui_input);
ClassDB::bind_method(D_METHOD("set_split_offset", "offset"), &SplitContainer::set_split_offset);
ClassDB::bind_method(D_METHOD("get_split_offset"), &SplitContainer::get_split_offset);
ClassDB::bind_method(D_METHOD("clamp_split_offset"), &SplitContainer::clamp_split_offset);
ClassDB::bind_method(D_METHOD("set_collapsed", "collapsed"), &SplitContainer::set_collapsed);
ClassDB::bind_method(D_METHOD("is_collapsed"), &SplitContainer::is_collapsed);
ClassDB::bind_method(D_METHOD("set_dragger_visibility", "mode"), &SplitContainer::set_dragger_visibility);
ClassDB::bind_method(D_METHOD("get_dragger_visibility"), &SplitContainer::get_dragger_visibility);
ADD_SIGNAL(MethodInfo("dragged", PropertyInfo(Variant::INT, "offset")));
ADD_PROPERTY(PropertyInfo(Variant::INT, "split_offset"), "set_split_offset", "get_split_offset");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "collapsed"), "set_collapsed", "is_collapsed");
ADD_PROPERTY(PropertyInfo(Variant::INT, "dragger_visibility", PROPERTY_HINT_ENUM, "Visible,Hidden,Hidden & Collapsed"), "set_dragger_visibility", "get_dragger_visibility");
BIND_ENUM_CONSTANT(DRAGGER_VISIBLE);
BIND_ENUM_CONSTANT(DRAGGER_HIDDEN);
BIND_ENUM_CONSTANT(DRAGGER_HIDDEN_COLLAPSED);
}
SplitContainer::SplitContainer(bool p_vertical) {
mouse_inside = false;
split_offset = 0;
should_clamp_split_offset = false;
middle_sep = 0;
vertical = p_vertical;
dragging = false;
collapsed = false;
dragger_visibility = DRAGGER_VISIBLE;
}
<|endoftext|> |
<commit_before>#pragma once
/* A trivial class to run a function at the end of a scope. */
class Finally
{
private:
std::function<void()> fun;
public:
Finally(std::function<void()> fun) : fun(fun) { }
~Finally() { fun(); }
};
<commit_msg>Add missing #include<commit_after>#pragma once
#include <functional>
/* A trivial class to run a function at the end of a scope. */
class Finally
{
private:
std::function<void()> fun;
public:
Finally(std::function<void()> fun) : fun(fun) { }
~Finally() { fun(); }
};
<|endoftext|> |
<commit_before>#ifndef TOML11_LEXER_HPP
#define TOML11_LEXER_HPP
#include "combinator.hpp"
#include <stdexcept>
#include <istream>
#include <sstream>
#include <fstream>
namespace toml
{
namespace detail
{
// these scans contents from current location in a container of char
// and extract a region that matches their own pattern.
// to see the implementation of each component, see combinator.hpp.
using lex_wschar = either<character<' '>, character<'\t'>>;
using lex_ws = repeat<lex_wschar, at_least<1>>;
using lex_newline = either<character<'\n'>,
sequence<character<'\r'>, character<'\n'>>>;
using lex_lower = in_range<'a', 'z'>;
using lex_upper = in_range<'A', 'Z'>;
using lex_alpha = either<lex_lower, lex_upper>;
using lex_digit = in_range<'0', '9'>;
using lex_nonzero = in_range<'1', '9'>;
using lex_oct_dig = in_range<'0', '7'>;
using lex_bin_dig = in_range<'0', '1'>;
using lex_hex_dig = either<lex_digit, in_range<'A', 'F'>, in_range<'a', 'f'>>;
using lex_hex_prefix = sequence<character<'0'>, character<'x'>>;
using lex_oct_prefix = sequence<character<'0'>, character<'o'>>;
using lex_bin_prefix = sequence<character<'0'>, character<'b'>>;
using lex_underscore = character<'_'>;
using lex_plus = character<'+'>;
using lex_minus = character<'-'>;
using lex_sign = either<lex_plus, lex_minus>;
// digit | nonzero 1*(digit | _ digit)
using lex_unsigned_dec_int = either<sequence<lex_nonzero, repeat<
either<lex_digit, sequence<lex_underscore, lex_digit>>, at_least<1>>>,
lex_digit>;
// (+|-)? unsigned_dec_int
using lex_dec_int = sequence<maybe<lex_sign>, lex_unsigned_dec_int>;
// hex_prefix hex_dig *(hex_dig | _ hex_dig)
using lex_hex_int = sequence<lex_hex_prefix, sequence<lex_hex_dig, repeat<
either<lex_hex_dig, sequence<lex_underscore, lex_hex_dig>>, unlimited>>>;
// oct_prefix oct_dig *(oct_dig | _ oct_dig)
using lex_oct_int = sequence<lex_oct_prefix, sequence<lex_oct_dig, repeat<
either<lex_oct_dig, sequence<lex_underscore, lex_oct_dig>>, unlimited>>>;
// bin_prefix bin_dig *(bin_dig | _ bin_dig)
using lex_bin_int = sequence<lex_bin_prefix, sequence<lex_bin_dig, repeat<
either<lex_bin_dig, sequence<lex_underscore, lex_bin_dig>>, unlimited>>>;
// (dec_int | hex_int | oct_int | bin_int)
using lex_integer = either<lex_bin_int, lex_oct_int, lex_hex_int, lex_dec_int>;
// ===========================================================================
using lex_inf = sequence<character<'i'>, character<'n'>, character<'f'>>;
using lex_nan = sequence<character<'n'>, character<'a'>, character<'n'>>;
using lex_special_float = sequence<maybe<lex_sign>, either<lex_inf, lex_nan>>;
using lex_exponent_part = sequence<either<character<'e'>, character<'E'>>, lex_dec_int>;
using lex_zero_prefixable_int = sequence<lex_digit, repeat<either<lex_digit,
sequence<lex_underscore, lex_digit>>, unlimited>>;
using lex_fractional_part = sequence<character<'.'>, lex_zero_prefixable_int>;
using lex_float = either<lex_special_float,
sequence<lex_dec_int, either<lex_exponent_part,
sequence<lex_fractional_part, maybe<lex_exponent_part>>>>>;
// ===========================================================================
using lex_true = sequence<character<'t'>, character<'r'>,
character<'u'>, character<'e'>>;
using lex_false = sequence<character<'f'>, character<'a'>, character<'l'>,
character<'s'>, character<'e'>>;
using lex_boolean = either<lex_true, lex_false>;
// ===========================================================================
using lex_date_fullyear = repeat<lex_digit, exactly<4>>;
using lex_date_month = repeat<lex_digit, exactly<2>>;
using lex_date_mday = repeat<lex_digit, exactly<2>>;
using lex_time_delim = either<character<'T'>, character<'t'>, character<' '>>;
using lex_time_hour = repeat<lex_digit, exactly<2>>;
using lex_time_minute = repeat<lex_digit, exactly<2>>;
using lex_time_second = repeat<lex_digit, exactly<2>>;
using lex_time_secfrac = sequence<character<'.'>,
repeat<lex_digit, at_least<1>>>;
using lex_time_numoffset = sequence<either<character<'+'>, character<'-'>>,
sequence<lex_time_hour, character<':'>,
lex_time_minute>>;
using lex_time_offset = either<character<'Z'>, character<'z'>,
lex_time_numoffset>;
using lex_partial_time = sequence<lex_time_hour, character<':'>,
lex_time_minute, character<':'>,
lex_time_second, maybe<lex_time_secfrac>>;
using lex_full_date = sequence<lex_date_fullyear, character<'-'>,
lex_date_month, character<'-'>,
lex_date_mday>;
using lex_full_time = sequence<lex_partial_time, lex_time_offset>;
using lex_offset_date_time = sequence<lex_full_date, lex_time_delim, lex_full_time>;
using lex_local_date_time = sequence<lex_full_date, lex_time_delim, lex_partial_time>;
using lex_local_date = lex_full_date;
using lex_local_time = lex_partial_time;
// ===========================================================================
using lex_quotation_mark = character<'"'>;
using lex_basic_unescaped = exclude<either<in_range<0x00, 0x1F>,
character<0x22>, character<0x5C>,
character<0x7F>>>;
using lex_escape = character<'\\'>;
using lex_escape_seq_char = either<character<'"'>, character<'\\'>,
character<'/'>, character<'b'>,
character<'f'>, character<'n'>,
character<'r'>, character<'t'>,
sequence<character<'u'>,
repeat<lex_hex_dig, exactly<4>>>,
sequence<character<'U'>,
repeat<lex_hex_dig, exactly<8>>>
>;
using lex_escaped = sequence<lex_escape, lex_escape_seq_char>;
using lex_basic_char = either<lex_basic_unescaped, lex_escaped>;
using lex_basic_string = sequence<lex_quotation_mark,
repeat<lex_basic_char, unlimited>,
lex_quotation_mark>;
using lex_ml_basic_string_delim = repeat<lex_quotation_mark, exactly<3>>;
using lex_ml_basic_unescaped = exclude<either<in_range<0x00, 0x1F>,
character<0x5C>,
character<0x7F>,
lex_ml_basic_string_delim>>;
using lex_ml_basic_escaped_newline = sequence<
lex_escape, maybe<lex_ws>, lex_newline,
repeat<either<lex_ws, lex_newline>, unlimited>>;
using lex_ml_basic_char = either<lex_ml_basic_unescaped, lex_escaped>;
using lex_ml_basic_body = repeat<either<lex_ml_basic_char, lex_newline,
lex_ml_basic_escaped_newline>,
unlimited>;
using lex_ml_basic_string = sequence<lex_ml_basic_string_delim,
lex_ml_basic_body,
lex_ml_basic_string_delim>;
using lex_literal_char = exclude<either<in_range<0x00, 0x08>,
in_range<0x10, 0x19>, character<0x27>>>;
using lex_apostrophe = character<'\''>;
using lex_literal_string = sequence<lex_apostrophe,
repeat<lex_literal_char, unlimited>,
lex_apostrophe>;
using lex_ml_literal_string_delim = repeat<lex_apostrophe, exactly<3>>;
using lex_ml_literal_char = exclude<either<in_range<0x00, 0x08>,
in_range<0x10, 0x1F>,
character<0x7F>,
lex_ml_literal_string_delim>>;
using lex_ml_literal_body = repeat<either<lex_ml_literal_char, lex_newline>,
unlimited>;
using lex_ml_literal_string = sequence<lex_ml_literal_string_delim,
lex_ml_literal_body,
lex_ml_literal_string_delim>;
using lex_string = either<lex_ml_basic_string, lex_basic_string,
lex_ml_literal_string, lex_literal_string>;
// ===========================================================================
using lex_comment_start_symbol = character<'#'>;
using lex_non_eol = either<character<'\t'>, exclude<in_range<0x00, 0x19>>>;
using lex_comment = sequence<lex_comment_start_symbol,
repeat<lex_non_eol, unlimited>>;
using lex_dot_sep = sequence<maybe<lex_ws>, character<'.'>, maybe<lex_ws>>;
using lex_unquoted_key = repeat<either<lex_alpha, lex_digit,
character<'-'>, character<'_'>>,
at_least<1>>;
using lex_quoted_key = either<lex_basic_string, lex_literal_string>;
using lex_simple_key = either<lex_unquoted_key, lex_quoted_key>;
using lex_dotted_key = sequence<lex_simple_key,
repeat<sequence<lex_dot_sep, lex_simple_key>,
at_least<1>>
>;
using lex_key = either<lex_dotted_key, lex_simple_key>;
using lex_keyval_sep = sequence<maybe<lex_ws>,
character<'='>,
maybe<lex_ws>>;
using lex_std_table_open = character<'['>;
using lex_std_table_close = character<']'>;
using lex_std_table = sequence<lex_std_table_open,
lex_key,
lex_std_table_close>;
using lex_array_table_open = sequence<lex_std_table_open, lex_std_table_open>;
using lex_array_table_close = sequence<lex_std_table_close, lex_std_table_close>;
using lex_array_table = sequence<lex_array_table_open,
lex_key,
lex_array_table_close>;
} // detail
} // toml
#endif // TOML_LEXER_HPP
<commit_msg>add whitespace between [] and key<commit_after>#ifndef TOML11_LEXER_HPP
#define TOML11_LEXER_HPP
#include "combinator.hpp"
#include <stdexcept>
#include <istream>
#include <sstream>
#include <fstream>
namespace toml
{
namespace detail
{
// these scans contents from current location in a container of char
// and extract a region that matches their own pattern.
// to see the implementation of each component, see combinator.hpp.
using lex_wschar = either<character<' '>, character<'\t'>>;
using lex_ws = repeat<lex_wschar, at_least<1>>;
using lex_newline = either<character<'\n'>,
sequence<character<'\r'>, character<'\n'>>>;
using lex_lower = in_range<'a', 'z'>;
using lex_upper = in_range<'A', 'Z'>;
using lex_alpha = either<lex_lower, lex_upper>;
using lex_digit = in_range<'0', '9'>;
using lex_nonzero = in_range<'1', '9'>;
using lex_oct_dig = in_range<'0', '7'>;
using lex_bin_dig = in_range<'0', '1'>;
using lex_hex_dig = either<lex_digit, in_range<'A', 'F'>, in_range<'a', 'f'>>;
using lex_hex_prefix = sequence<character<'0'>, character<'x'>>;
using lex_oct_prefix = sequence<character<'0'>, character<'o'>>;
using lex_bin_prefix = sequence<character<'0'>, character<'b'>>;
using lex_underscore = character<'_'>;
using lex_plus = character<'+'>;
using lex_minus = character<'-'>;
using lex_sign = either<lex_plus, lex_minus>;
// digit | nonzero 1*(digit | _ digit)
using lex_unsigned_dec_int = either<sequence<lex_nonzero, repeat<
either<lex_digit, sequence<lex_underscore, lex_digit>>, at_least<1>>>,
lex_digit>;
// (+|-)? unsigned_dec_int
using lex_dec_int = sequence<maybe<lex_sign>, lex_unsigned_dec_int>;
// hex_prefix hex_dig *(hex_dig | _ hex_dig)
using lex_hex_int = sequence<lex_hex_prefix, sequence<lex_hex_dig, repeat<
either<lex_hex_dig, sequence<lex_underscore, lex_hex_dig>>, unlimited>>>;
// oct_prefix oct_dig *(oct_dig | _ oct_dig)
using lex_oct_int = sequence<lex_oct_prefix, sequence<lex_oct_dig, repeat<
either<lex_oct_dig, sequence<lex_underscore, lex_oct_dig>>, unlimited>>>;
// bin_prefix bin_dig *(bin_dig | _ bin_dig)
using lex_bin_int = sequence<lex_bin_prefix, sequence<lex_bin_dig, repeat<
either<lex_bin_dig, sequence<lex_underscore, lex_bin_dig>>, unlimited>>>;
// (dec_int | hex_int | oct_int | bin_int)
using lex_integer = either<lex_bin_int, lex_oct_int, lex_hex_int, lex_dec_int>;
// ===========================================================================
using lex_inf = sequence<character<'i'>, character<'n'>, character<'f'>>;
using lex_nan = sequence<character<'n'>, character<'a'>, character<'n'>>;
using lex_special_float = sequence<maybe<lex_sign>, either<lex_inf, lex_nan>>;
using lex_exponent_part = sequence<either<character<'e'>, character<'E'>>, lex_dec_int>;
using lex_zero_prefixable_int = sequence<lex_digit, repeat<either<lex_digit,
sequence<lex_underscore, lex_digit>>, unlimited>>;
using lex_fractional_part = sequence<character<'.'>, lex_zero_prefixable_int>;
using lex_float = either<lex_special_float,
sequence<lex_dec_int, either<lex_exponent_part,
sequence<lex_fractional_part, maybe<lex_exponent_part>>>>>;
// ===========================================================================
using lex_true = sequence<character<'t'>, character<'r'>,
character<'u'>, character<'e'>>;
using lex_false = sequence<character<'f'>, character<'a'>, character<'l'>,
character<'s'>, character<'e'>>;
using lex_boolean = either<lex_true, lex_false>;
// ===========================================================================
using lex_date_fullyear = repeat<lex_digit, exactly<4>>;
using lex_date_month = repeat<lex_digit, exactly<2>>;
using lex_date_mday = repeat<lex_digit, exactly<2>>;
using lex_time_delim = either<character<'T'>, character<'t'>, character<' '>>;
using lex_time_hour = repeat<lex_digit, exactly<2>>;
using lex_time_minute = repeat<lex_digit, exactly<2>>;
using lex_time_second = repeat<lex_digit, exactly<2>>;
using lex_time_secfrac = sequence<character<'.'>,
repeat<lex_digit, at_least<1>>>;
using lex_time_numoffset = sequence<either<character<'+'>, character<'-'>>,
sequence<lex_time_hour, character<':'>,
lex_time_minute>>;
using lex_time_offset = either<character<'Z'>, character<'z'>,
lex_time_numoffset>;
using lex_partial_time = sequence<lex_time_hour, character<':'>,
lex_time_minute, character<':'>,
lex_time_second, maybe<lex_time_secfrac>>;
using lex_full_date = sequence<lex_date_fullyear, character<'-'>,
lex_date_month, character<'-'>,
lex_date_mday>;
using lex_full_time = sequence<lex_partial_time, lex_time_offset>;
using lex_offset_date_time = sequence<lex_full_date, lex_time_delim, lex_full_time>;
using lex_local_date_time = sequence<lex_full_date, lex_time_delim, lex_partial_time>;
using lex_local_date = lex_full_date;
using lex_local_time = lex_partial_time;
// ===========================================================================
using lex_quotation_mark = character<'"'>;
using lex_basic_unescaped = exclude<either<in_range<0x00, 0x1F>,
character<0x22>, character<0x5C>,
character<0x7F>>>;
using lex_escape = character<'\\'>;
using lex_escape_seq_char = either<character<'"'>, character<'\\'>,
character<'/'>, character<'b'>,
character<'f'>, character<'n'>,
character<'r'>, character<'t'>,
sequence<character<'u'>,
repeat<lex_hex_dig, exactly<4>>>,
sequence<character<'U'>,
repeat<lex_hex_dig, exactly<8>>>
>;
using lex_escaped = sequence<lex_escape, lex_escape_seq_char>;
using lex_basic_char = either<lex_basic_unescaped, lex_escaped>;
using lex_basic_string = sequence<lex_quotation_mark,
repeat<lex_basic_char, unlimited>,
lex_quotation_mark>;
using lex_ml_basic_string_delim = repeat<lex_quotation_mark, exactly<3>>;
using lex_ml_basic_unescaped = exclude<either<in_range<0x00, 0x1F>,
character<0x5C>,
character<0x7F>,
lex_ml_basic_string_delim>>;
using lex_ml_basic_escaped_newline = sequence<
lex_escape, maybe<lex_ws>, lex_newline,
repeat<either<lex_ws, lex_newline>, unlimited>>;
using lex_ml_basic_char = either<lex_ml_basic_unescaped, lex_escaped>;
using lex_ml_basic_body = repeat<either<lex_ml_basic_char, lex_newline,
lex_ml_basic_escaped_newline>,
unlimited>;
using lex_ml_basic_string = sequence<lex_ml_basic_string_delim,
lex_ml_basic_body,
lex_ml_basic_string_delim>;
using lex_literal_char = exclude<either<in_range<0x00, 0x08>,
in_range<0x10, 0x19>, character<0x27>>>;
using lex_apostrophe = character<'\''>;
using lex_literal_string = sequence<lex_apostrophe,
repeat<lex_literal_char, unlimited>,
lex_apostrophe>;
using lex_ml_literal_string_delim = repeat<lex_apostrophe, exactly<3>>;
using lex_ml_literal_char = exclude<either<in_range<0x00, 0x08>,
in_range<0x10, 0x1F>,
character<0x7F>,
lex_ml_literal_string_delim>>;
using lex_ml_literal_body = repeat<either<lex_ml_literal_char, lex_newline>,
unlimited>;
using lex_ml_literal_string = sequence<lex_ml_literal_string_delim,
lex_ml_literal_body,
lex_ml_literal_string_delim>;
using lex_string = either<lex_ml_basic_string, lex_basic_string,
lex_ml_literal_string, lex_literal_string>;
// ===========================================================================
using lex_comment_start_symbol = character<'#'>;
using lex_non_eol = either<character<'\t'>, exclude<in_range<0x00, 0x19>>>;
using lex_comment = sequence<lex_comment_start_symbol,
repeat<lex_non_eol, unlimited>>;
using lex_dot_sep = sequence<maybe<lex_ws>, character<'.'>, maybe<lex_ws>>;
using lex_unquoted_key = repeat<either<lex_alpha, lex_digit,
character<'-'>, character<'_'>>,
at_least<1>>;
using lex_quoted_key = either<lex_basic_string, lex_literal_string>;
using lex_simple_key = either<lex_unquoted_key, lex_quoted_key>;
using lex_dotted_key = sequence<lex_simple_key,
repeat<sequence<lex_dot_sep, lex_simple_key>,
at_least<1>
>
>;
using lex_key = either<lex_dotted_key, lex_simple_key>;
using lex_keyval_sep = sequence<maybe<lex_ws>,
character<'='>,
maybe<lex_ws>>;
using lex_std_table_open = character<'['>;
using lex_std_table_close = character<']'>;
using lex_std_table = sequence<lex_std_table_open,
maybe<lex_ws>,
lex_key,
maybe<lex_ws>,
lex_std_table_close>;
using lex_array_table_open = sequence<lex_std_table_open, lex_std_table_open>;
using lex_array_table_close = sequence<lex_std_table_close, lex_std_table_close>;
using lex_array_table = sequence<lex_array_table_open,
maybe<lex_ws>,
lex_key,
maybe<lex_ws>,
lex_array_table_close>;
} // detail
} // toml
#endif // TOML_LEXER_HPP
<|endoftext|> |
<commit_before>/*
* ModSecurity, http://www.modsecurity.org/
* Copyright (c) 2015 Trustwave Holdings, Inc. (http://www.trustwave.com/)
*
* 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
*
* If any of the files related to licensing are missing or if you have any
* other questions related to licensing please contact Trustwave Holdings, Inc.
* directly using the email address security@modsecurity.org.
*
*/
#include <memory>
#include "src/macro_expansion.h"
#include "modsecurity/transaction.h"
#include "modsecurity/collection/variable.h"
#include "src/variables/rule.h"
#include "src/variables/tx.h"
#include "src/variables/highest_severity.h"
#include "src/utils/string.h"
namespace modsecurity {
MacroExpansion::MacroExpansion() { }
std::string MacroExpansion::expandKeepOriginal(const std::string& input,
Transaction *transaction) {
std::string a = MacroExpansion::expand(input, transaction);
if (a != input) {
return "\"" + a + "\" (Was: " + input + ")";
}
return input;
}
std::string MacroExpansion::expand(const std::string& input,
Transaction *transaction) {
return expand(input, NULL, transaction);
}
std::string MacroExpansion::expand(const std::string& input,
modsecurity::Rule *rule, Transaction *transaction) {
std::string res;
size_t pos = input.find("%{");
if (pos != std::string::npos) {
res = input;
} else {
return input;
}
while (pos != std::string::npos) {
size_t start = pos;
size_t end = res.find("}");
if (end == std::string::npos) {
return res;
}
std::string variable(res, start + 2, end - (start + 2));
std::unique_ptr<std::string> variableValue = nullptr;
size_t collection = variable.find(".");
if (collection == std::string::npos) {
collection = variable.find(":");
}
variable = utils::string::toupper(variable);
if (collection == std::string::npos) {
if (variable == "ARGS_NAMES") {
variableValue = transaction->m_variableArgsNames.resolveFirst();
}
else if (variable == "ARGS_GET_NAMES") {
variableValue = transaction->m_variableArgGetNames.resolveFirst();
}
else if (variable == "ARGS_POST_NAMES") {
variableValue = transaction->m_variableArgPostNames.resolveFirst();
}
else if (variable == "REQUEST_HEADERS_NAMES") {
variableValue = transaction->m_variableRequestHeadersNames.resolveFirst();
}
else if (variable == "RESPONSE_CONTENT_TYPE") {
variableValue = transaction->m_variableResponseContentType.resolveFirst();
}
else if (variable == "RESPONSE_HEADERS_NAMES") {
variableValue = transaction->m_variableResponseHeadersNames.resolveFirst();
}
else if (variable == "ARGS_COMBINED_SIZE") {
variableValue = transaction->m_variableARGScombinedSize.resolveFirst();
}
else if (variable == "AUTH_TYPE") {
variableValue = transaction->m_variableAuthType.resolveFirst();
}
else if (variable == "FILES_COMBINED_SIZE") {
variableValue = transaction->m_variableFilesCombinedSize.resolveFirst();
}
else if (variable == "FULL_REQUEST") {
variableValue = transaction->m_variableFullRequest.resolveFirst();
}
else if (variable == "FULL_REQUEST_LENGTH") {
variableValue = transaction->m_variableFullRequestLength.resolveFirst();
}
else if (variable == "INBOUND_DATA_ERROR") {
variableValue = transaction->m_variableInboundDataError.resolveFirst();
}
else if (variable == "MATCHED_VAR") {
variableValue = transaction->m_variableMatchedVar.resolveFirst();
}
else if (variable == "MATCHED_VAR_NAME") {
variableValue = transaction->m_variableMatchedVarName.resolveFirst();
}
else if (variable == "MULTIPART_CRLF_LF_LINES") {
variableValue = transaction->m_variableMultipartCrlfLFLines.resolveFirst();
}
else if (variable == "MULTIPART_DATA_AFTER") {
variableValue = transaction->m_variableMultipartDataAfter.resolveFirst();
}
else if (variable == "MULTIPART_FILE_LIMIT_EXCEEDED") {
variableValue = transaction->m_variableMultipartFileLimitExceeded.resolveFirst();
}
else if (variable == "MULTIPART_STRICT_ERROR") {
variableValue = transaction->m_variableMultipartStrictError.resolveFirst();
}
else if (variable == "MULTIPART_HEADER_FOLDING") {
variableValue = transaction->m_variableMultipartHeaderFolding.resolveFirst();
}
else if (variable == "MULTIPART_INVALID_QUOTING") {
variableValue = transaction->m_variableMultipartInvalidQuoting.resolveFirst();
}
else if (variable == "MULTIPART_INVALID_HEADER_FOLDING") {
variableValue = transaction->m_variableMultipartInvalidHeaderFolding.resolveFirst();
}
else if (variable == "MULTIPART_UNMATCHED_BOUNDARY") {
variableValue = transaction->m_variableMultipartUnmatchedBoundary.resolveFirst();
}
else if (variable == "OUTBOUND_DATA_ERROR") {
variableValue = transaction->m_variableOutboundDataError.resolveFirst();
}
else if (variable == "PATH_INFO") {
variableValue = transaction->m_variablePathInfo.resolveFirst();
}
else if (variable == "QUERY_STRING") {
variableValue = transaction->m_variableQueryString.resolveFirst();
}
else if (variable == "REMOTE_ADDR") {
variableValue = transaction->m_variableRemoteAddr.resolveFirst();
}
else if (variable == "REMOTE_HOST") {
variableValue = transaction->m_variableRemoteHost.resolveFirst();
}
else if (variable == "REMOTE_PORT") {
variableValue = transaction->m_variableRemotePort.resolveFirst();
}
else if (variable == "REQBODY_ERROR") {
variableValue = transaction->m_variableReqbodyError.resolveFirst();
}
else if (variable == "REQBODY_ERROR_MSG") {
variableValue = transaction->m_variableReqbodyErrorMsg.resolveFirst();
}
else if (variable == "REQBODY_PROCESSOR_ERROR_MSG") {
variableValue = transaction->m_variableReqbodyProcessorErrorMsg.resolveFirst();
}
else if (variable == "REQBODY_PROCESSOR_ERROR") {
variableValue = transaction->m_variableReqbodyProcessorError.resolveFirst();
}
else if (variable == "REQBODY_PROCESSOR") {
variableValue = transaction->m_variableReqbodyProcessor.resolveFirst();
}
else if (variable == "REQUEST_BASENAME") {
variableValue = transaction->m_variableRequestBasename.resolveFirst();
}
else if (variable == "REQUEST_BODY") {
variableValue = transaction->m_variableRequestBody.resolveFirst();
}
else if (variable == "REQUEST_BODY_LENGTH") {
variableValue = transaction->m_variableRequestBodyLength.resolveFirst();
}
else if (variable == "REQUEST_FILENAME") {
variableValue = transaction->m_variableRequestFilename.resolveFirst();
}
else if (variable == "REQUEST_LINE") {
variableValue = transaction->m_variableRequestLine.resolveFirst();
}
else if (variable == "REQUEST_METHOD") {
variableValue = transaction->m_variableRequestMethod.resolveFirst();
}
else if (variable == "REQUEST_PROTOCOL") {
variableValue = transaction->m_variableRequestProtocol.resolveFirst();
}
else if (variable == "REQUEST_URI") {
variableValue = transaction->m_variableRequestURI.resolveFirst();
}
else if (variable == "REQUEST_URI_RAW") {
variableValue = transaction->m_variableRequestURIRaw.resolveFirst();
}
else if (variable == "RESOURCE") {
variableValue = transaction->m_variableResource.resolveFirst();
}
else if (variable == "RESPONSE_BODY") {
variableValue = transaction->m_variableResponseBody.resolveFirst();
}
else if (variable == "RESPONSE_CONTENT_LENGTH") {
variableValue = transaction->m_variableResponseContentLength.resolveFirst();
}
else if (variable == "RESPONSE_PROTOCOL") {
variableValue = transaction->m_variableResponseProtocol.resolveFirst();
}
else if (variable == "RESPONSE_STATUS") {
variableValue = transaction->m_variableResponseStatus.resolveFirst();
}
else if (variable == "SERVER_ADDR") {
variableValue = transaction->m_variableServerAddr.resolveFirst();
}
else if (variable == "SERVER_NAME") {
variableValue = transaction->m_variableServerName.resolveFirst();
}
else if (variable == "SERVER_PORT") {
variableValue = transaction->m_variableServerPort.resolveFirst();
}
else if (variable == "SESSIONID") {
variableValue = transaction->m_variableSessionID.resolveFirst();
}
else if (variable == "UNIQUE_ID") {
variableValue = transaction->m_variableUniqueID.resolveFirst();
}
else if (variable == "URLENCODED_ERROR") {
variableValue = transaction->m_variableUrlEncodedError.resolveFirst();
}
else if (variable == "USERID") {
variableValue = transaction->m_variableUserID.resolveFirst();
} else {
variableValue = transaction->m_collections.resolveFirst(
variable);
}
} else {
std::string col = std::string(variable, 0, collection);
std::string var = std::string(variable, collection + 1,
variable.length() - (collection + 1));
col = utils::string::toupper(col);
if (col == "ARGS") {
variableValue = transaction->m_variableArgs.resolveFirst(var);
}
else if (col == "RULE") {
variableValue = transaction->m_variableRule.resolveFirst(var);
}
else if (col == "ARGS_GET") {
variableValue = transaction->m_variableArgsGet.resolveFirst(var);
}
else if (col == "ARGS_POST") {
variableValue = transaction->m_variableArgsPost.resolveFirst(var);
}
else if (col == "FILES_SIZES") {
variableValue = transaction->m_variableFilesSizes.resolveFirst(var);
}
else if (col == "FILES_NAMES") {
variableValue = transaction->m_variableFilesNames.resolveFirst(var);
}
else if (col == "FILES_TMP_CONTENT") {
variableValue = transaction->m_variableFilesTmpContent.resolveFirst(var);
}
else if (col == "MULTIPART_FILENAME") {
variableValue = transaction->m_variableMultiPartFileName.resolveFirst(var);
}
else if (col == "MULTIPART_NAME") {
variableValue = transaction->m_variableMultiPartName.resolveFirst(var);
}
else if (col == "MATCHED_VARS_NAMES") {
variableValue = transaction->m_variableMatchedVarsNames.resolveFirst(var);
}
else if (col == "MATCHED_VARS") {
variableValue = transaction->m_variableMatchedVars.resolveFirst(var);
}
else if (col == "FILES") {
variableValue = transaction->m_variableFiles.resolveFirst(var);
}
else if (col == "REQUEST_COOKIES") {
variableValue = transaction->m_variableRequestCookies.resolveFirst(var);
}
else if (col == "REQUEST_HEADERS") {
variableValue = transaction->m_variableRequestHeaders.resolveFirst(var);
}
else if (col == "RESPONSE_HEADERS") {
variableValue = transaction->m_variableResponseHeaders.resolveFirst(var);
}
else if (col == "GEO") {
variableValue = transaction->m_variableGeo.resolveFirst(var);
}
else if (col == "REQUEST_COOKIES_NAMES") {
variableValue = transaction->m_variableRequestCookiesNames.resolveFirst(var);
}
else if (col == "FILES_TMPNAMES") {
variableValue = transaction->m_variableFilesTmpNames.resolveFirst(var);
} else {
variableValue = transaction->m_collections.resolveFirst(col,
var);
}
}
if (variableValue) {
transaction->debug(6, "Resolving: " + variable + " to: " +
*variableValue);
} else {
transaction->debug(6, "Resolving: " + variable + " to: NULL");
}
res.erase(start, end - start + 1);
if (res[start] == '%') {
res.erase(start, 1);
}
if (variableValue != NULL) {
res.insert(start, *variableValue);
}
pos = res.find("%{");
}
return res;
}
} // namespace modsecurity
<commit_msg>Avoids call `toupper' twice while resolving a variable<commit_after>/*
* ModSecurity, http://www.modsecurity.org/
* Copyright (c) 2015 Trustwave Holdings, Inc. (http://www.trustwave.com/)
*
* 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
*
* If any of the files related to licensing are missing or if you have any
* other questions related to licensing please contact Trustwave Holdings, Inc.
* directly using the email address security@modsecurity.org.
*
*/
#include <memory>
#include "src/macro_expansion.h"
#include "modsecurity/transaction.h"
#include "modsecurity/collection/variable.h"
#include "src/variables/rule.h"
#include "src/variables/tx.h"
#include "src/variables/highest_severity.h"
#include "src/utils/string.h"
namespace modsecurity {
MacroExpansion::MacroExpansion() { }
std::string MacroExpansion::expandKeepOriginal(const std::string& input,
Transaction *transaction) {
std::string a = MacroExpansion::expand(input, transaction);
if (a != input) {
return "\"" + a + "\" (Was: " + input + ")";
}
return input;
}
std::string MacroExpansion::expand(const std::string& input,
Transaction *transaction) {
return expand(input, NULL, transaction);
}
std::string MacroExpansion::expand(const std::string& input,
modsecurity::Rule *rule, Transaction *transaction) {
std::string res;
size_t pos = input.find("%{");
if (pos != std::string::npos) {
res = input;
} else {
return input;
}
while (pos != std::string::npos) {
size_t start = pos;
size_t end = res.find("}");
if (end == std::string::npos) {
return res;
}
std::string variable(res, start + 2, end - (start + 2));
std::unique_ptr<std::string> variableValue = nullptr;
size_t collection = variable.find(".");
if (collection == std::string::npos) {
collection = variable.find(":");
}
variable = utils::string::toupper(variable);
if (collection == std::string::npos) {
if (variable == "ARGS_NAMES") {
variableValue = transaction->m_variableArgsNames.resolveFirst();
}
else if (variable == "ARGS_GET_NAMES") {
variableValue = transaction->m_variableArgGetNames.resolveFirst();
}
else if (variable == "ARGS_POST_NAMES") {
variableValue = transaction->m_variableArgPostNames.resolveFirst();
}
else if (variable == "REQUEST_HEADERS_NAMES") {
variableValue = transaction->m_variableRequestHeadersNames.resolveFirst();
}
else if (variable == "RESPONSE_CONTENT_TYPE") {
variableValue = transaction->m_variableResponseContentType.resolveFirst();
}
else if (variable == "RESPONSE_HEADERS_NAMES") {
variableValue = transaction->m_variableResponseHeadersNames.resolveFirst();
}
else if (variable == "ARGS_COMBINED_SIZE") {
variableValue = transaction->m_variableARGScombinedSize.resolveFirst();
}
else if (variable == "AUTH_TYPE") {
variableValue = transaction->m_variableAuthType.resolveFirst();
}
else if (variable == "FILES_COMBINED_SIZE") {
variableValue = transaction->m_variableFilesCombinedSize.resolveFirst();
}
else if (variable == "FULL_REQUEST") {
variableValue = transaction->m_variableFullRequest.resolveFirst();
}
else if (variable == "FULL_REQUEST_LENGTH") {
variableValue = transaction->m_variableFullRequestLength.resolveFirst();
}
else if (variable == "INBOUND_DATA_ERROR") {
variableValue = transaction->m_variableInboundDataError.resolveFirst();
}
else if (variable == "MATCHED_VAR") {
variableValue = transaction->m_variableMatchedVar.resolveFirst();
}
else if (variable == "MATCHED_VAR_NAME") {
variableValue = transaction->m_variableMatchedVarName.resolveFirst();
}
else if (variable == "MULTIPART_CRLF_LF_LINES") {
variableValue = transaction->m_variableMultipartCrlfLFLines.resolveFirst();
}
else if (variable == "MULTIPART_DATA_AFTER") {
variableValue = transaction->m_variableMultipartDataAfter.resolveFirst();
}
else if (variable == "MULTIPART_FILE_LIMIT_EXCEEDED") {
variableValue = transaction->m_variableMultipartFileLimitExceeded.resolveFirst();
}
else if (variable == "MULTIPART_STRICT_ERROR") {
variableValue = transaction->m_variableMultipartStrictError.resolveFirst();
}
else if (variable == "MULTIPART_HEADER_FOLDING") {
variableValue = transaction->m_variableMultipartHeaderFolding.resolveFirst();
}
else if (variable == "MULTIPART_INVALID_QUOTING") {
variableValue = transaction->m_variableMultipartInvalidQuoting.resolveFirst();
}
else if (variable == "MULTIPART_INVALID_HEADER_FOLDING") {
variableValue = transaction->m_variableMultipartInvalidHeaderFolding.resolveFirst();
}
else if (variable == "MULTIPART_UNMATCHED_BOUNDARY") {
variableValue = transaction->m_variableMultipartUnmatchedBoundary.resolveFirst();
}
else if (variable == "OUTBOUND_DATA_ERROR") {
variableValue = transaction->m_variableOutboundDataError.resolveFirst();
}
else if (variable == "PATH_INFO") {
variableValue = transaction->m_variablePathInfo.resolveFirst();
}
else if (variable == "QUERY_STRING") {
variableValue = transaction->m_variableQueryString.resolveFirst();
}
else if (variable == "REMOTE_ADDR") {
variableValue = transaction->m_variableRemoteAddr.resolveFirst();
}
else if (variable == "REMOTE_HOST") {
variableValue = transaction->m_variableRemoteHost.resolveFirst();
}
else if (variable == "REMOTE_PORT") {
variableValue = transaction->m_variableRemotePort.resolveFirst();
}
else if (variable == "REQBODY_ERROR") {
variableValue = transaction->m_variableReqbodyError.resolveFirst();
}
else if (variable == "REQBODY_ERROR_MSG") {
variableValue = transaction->m_variableReqbodyErrorMsg.resolveFirst();
}
else if (variable == "REQBODY_PROCESSOR_ERROR_MSG") {
variableValue = transaction->m_variableReqbodyProcessorErrorMsg.resolveFirst();
}
else if (variable == "REQBODY_PROCESSOR_ERROR") {
variableValue = transaction->m_variableReqbodyProcessorError.resolveFirst();
}
else if (variable == "REQBODY_PROCESSOR") {
variableValue = transaction->m_variableReqbodyProcessor.resolveFirst();
}
else if (variable == "REQUEST_BASENAME") {
variableValue = transaction->m_variableRequestBasename.resolveFirst();
}
else if (variable == "REQUEST_BODY") {
variableValue = transaction->m_variableRequestBody.resolveFirst();
}
else if (variable == "REQUEST_BODY_LENGTH") {
variableValue = transaction->m_variableRequestBodyLength.resolveFirst();
}
else if (variable == "REQUEST_FILENAME") {
variableValue = transaction->m_variableRequestFilename.resolveFirst();
}
else if (variable == "REQUEST_LINE") {
variableValue = transaction->m_variableRequestLine.resolveFirst();
}
else if (variable == "REQUEST_METHOD") {
variableValue = transaction->m_variableRequestMethod.resolveFirst();
}
else if (variable == "REQUEST_PROTOCOL") {
variableValue = transaction->m_variableRequestProtocol.resolveFirst();
}
else if (variable == "REQUEST_URI") {
variableValue = transaction->m_variableRequestURI.resolveFirst();
}
else if (variable == "REQUEST_URI_RAW") {
variableValue = transaction->m_variableRequestURIRaw.resolveFirst();
}
else if (variable == "RESOURCE") {
variableValue = transaction->m_variableResource.resolveFirst();
}
else if (variable == "RESPONSE_BODY") {
variableValue = transaction->m_variableResponseBody.resolveFirst();
}
else if (variable == "RESPONSE_CONTENT_LENGTH") {
variableValue = transaction->m_variableResponseContentLength.resolveFirst();
}
else if (variable == "RESPONSE_PROTOCOL") {
variableValue = transaction->m_variableResponseProtocol.resolveFirst();
}
else if (variable == "RESPONSE_STATUS") {
variableValue = transaction->m_variableResponseStatus.resolveFirst();
}
else if (variable == "SERVER_ADDR") {
variableValue = transaction->m_variableServerAddr.resolveFirst();
}
else if (variable == "SERVER_NAME") {
variableValue = transaction->m_variableServerName.resolveFirst();
}
else if (variable == "SERVER_PORT") {
variableValue = transaction->m_variableServerPort.resolveFirst();
}
else if (variable == "SESSIONID") {
variableValue = transaction->m_variableSessionID.resolveFirst();
}
else if (variable == "UNIQUE_ID") {
variableValue = transaction->m_variableUniqueID.resolveFirst();
}
else if (variable == "URLENCODED_ERROR") {
variableValue = transaction->m_variableUrlEncodedError.resolveFirst();
}
else if (variable == "USERID") {
variableValue = transaction->m_variableUserID.resolveFirst();
} else {
variableValue = transaction->m_collections.resolveFirst(
variable);
}
} else {
std::string col = std::string(variable, 0, collection);
std::string var = std::string(variable, collection + 1,
variable.length() - (collection + 1));
if (col == "ARGS") {
variableValue = transaction->m_variableArgs.resolveFirst(var);
}
else if (col == "RULE") {
variableValue = transaction->m_variableRule.resolveFirst(var);
}
else if (col == "ARGS_GET") {
variableValue = transaction->m_variableArgsGet.resolveFirst(var);
}
else if (col == "ARGS_POST") {
variableValue = transaction->m_variableArgsPost.resolveFirst(var);
}
else if (col == "FILES_SIZES") {
variableValue = transaction->m_variableFilesSizes.resolveFirst(var);
}
else if (col == "FILES_NAMES") {
variableValue = transaction->m_variableFilesNames.resolveFirst(var);
}
else if (col == "FILES_TMP_CONTENT") {
variableValue = transaction->m_variableFilesTmpContent.resolveFirst(var);
}
else if (col == "MULTIPART_FILENAME") {
variableValue = transaction->m_variableMultiPartFileName.resolveFirst(var);
}
else if (col == "MULTIPART_NAME") {
variableValue = transaction->m_variableMultiPartName.resolveFirst(var);
}
else if (col == "MATCHED_VARS_NAMES") {
variableValue = transaction->m_variableMatchedVarsNames.resolveFirst(var);
}
else if (col == "MATCHED_VARS") {
variableValue = transaction->m_variableMatchedVars.resolveFirst(var);
}
else if (col == "FILES") {
variableValue = transaction->m_variableFiles.resolveFirst(var);
}
else if (col == "REQUEST_COOKIES") {
variableValue = transaction->m_variableRequestCookies.resolveFirst(var);
}
else if (col == "REQUEST_HEADERS") {
variableValue = transaction->m_variableRequestHeaders.resolveFirst(var);
}
else if (col == "RESPONSE_HEADERS") {
variableValue = transaction->m_variableResponseHeaders.resolveFirst(var);
}
else if (col == "GEO") {
variableValue = transaction->m_variableGeo.resolveFirst(var);
}
else if (col == "REQUEST_COOKIES_NAMES") {
variableValue = transaction->m_variableRequestCookiesNames.resolveFirst(var);
}
else if (col == "FILES_TMPNAMES") {
variableValue = transaction->m_variableFilesTmpNames.resolveFirst(var);
} else {
variableValue = transaction->m_collections.resolveFirst(col,
var);
}
}
if (variableValue) {
transaction->debug(6, "Resolving: " + variable + " to: " +
*variableValue);
} else {
transaction->debug(6, "Resolving: " + variable + " to: NULL");
}
res.erase(start, end - start + 1);
if (res[start] == '%') {
res.erase(start, 1);
}
if (variableValue != NULL) {
res.insert(start, *variableValue);
}
pos = res.find("%{");
}
return res;
}
} // namespace modsecurity
<|endoftext|> |
<commit_before>// TODO Add restarting
namespace mant {
template <typename ParameterType>
class SimulatedAnnealing : public TrajectoryBasedOptimisationAlgorithm<ParameterType> {
public:
explicit SimulatedAnnealing(
const std::shared_ptr<OptimisationProblem<ParameterType>> optimisationProblem) noexcept;
void setMaximalStepSize(
const ParameterType maximalStepSize);
std::string toString() const noexcept override;
protected:
ParameterType maximalStepSize_;
virtual bool isAcceptableState(
const double candidateObjectiveValue) noexcept;
void optimiseImplementation() noexcept override;
void setDefaultMaximalStepSize(std::true_type) noexcept;
void setDefaultMaximalStepSize(std::false_type) noexcept;
};
//
// Implementation
//
template <typename ParameterType>
SimulatedAnnealing<ParameterType>::SimulatedAnnealing(
const std::shared_ptr<OptimisationProblem<ParameterType>> optimisationProblem) noexcept
: TrajectoryBasedOptimisationAlgorithm<ParameterType>(optimisationProblem) {
setDefaultMaximalStepSize(std::is_floating_point<ParameterType>());
}
template <typename ParameterType>
void SimulatedAnnealing<ParameterType>::optimiseImplementation() noexcept {
++this->numberOfIterations_;
this->bestParameter_ = this->initialParameter_;
this->bestSoftConstraintsValue_ = this->getSoftConstraintsValue(this->initialParameter_);
this->bestObjectiveValue_ = this->getObjectiveValue(this->initialParameter_);
arma::Col<double> state = this->bestParameter_;
while(!this->isFinished() && !this->isTerminated()) {
++this->numberOfIterations_;
arma::Col<ParameterType> candidateParameter = this->distanceFunction_.getRandomNeighbour(state, 0, maximalStepSize_);
const arma::Col<unsigned int>& belowLowerBound = arma::find(candidateParameter < this->getLowerBounds());
const arma::Col<unsigned int>& aboveUpperBound = arma::find(candidateParameter > this->getUpperBounds());
candidateParameter.elem(belowLowerBound) = this->getLowerBounds().elem(belowLowerBound);
candidateParameter.elem(aboveUpperBound) = this->getUpperBounds().elem(aboveUpperBound);
const double& candidateSoftConstraintsValue = this->getSoftConstraintsValue(candidateParameter);
const double& candidateObjectiveValue = this->getObjectiveValue(candidateParameter);
if(candidateSoftConstraintsValue < this->bestSoftConstraintsValue_ || (candidateSoftConstraintsValue == this->bestSoftConstraintsValue_ && candidateObjectiveValue < this->bestObjectiveValue_)) {
state = candidateParameter;
this->bestParameter_ = candidateParameter;
this->bestSoftConstraintsValue_ = candidateSoftConstraintsValue;
this->bestObjectiveValue_ = candidateObjectiveValue;
} else if(isAcceptableState(candidateObjectiveValue)) {
state = candidateParameter;
}
}
}
template <typename ParameterType>
bool SimulatedAnnealing<ParameterType>::isAcceptableState(
const double candidateObjectiveValue) noexcept {
return std::exp((this->bestObjectiveValue_ - candidateObjectiveValue) / (this->numberOfIterations_ / this->maximalNumberOfIterations_)) < std::uniform_real_distribution<double>(0.0, 1.0)(Rng::getGenerator());
}
template <typename ParameterType>
void SimulatedAnnealing<ParameterType>::setMaximalStepSize(
const ParameterType maximalStepSize) {
if (maximalStepSize <= 0) {
throw std::logic_error("The maximal step size must be strict greater than 0.");
}
maximalStepSize_ = maximalStepSize;
}
template <typename ParameterType>
std::string SimulatedAnnealing<ParameterType>::toString() const noexcept {
return "SimulatedAnnealing";
}
template <typename ParameterType>
void SimulatedAnnealing<ParameterType>::setDefaultMaximalStepSize(
std::true_type) noexcept {
setMaximalStepSize(this->distanceFunction_.getDistance(this->getLowerBounds(), this->getUpperBounds()) / 10.0);
}
template <typename ParameterType>
void SimulatedAnnealing<ParameterType>::setDefaultMaximalStepSize(
std::false_type) noexcept {
setMaximalStepSize(arma::max(1, this->distanceFunction_.getDistance(this->getLowerBounds(), this->getUpperBounds()) / 10));
}
}
<commit_msg>Fixed distanceFunction_ pointer<commit_after>// TODO Add restarting
namespace mant {
template <typename ParameterType>
class SimulatedAnnealing : public TrajectoryBasedOptimisationAlgorithm<ParameterType> {
public:
explicit SimulatedAnnealing(
const std::shared_ptr<OptimisationProblem<ParameterType>> optimisationProblem) noexcept;
void setMaximalStepSize(
const ParameterType maximalStepSize);
std::string toString() const noexcept override;
protected:
ParameterType maximalStepSize_;
virtual bool isAcceptableState(
const double candidateObjectiveValue) noexcept;
void optimiseImplementation() noexcept override;
void setDefaultMaximalStepSize(std::true_type) noexcept;
void setDefaultMaximalStepSize(std::false_type) noexcept;
};
//
// Implementation
//
template <typename ParameterType>
SimulatedAnnealing<ParameterType>::SimulatedAnnealing(
const std::shared_ptr<OptimisationProblem<ParameterType>> optimisationProblem) noexcept
: TrajectoryBasedOptimisationAlgorithm<ParameterType>(optimisationProblem) {
setDefaultMaximalStepSize(std::is_floating_point<ParameterType>());
}
template <typename ParameterType>
void SimulatedAnnealing<ParameterType>::optimiseImplementation() noexcept {
++this->numberOfIterations_;
this->bestParameter_ = this->initialParameter_;
this->bestSoftConstraintsValue_ = this->getSoftConstraintsValue(this->initialParameter_);
this->bestObjectiveValue_ = this->getObjectiveValue(this->initialParameter_);
arma::Col<double> state = this->bestParameter_;
while(!this->isFinished() && !this->isTerminated()) {
++this->numberOfIterations_;
arma::Col<ParameterType> candidateParameter = this->distanceFunction_->getRandomNeighbour(state, 0, maximalStepSize_);
const arma::Col<unsigned int>& belowLowerBound = arma::find(candidateParameter < this->getLowerBounds());
const arma::Col<unsigned int>& aboveUpperBound = arma::find(candidateParameter > this->getUpperBounds());
candidateParameter.elem(belowLowerBound) = this->getLowerBounds().elem(belowLowerBound);
candidateParameter.elem(aboveUpperBound) = this->getUpperBounds().elem(aboveUpperBound);
const double& candidateSoftConstraintsValue = this->getSoftConstraintsValue(candidateParameter);
const double& candidateObjectiveValue = this->getObjectiveValue(candidateParameter);
if(candidateSoftConstraintsValue < this->bestSoftConstraintsValue_ || (candidateSoftConstraintsValue == this->bestSoftConstraintsValue_ && candidateObjectiveValue < this->bestObjectiveValue_)) {
state = candidateParameter;
this->bestParameter_ = candidateParameter;
this->bestSoftConstraintsValue_ = candidateSoftConstraintsValue;
this->bestObjectiveValue_ = candidateObjectiveValue;
} else if(isAcceptableState(candidateObjectiveValue)) {
state = candidateParameter;
}
}
}
template <typename ParameterType>
bool SimulatedAnnealing<ParameterType>::isAcceptableState(
const double candidateObjectiveValue) noexcept {
return std::exp((this->bestObjectiveValue_ - candidateObjectiveValue) / (this->numberOfIterations_ / this->maximalNumberOfIterations_)) < std::uniform_real_distribution<double>(0.0, 1.0)(Rng::getGenerator());
}
template <typename ParameterType>
void SimulatedAnnealing<ParameterType>::setMaximalStepSize(
const ParameterType maximalStepSize) {
if (maximalStepSize <= 0) {
throw std::logic_error("The maximal step size must be strict greater than 0.");
}
maximalStepSize_ = maximalStepSize;
}
template <typename ParameterType>
std::string SimulatedAnnealing<ParameterType>::toString() const noexcept {
return "SimulatedAnnealing";
}
template <typename ParameterType>
void SimulatedAnnealing<ParameterType>::setDefaultMaximalStepSize(
std::true_type) noexcept {
setMaximalStepSize(this->distanceFunction_->getDistance(this->getLowerBounds(), this->getUpperBounds()) / 10.0);
}
template <typename ParameterType>
void SimulatedAnnealing<ParameterType>::setDefaultMaximalStepSize(
std::false_type) noexcept {
setMaximalStepSize(arma::max(1, this->distanceFunction_->getDistance(this->getLowerBounds(), this->getUpperBounds()) / 10));
}
}
<|endoftext|> |
<commit_before>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
// Container class for AliGenerator through recursion.
// Container is itself an AliGenerator.
// What is stored are not the pointers to the generators directly but to objects of type
// AliGenCocktail entry.
// The class provides also iterator functionality.
// Author: andreas.morsch@cern.ch
//
#include <TList.h>
#include <TObjArray.h>
#include "AliGenCocktail.h"
#include "AliGenCocktailEntry.h"
#include "AliCollisionGeometry.h"
#include "AliRun.h"
#include "AliMC.h"
ClassImp(AliGenCocktail)
AliGenCocktail::AliGenCocktail()
:AliGenerator()
{
// Constructor
fName = "Cocktail";
fTitle= "Particle Generator using cocktail of generators";
flnk1 = 0;
flnk2 = 0;
fNGenerators=0;
fEntries = 0;
}
AliGenCocktail::AliGenCocktail(const AliGenCocktail & cocktail):
AliGenerator(cocktail)
{
// Copy constructor
cocktail.Copy(*this);
}
AliGenCocktail::~AliGenCocktail()
{
// Destructor
delete fEntries;
}
void AliGenCocktail::
AddGenerator(AliGenerator *Generator, const char* Name, Float_t RateExp)
{
//
// Add a generator to the list
// First check that list exists
if (!fEntries) fEntries = new TList();
//
// Forward parameters to the new generator
if(TestBit(kPtRange) && !(Generator->TestBit(kPtRange)) && !(Generator->TestBit(kMomentumRange)))
Generator->SetPtRange(fPtMin,fPtMax);
if(TestBit(kMomentumRange) && !(Generator->TestBit(kPtRange)) && !(Generator->TestBit(kMomentumRange)))
Generator->SetMomentumRange(fPMin,fPMax);
if (!(Generator->TestBit(kYRange)))
Generator->SetYRange(fYMin,fYMax);
if (!(Generator->TestBit(kPhiRange)))
Generator->SetPhiRange(fPhiMin*180/TMath::Pi(),fPhiMax*180/TMath::Pi());
if (!(Generator->TestBit(kThetaRange)))
Generator->SetThetaRange(fThetaMin*180/TMath::Pi(),fThetaMax*180/TMath::Pi());
if (!(Generator->TestBit(kVertexRange)))
Generator->SetOrigin(fOrigin[0], fOrigin[1], fOrigin[2]);
Generator->SetSigma(fOsigma[0], fOsigma[1], fOsigma[2]);
Generator->SetVertexSmear(fVertexSmear);
Generator->SetVertexSource(kContainer);
Generator->SetTrackingFlag(fTrackIt);
//
// Add generator to list
char theName[256];
sprintf(theName, "%s_%d",Name, fNGenerators);
Generator->SetName(theName);
AliGenCocktailEntry *entry =
new AliGenCocktailEntry(Generator, Name, RateExp);
fEntries->Add(entry);
fNGenerators++;
}
void AliGenCocktail::Init()
{
// Initialisation
TIter next(fEntries);
AliGenCocktailEntry *entry;
//
// Loop over generators and initialize
while((entry = (AliGenCocktailEntry*)next())) {
if (fStack) entry->Generator()->SetStack(fStack);
entry->Generator()->Init();
}
}
void AliGenCocktail::FinishRun()
{
// Initialisation
TIter next(fEntries);
AliGenCocktailEntry *entry;
//
// Loop over generators and initialize
while((entry = (AliGenCocktailEntry*)next())) {
entry->Generator()->FinishRun();
}
}
void AliGenCocktail::Generate()
{
//
// Generate event
TIter next(fEntries);
AliGenCocktailEntry *entry = 0;
AliGenCocktailEntry *preventry = 0;
AliGenerator* gen = 0;
TObjArray *partArray = gAlice->GetMCApp()->Particles();
//
// Generate the vertex position used by all generators
//
if(fVertexSmear == kPerEvent) Vertex();
//
// Loop over generators and generate events
Int_t igen=0;
while((entry = (AliGenCocktailEntry*)next())) {
igen++;
if (igen ==1) {
entry->SetFirst(0);
} else {
entry->SetFirst((partArray->GetEntriesFast())+1);
}
//
// Handle case in which current generator needs collision geometry from previous generator
//
gen = entry->Generator();
if (gen->NeedsCollisionGeometry())
{
if (preventry && preventry->Generator()->ProvidesCollisionGeometry())
{
gen->SetCollisionGeometry(preventry->Generator()->CollisionGeometry());
} else {
Fatal("Generate()", "No Collision Geometry Provided");
}
}
entry->Generator()->SetVertex(fVertex.At(0), fVertex.At(1), fVertex.At(2));
entry->Generator()->Generate();
entry->SetLast(partArray->GetEntriesFast());
preventry = entry;
}
next.Reset();
}
AliGenCocktailEntry * AliGenCocktail::FirstGenerator()
{
// Iterator over generators: Initialisation
flnk1 = fEntries->FirstLink();
if (flnk1) {
return (AliGenCocktailEntry*) (flnk1->GetObject());
} else {
return 0;
}
}
AliGenCocktailEntry* AliGenCocktail::NextGenerator()
{
// Iterator over generators: Increment
flnk1 = flnk1->Next();
if (flnk1) {
return (AliGenCocktailEntry*) (flnk1->GetObject());
} else {
return 0;
}
}
void AliGenCocktail::
FirstGeneratorPair(AliGenCocktailEntry*& e1, AliGenCocktailEntry*& e2)
{
// Iterator over generator pairs: Initialisation
flnk2 = flnk1 = fEntries->FirstLink();
if (flnk1) {
e2 = e1 = (AliGenCocktailEntry*) (flnk1->GetObject());
} else {
e2= e1 = 0;
}
}
void AliGenCocktail::
NextGeneratorPair(AliGenCocktailEntry*& e1, AliGenCocktailEntry*& e2)
{
// Iterator over generators: Increment
flnk2 = flnk2->Next();
if (flnk2) {
e1 = (AliGenCocktailEntry*) (flnk1->GetObject());
e2 = (AliGenCocktailEntry*) (flnk2->GetObject());
} else {
flnk2 = flnk1 = flnk1->Next();
if (flnk1) {
e1 = (AliGenCocktailEntry*) (flnk1->GetObject());
e2 = (AliGenCocktailEntry*) (flnk2->GetObject());
} else {
e1=0;
e2=0;
}
}
}
AliGenCocktail& AliGenCocktail::operator=(const AliGenCocktail& rhs)
{
// Assignment operator
rhs.Copy(*this);
return (*this);
}
void AliGenCocktail::Copy(TObject &) const
{
Fatal("Copy","Not implemented!\n");
}
<commit_msg>Adding AliGenEventHeader<commit_after>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
// Container class for AliGenerator through recursion.
// Container is itself an AliGenerator.
// What is stored are not the pointers to the generators directly but to objects of type
// AliGenCocktail entry.
// The class provides also iterator functionality.
// Author: andreas.morsch@cern.ch
//
#include <TList.h>
#include <TObjArray.h>
#include "AliGenCocktail.h"
#include "AliGenCocktailEntry.h"
#include "AliCollisionGeometry.h"
#include "AliRun.h"
#include "AliMC.h"
#include "AliGenEventHeader.h"
ClassImp(AliGenCocktail)
AliGenCocktail::AliGenCocktail()
:AliGenerator()
{
// Constructor
fName = "Cocktail";
fTitle= "Particle Generator using cocktail of generators";
flnk1 = 0;
flnk2 = 0;
fNGenerators=0;
fEntries = 0;
}
AliGenCocktail::AliGenCocktail(const AliGenCocktail & cocktail):
AliGenerator(cocktail)
{
// Copy constructor
cocktail.Copy(*this);
}
AliGenCocktail::~AliGenCocktail()
{
// Destructor
delete fEntries;
}
void AliGenCocktail::
AddGenerator(AliGenerator *Generator, const char* Name, Float_t RateExp)
{
//
// Add a generator to the list
// First check that list exists
if (!fEntries) fEntries = new TList();
//
// Forward parameters to the new generator
if(TestBit(kPtRange) && !(Generator->TestBit(kPtRange)) && !(Generator->TestBit(kMomentumRange)))
Generator->SetPtRange(fPtMin,fPtMax);
if(TestBit(kMomentumRange) && !(Generator->TestBit(kPtRange)) && !(Generator->TestBit(kMomentumRange)))
Generator->SetMomentumRange(fPMin,fPMax);
if (!(Generator->TestBit(kYRange)))
Generator->SetYRange(fYMin,fYMax);
if (!(Generator->TestBit(kPhiRange)))
Generator->SetPhiRange(fPhiMin*180/TMath::Pi(),fPhiMax*180/TMath::Pi());
if (!(Generator->TestBit(kThetaRange)))
Generator->SetThetaRange(fThetaMin*180/TMath::Pi(),fThetaMax*180/TMath::Pi());
if (!(Generator->TestBit(kVertexRange)))
Generator->SetOrigin(fOrigin[0], fOrigin[1], fOrigin[2]);
Generator->SetSigma(fOsigma[0], fOsigma[1], fOsigma[2]);
Generator->SetVertexSmear(fVertexSmear);
Generator->SetVertexSource(kContainer);
Generator->SetTrackingFlag(fTrackIt);
//
// Add generator to list
char theName[256];
sprintf(theName, "%s_%d",Name, fNGenerators);
Generator->SetName(theName);
AliGenCocktailEntry *entry =
new AliGenCocktailEntry(Generator, Name, RateExp);
fEntries->Add(entry);
fNGenerators++;
}
void AliGenCocktail::Init()
{
// Initialisation
TIter next(fEntries);
AliGenCocktailEntry *entry;
//
// Loop over generators and initialize
while((entry = (AliGenCocktailEntry*)next())) {
if (fStack) entry->Generator()->SetStack(fStack);
entry->Generator()->Init();
}
}
void AliGenCocktail::FinishRun()
{
// Initialisation
TIter next(fEntries);
AliGenCocktailEntry *entry;
//
// Loop over generators and initialize
while((entry = (AliGenCocktailEntry*)next())) {
entry->Generator()->FinishRun();
}
}
void AliGenCocktail::Generate()
{
//
// Generate event
TIter next(fEntries);
AliGenCocktailEntry *entry = 0;
AliGenCocktailEntry *preventry = 0;
AliGenerator* gen = 0;
TObjArray *partArray = gAlice->GetMCApp()->Particles();
//
// Generate the vertex position used by all generators
//
if(fVertexSmear == kPerEvent) Vertex();
TArrayF eventVertex;
eventVertex.Set(3);
for (Int_t j=0; j < 3; j++) eventVertex[j] = fVertex[j];
//
// Loop over generators and generate events
Int_t igen=0;
while((entry = (AliGenCocktailEntry*)next())) {
igen++;
if (igen ==1) {
entry->SetFirst(0);
} else {
entry->SetFirst((partArray->GetEntriesFast())+1);
}
//
// Handle case in which current generator needs collision geometry from previous generator
//
gen = entry->Generator();
if (gen->NeedsCollisionGeometry())
{
if (preventry && preventry->Generator()->ProvidesCollisionGeometry())
{
gen->SetCollisionGeometry(preventry->Generator()->CollisionGeometry());
} else {
Fatal("Generate()", "No Collision Geometry Provided");
}
}
entry->Generator()->SetVertex(fVertex.At(0), fVertex.At(1), fVertex.At(2));
entry->Generator()->Generate();
entry->SetLast(partArray->GetEntriesFast());
preventry = entry;
}
next.Reset();
// Header
AliGenEventHeader* header = new AliGenEventHeader("AliGenCocktail");
// Event Vertex
header->SetPrimaryVertex(eventVertex);
gAlice->SetGenEventHeader(header);
}
AliGenCocktailEntry * AliGenCocktail::FirstGenerator()
{
// Iterator over generators: Initialisation
flnk1 = fEntries->FirstLink();
if (flnk1) {
return (AliGenCocktailEntry*) (flnk1->GetObject());
} else {
return 0;
}
}
AliGenCocktailEntry* AliGenCocktail::NextGenerator()
{
// Iterator over generators: Increment
flnk1 = flnk1->Next();
if (flnk1) {
return (AliGenCocktailEntry*) (flnk1->GetObject());
} else {
return 0;
}
}
void AliGenCocktail::
FirstGeneratorPair(AliGenCocktailEntry*& e1, AliGenCocktailEntry*& e2)
{
// Iterator over generator pairs: Initialisation
flnk2 = flnk1 = fEntries->FirstLink();
if (flnk1) {
e2 = e1 = (AliGenCocktailEntry*) (flnk1->GetObject());
} else {
e2= e1 = 0;
}
}
void AliGenCocktail::
NextGeneratorPair(AliGenCocktailEntry*& e1, AliGenCocktailEntry*& e2)
{
// Iterator over generators: Increment
flnk2 = flnk2->Next();
if (flnk2) {
e1 = (AliGenCocktailEntry*) (flnk1->GetObject());
e2 = (AliGenCocktailEntry*) (flnk2->GetObject());
} else {
flnk2 = flnk1 = flnk1->Next();
if (flnk1) {
e1 = (AliGenCocktailEntry*) (flnk1->GetObject());
e2 = (AliGenCocktailEntry*) (flnk2->GetObject());
} else {
e1=0;
e2=0;
}
}
}
AliGenCocktail& AliGenCocktail::operator=(const AliGenCocktail& rhs)
{
// Assignment operator
rhs.Copy(*this);
return (*this);
}
void AliGenCocktail::Copy(TObject &) const
{
Fatal("Copy","Not implemented!\n");
}
<|endoftext|> |
<commit_before>#include <platform.h>
#include <CogServer.h>
#include <Node.h>
#include <Link.h>
#include <string>
#include <queue>
using namespace opencog;
class DottyGrapher
{
public:
DottyGrapher(AtomSpace *space) : space(space), withIncoming(false) { answer = ""; }
AtomSpace *space;
std::string answer;
bool withIncoming;
/**
* Outputs a dotty node for an atom.
*/
bool do_nodes(Atom *a)
{
std::ostringstream ost;
ost << TLB::getHandle(a) << " [";
if (!space->isNode(a->getType()))
ost << "shape=\"diamond\" ";
ost << "label=\"[" << ClassServer::getTypeName(a->getType()) << "]";
if (space->isNode(a->getType())) {
Node *n = (Node*)a;
ost << " " << n->getName();
} else {
Link *l = (Link*)a;
l = l; // TODO: anything to output for links?
}
ost << "\"];\n";
answer += ost.str();
return false;
}
/**
* Outputs dotty links for an atom's outgoing connections.
*/
bool do_links(Atom *a)
{
Handle h = TLB::getHandle(a);
std::ostringstream ost;
const std::vector<Handle> &out = a->getOutgoingSet();
for (size_t i = 0; i < out.size(); i++) {
ost << h << "->" << out[i] << " [label=\"" << i << "\"];\n";
}
if (withIncoming) {
HandleEntry *he = a->getIncomingSet();
int i = 0;
while (he) {
ost << h << "->" << he->handle << " [style=\"dotted\" label=\"" << i << "\"];\n";
he = he->next;
i++;
}
}
answer += ost.str();
return false;
}
void graph()
{
answer += "\ndigraph OpenCog {\n";
space->getAtomTable().foreach_atom(&DottyGrapher::do_nodes, this);
space->getAtomTable().foreach_atom(&DottyGrapher::do_links, this);
answer += "}\n";
}
};
extern "C" std::string cmd_dotty(std::queue<std::string> &args)
{
AtomSpace *space = CogServer::getAtomSpace();
DottyGrapher g(space);
while (!args.empty()) {
if (args.front() == "with-incoming")
g.withIncoming = true;
args.pop();
}
g.graph();
return g.answer;
}
<commit_msg>convert signatures of misc routines to const, also minor performance improvement in cast.<commit_after>#include <platform.h>
#include <CogServer.h>
#include <Node.h>
#include <Link.h>
#include <string>
#include <queue>
using namespace opencog;
class DottyGrapher
{
public:
DottyGrapher(AtomSpace *space) : space(space), withIncoming(false) { answer = ""; }
AtomSpace *space;
std::string answer;
bool withIncoming;
/**
* Outputs a dotty node for an atom.
*/
bool do_nodes(const Atom *a)
{
std::ostringstream ost;
ost << TLB::getHandle(a) << " [";
if (!space->isNode(a->getType()))
ost << "shape=\"diamond\" ";
ost << "label=\"[" << ClassServer::getTypeName(a->getType()) << "]";
const Node *n = dynamic_cast<const Node *>(a);
if (n) {
ost << " " << n->getName();
} else {
const Link *l = dynamic_cast<const Link *>(a);
l = l; // TODO: anything to output for links?
}
ost << "\"];\n";
answer += ost.str();
return false;
}
/**
* Outputs dotty links for an atom's outgoing connections.
*/
bool do_links(const Atom *a)
{
Handle h = TLB::getHandle(a);
std::ostringstream ost;
const std::vector<Handle> &out = a->getOutgoingSet();
for (size_t i = 0; i < out.size(); i++) {
ost << h << "->" << out[i] << " [label=\"" << i << "\"];\n";
}
if (withIncoming) {
HandleEntry *he = a->getIncomingSet();
int i = 0;
while (he) {
ost << h << "->" << he->handle << " [style=\"dotted\" label=\"" << i << "\"];\n";
he = he->next;
i++;
}
}
answer += ost.str();
return false;
}
void graph()
{
answer += "\ndigraph OpenCog {\n";
space->getAtomTable().foreach_atom(&DottyGrapher::do_nodes, this);
space->getAtomTable().foreach_atom(&DottyGrapher::do_links, this);
answer += "}\n";
}
};
extern "C" std::string cmd_dotty(std::queue<std::string> &args)
{
AtomSpace *space = CogServer::getAtomSpace();
DottyGrapher g(space);
while (!args.empty()) {
if (args.front() == "with-incoming")
g.withIncoming = true;
args.pop();
}
g.graph();
return g.answer;
}
<|endoftext|> |
<commit_before>#include "Model.h"
#include "Globals.h"
#include "Engine.h"
#include "ModuleRender.h"
#include "ModuleWindow.h"
#include "ModuleInput.h"
#include "SDL/include/SDL.h"
#include <windows.h>
#include "GL/glew.h"
#include <gl/GL.h>
#include <gl/GLU.h>
#include "Cube.h"
#include "Sphere.h"
#include "Cylinder.h"
#include "Plane.h"
#include "ModuleEditorCamera.h"
#include "CoordinateArrows.h"
#include "IL/ilut_config.h"
#include "IL/il.h"
#include "IL/ilut.h"
#include "IL/ilu.h"
ModuleRender::ModuleRender()
{
}
// Destructor
ModuleRender::~ModuleRender()
{}
// Called before render is available
bool ModuleRender::Init()
{
return true;
}
bool ModuleRender::Start()
{
LOG("Creating Renderer context");
bool ret = true;
context = SDL_GL_CreateContext(App->window->window);
if (context == nullptr)
{
LOG("Renderer could not be created! SDL_Error: %s\n", SDL_GetError());
ret = false;
}
else
{
GLenum err = glewInit();
if (err != GLEW_OK)
{
LOG("Error initialising GLEW: %s", glewGetErrorString(err));
return false;
}
LOG("Using Glew %s", glewGetString(GLEW_VERSION));
LOG("Vendor: %s", glGetString(GL_VENDOR));
LOG("Renderer: %s", glGetString(GL_RENDERER));
LOG("OpenGL version supported %s", glGetString(GL_VERSION));
LOG("GLSL: %s\n", glGetString(GL_SHADING_LANGUAGE_VERSION));
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
glClearDepth(1.0f);
glClearColor(0, 0, 0, 1.f);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
glEnable(GL_LIGHTING);
glEnable(GL_COLOR_MATERIAL);
glEnable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
int w, h;
SDL_GetWindowSize(App->window->window, &w, &h);
App->editorCamera->SetAspectRatio(float(w) / float(h));
GLubyte checkImage[CHECKERS_WIDTH][CHECKERS_HEIGHT][4];
//Check Image
for (int i = 0; i < CHECKERS_WIDTH; i++) {
for (int j = 0; j < CHECKERS_HEIGHT; j++) {
int c = ((((i & 0x8) == 0) ^ (((j & 0x8)) == 0))) * 255;
checkImage[i][j][0] = GLubyte(c);
checkImage[i][j][1] = GLubyte(c);
checkImage[i][j][2] = GLubyte(c);
checkImage[i][j][3] = GLubyte(255);
}
}
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glGenTextures(1, &ImageName);
glBindTexture(GL_TEXTURE_2D, ImageName);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, CHECKERS_WIDTH, CHECKERS_HEIGHT,
0, GL_RGBA, GL_UNSIGNED_BYTE, checkImage);
lenaImage = ilutGLLoadImage("Lenna.png");
Quat rotation_plane = Quat::FromEulerXYZ(DEG2RAD(0.f), DEG2RAD(0.f), DEG2RAD(0.f));
Quat rotation_cube = Quat::FromEulerXYZ(DEG2RAD(0.f), DEG2RAD(0.f), DEG2RAD(0.f));
Quat rotation_sphere = Quat::FromEulerXYZ(DEG2RAD(0.f), DEG2RAD(0.f), DEG2RAD(0.f));
Quat rotation_cylinder = Quat::FromEulerXYZ(DEG2RAD(0.f), DEG2RAD(0.f), DEG2RAD(0.f));
objects.push_back(new Cube(float3(0.f, 0.f, -5.f), rotation_cube, ImageName));
objects.push_back(new ::Plane(float3(0, 0.f, -5.f), rotation_plane, 60));
objects.push_back(new Cube(float3(5.f, 0.f, -5.f), rotation_cube, lenaImage));
objects.push_back(new ::Cylinder(float3(-2.f, 3.f, -5.f), rotation_cylinder, float3(0.f, 0.f, 25.f), 0.3f, 1.5));
objects.push_back(new ::Sphere(float3(2, 2, -5.f), rotation_sphere, float3(25.f, 21.75f, 0), 1, 12, 24));
Model* batman = new Model();
batman->Load("Models/Batman/", "batman.obj");
batman->Position.x = 10;
objects.push_back(batman);
objects.push_back(new CoordinateArrows());
}
return ret;
}
update_status ModuleRender::PreUpdate()
{
ModuleEditorCamera* camera = App->editorCamera;
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glLoadMatrixf(camera->GetProjectionMatrix());
if (App->input->GetWindowEvent(WE_RESIZE))
{
int w, h;
SDL_GetWindowSize(App->window->window, &w, &h);
camera->SetAspectRatio(float(w) / float(h));
glViewport(0, 0, w, h);
}
glClearColor(0, 0, 0, 1.f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glLoadMatrixf(camera->GetViewMatrix());
return UPDATE_CONTINUE;
}
// Called every draw update
update_status ModuleRender::Update()
{
bool ret = true;
GLfloat light_diffuse[] = { 1.0f, 1.0f, 1.0f, 1.0f };
glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse);
GLfloat light_position[] = { 0.25f, 1.0f, 1.0f, 0.0f };
glLightfv(GL_LIGHT0, GL_POSITION, light_position);
glEnable(GL_LIGHT0);
glEnable(GL_LIGHTING);
for (std::list<Primitive*>::iterator it = objects.begin(); it != objects.end(); ++it)
(*it)->Draw();
return ret ? UPDATE_CONTINUE : UPDATE_ERROR;
}
update_status ModuleRender::PostUpdate()
{
SDL_GL_SwapWindow(App->window->window);
return UPDATE_CONTINUE;
}
// Called before quitting
bool ModuleRender::CleanUp()
{
LOG("Destroying renderer");
//Destroy window
if (context != nullptr)
{
SDL_GL_DeleteContext(context);
}
for (std::list<Primitive*>::iterator it = objects.begin(); it != objects.end(); ++it)
{
(*it)->CleanUp();
RELEASE(*it);
}
return true;
}
<commit_msg>Load cube textures from the TextureManager<commit_after>#include "Model.h"
#include "Globals.h"
#include "Engine.h"
#include "ModuleRender.h"
#include "ModuleWindow.h"
#include "ModuleInput.h"
#include "SDL/include/SDL.h"
#include <windows.h>
#include "GL/glew.h"
#include <gl/GL.h>
#include <gl/GLU.h>
#include "Cube.h"
#include "Sphere.h"
#include "Cylinder.h"
#include "Plane.h"
#include "ModuleEditorCamera.h"
#include "CoordinateArrows.h"
#include "IL/ilut_config.h"
#include "IL/il.h"
#include "IL/ilut.h"
#include "IL/ilu.h"
#include "ModuleTextures.h"
ModuleRender::ModuleRender()
{
}
// Destructor
ModuleRender::~ModuleRender()
{}
// Called before render is available
bool ModuleRender::Init()
{
return true;
}
bool ModuleRender::Start()
{
LOG("Creating Renderer context");
bool ret = true;
context = SDL_GL_CreateContext(App->window->window);
if (context == nullptr)
{
LOG("Renderer could not be created! SDL_Error: %s\n", SDL_GetError());
ret = false;
}
else
{
GLenum err = glewInit();
if (err != GLEW_OK)
{
LOG("Error initialising GLEW: %s", glewGetErrorString(err));
return false;
}
LOG("Using Glew %s", glewGetString(GLEW_VERSION));
LOG("Vendor: %s", glGetString(GL_VENDOR));
LOG("Renderer: %s", glGetString(GL_RENDERER));
LOG("OpenGL version supported %s", glGetString(GL_VERSION));
LOG("GLSL: %s\n", glGetString(GL_SHADING_LANGUAGE_VERSION));
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
glClearDepth(1.0f);
glClearColor(0, 0, 0, 1.f);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
glEnable(GL_LIGHTING);
glEnable(GL_COLOR_MATERIAL);
glEnable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
int w, h;
SDL_GetWindowSize(App->window->window, &w, &h);
App->editorCamera->SetAspectRatio(float(w) / float(h));
GLubyte checkImage[CHECKERS_WIDTH][CHECKERS_HEIGHT][4];
//Check Image
for (int i = 0; i < CHECKERS_WIDTH; i++) {
for (int j = 0; j < CHECKERS_HEIGHT; j++) {
int c = ((((i & 0x8) == 0) ^ (((j & 0x8)) == 0))) * 255;
checkImage[i][j][0] = GLubyte(c);
checkImage[i][j][1] = GLubyte(c);
checkImage[i][j][2] = GLubyte(c);
checkImage[i][j][3] = GLubyte(255);
}
}
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glGenTextures(1, &ImageName);
glBindTexture(GL_TEXTURE_2D, ImageName);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, CHECKERS_WIDTH, CHECKERS_HEIGHT,
0, GL_RGBA, GL_UNSIGNED_BYTE, checkImage);
lenaImage = App->textures->Load("Lenna.png");
Quat rotation_plane = Quat::FromEulerXYZ(DEG2RAD(0.f), DEG2RAD(0.f), DEG2RAD(0.f));
Quat rotation_cube = Quat::FromEulerXYZ(DEG2RAD(0.f), DEG2RAD(0.f), DEG2RAD(0.f));
Quat rotation_sphere = Quat::FromEulerXYZ(DEG2RAD(0.f), DEG2RAD(0.f), DEG2RAD(0.f));
Quat rotation_cylinder = Quat::FromEulerXYZ(DEG2RAD(0.f), DEG2RAD(0.f), DEG2RAD(0.f));
objects.push_back(new Cube(float3(0.f, 0.f, -5.f), rotation_cube, ImageName));
objects.push_back(new ::Plane(float3(0, 0.f, -5.f), rotation_plane, 60));
objects.push_back(new Cube(float3(5.f, 0.f, -5.f), rotation_cube, lenaImage));
objects.push_back(new ::Cylinder(float3(-2.f, 3.f, -5.f), rotation_cylinder, float3(0.f, 0.f, 25.f), 0.3f, 1.5));
objects.push_back(new ::Sphere(float3(2, 2, -5.f), rotation_sphere, float3(25.f, 21.75f, 0), 1, 12, 24));
Model* batman = new Model();
batman->Load("Models/Batman/", "batman.obj");
batman->Position.x = 10;
objects.push_back(batman);
objects.push_back(new CoordinateArrows());
}
return ret;
}
update_status ModuleRender::PreUpdate()
{
ModuleEditorCamera* camera = App->editorCamera;
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glLoadMatrixf(camera->GetProjectionMatrix());
if (App->input->GetWindowEvent(WE_RESIZE))
{
int w, h;
SDL_GetWindowSize(App->window->window, &w, &h);
camera->SetAspectRatio(float(w) / float(h));
glViewport(0, 0, w, h);
}
glClearColor(0, 0, 0, 1.f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glLoadMatrixf(camera->GetViewMatrix());
return UPDATE_CONTINUE;
}
// Called every draw update
update_status ModuleRender::Update()
{
bool ret = true;
GLfloat light_diffuse[] = { 1.0f, 1.0f, 1.0f, 1.0f };
glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse);
GLfloat light_position[] = { 0.25f, 1.0f, 1.0f, 0.0f };
glLightfv(GL_LIGHT0, GL_POSITION, light_position);
glEnable(GL_LIGHT0);
glEnable(GL_LIGHTING);
for (std::list<Primitive*>::iterator it = objects.begin(); it != objects.end(); ++it)
(*it)->Draw();
return ret ? UPDATE_CONTINUE : UPDATE_ERROR;
}
update_status ModuleRender::PostUpdate()
{
SDL_GL_SwapWindow(App->window->window);
return UPDATE_CONTINUE;
}
// Called before quitting
bool ModuleRender::CleanUp()
{
LOG("Destroying renderer");
//Destroy window
if (context != nullptr)
{
SDL_GL_DeleteContext(context);
}
for (std::list<Primitive*>::iterator it = objects.begin(); it != objects.end(); ++it)
{
(*it)->CleanUp();
RELEASE(*it);
}
return true;
}
<|endoftext|> |
<commit_before>/*
* main.cpp
* Copyright (C) 2015 Chris Waltrip <walt2178@vandals.uidaho.edu>
*
* This file is part of EvoComp-SantaFe
*
* EvoComp-SantaFe 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.
*
* EvoComp-SantaFe 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 EvoComp-SantaFe. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Source file containing the overall execution of the genetic program.
* Reads in command line arguments from the user including a map file to be
* used as a test for the Ant. It then creates a population of potential
* solutions, runs the evolution process and writes the results to file.
*
* @file
* @date 23 November 2015
*
*/
/**
* @todo Go through and make sure documentation is updated everywhere.
* @todo Implement some sort of parsimony pressure in addition to or
* instead of parsimony selection?
*/
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <boost/program_options.hpp>
#include "options.h"
#include "population.h"
#include "trail_map.h"
namespace po = boost::program_options;
/**
* Reads command line arguments for the program. Certain arguments will cause
* the execution of the program to halt, e.g. `--help` or `--input` with an
* an invalid filename.
* @param[in] argc Number of items in argv.
* @param[in] argv List of command line arguments.
* @param[out] opts Command line options that were specified.
*/
void ParseCommandLine(int argc, char **argv, Options &opt);
/**
* Returns the utility usage syntax.
* @param[in] program_name Name of the exectued program (i.e, argv[0]).
*
* @return Returns a `std::string` of usage details with the name of the
* calling program inserted into the string.
*/
std::string GetUsageString(std::string program_name);
/**
* Returns a vector of the lines in the given file. This is passed to the
* TrailMap to construct a new map object.
* @param[in] filename Name of the file to parse.
* @return Returns a `std::vector<std::string>` containing the
* contents of the file read in.
*/
std::vector<std::string> ParseDataFile(std::string filename);
/**
* Write the fitness and tree information to the file stream object passed in.
*
* @param[out] out File stream object to write to.
* @param[in] best_fitness The fitness score of the best indiviudal.
* @param[in] avg_fitness The average fitness of the generation.
* @param[in] best_solution_size Tree size of the best individual.
* @param[in] avg_size Average tree size of the generation.
*/
void WriteOutputFile(std::ofstream &out, double best_fitness,
double avg_fitness, size_t best_solution_size,
size_t avg_size);
/**
* Return a string formatted to write to file.
*
* @param[in] best_fitness The fitness score of the best indiviudal.
* @param[in] avg_fitness The average fitness of the generation.
* @param[in] best_solution_size Tree size of the best individual.
* @param[in] avg_size Average tree size of the generation.
*
* @return The parameters separated by commas and formatted as
* a `std::string`.
*/
std::string FormatOutputFile(double best_fitness, double avg_fitness,
size_t best_solution_size, size_t avg_size);
/*
* All of the command line options are stored in this object and this object
* is passed where needed to read the options.
*/
static Options opts;
int main(int argc, char **argv, char **envp) {
ParseCommandLine(argc, argv, opts);
std::vector<TrailMap*> maps;
std::vector<TrailMap*> secondary_maps;
std::vector<TrailMap*> verification_maps;
std::vector<std::pair<Population*,std::ofstream&>> populations;
/* Create all the maps */
for (std::string fn : opts.map_files_) {
maps.emplace_back(new TrailMap(ParseDataFile(fn),
opts.action_count_limit_));
}
if (opts.secondary_maps_exist_) {
for (std::string fn : opts.secondary_map_files_) {
secondary_maps.emplace_back(new TrailMap(ParseDataFile(fn),
opts.action_count_limit_));
}
}
if (opts.verification_maps_exist_) {
for (std::string fn : opts.verification_map_files_) {
verification_maps.emplace_back(new TrailMap(ParseDataFile(fn),
opts.action_count_limit_));
}
}
/* Create the populations */
populations.emplace_back(
std::make_pair(new Population(opts, maps),
std::ofstream(opts.output_file_,
std::ios::out | std::ios::trunc)));
if (opts.secondary_maps_exist_) {
/** @todo Would secondary_output_file lose scope if declared here? */
populations.emplace_back(
std::make_pair(new Population(*(populations.front().first),
secondary_maps),
std::ofstream(opts.secondary_output_file_,
std::ios::out | std::ios::trunc)));
}
/* Evolve the populations in tandem */
for (size_t i = 0; i < opts.evolution_count_; ++i) {
for (auto p : populations) {
p.first->Evolve();
p.second << FormatOutputFile(p.first->GetBestFitness(),
p.first->GetAverageFitness(),
p.first->GetBestTreeSize(),
p.first->GetAverageTreeSize());
p.second << "\n";
if (i % 10 == 0) {
std::clog << "Generation " << i << " completed.\n";
}
if (i % 100 == 0) {
std::clog << "Current best solution: \n";
std::clog << FormatOutputFile(p.first->GetBestFitness(),
p.first->GetAverageFitness(),
p.first->GetBestTreeSize(),
p.first->GetAverageTreeSize());
std::clog << "\n";
std::clog << p.first->GetBestSolutionGraphViz();
std::clog << "\n";
}
}
}
for (auto p : populations) {
p.second.flush(); /* @todo Does close() already do this? */
p.second.close();
}
/*
* Evolution is done. Write last of results to file. If a verification
* map set exists, then run all the populations through the maps.
*/
if (opts.verification_maps_exist_) {
std::ofstream verification_output_file;
verification_output_file.open(opts.verification_output_file_,
std::ios::out | std::ios::trunc);
for (auto p : populations) {
p.first->SetMaps(verification_maps);
p.first->CalculateFitness();
WriteOutputFile(verification_output_file,
p.first->GetBestFitness(),
p.first->GetAverageFitness(),
p.first->GetBestTreeSize(),
p.first->GetAverageTreeSize());
}
verification_output_file.flush();
verification_output_file.close();
}
return 0;
}
void ParseCommandLine(int argc, char **argv, Options &opts) {
/* Vector to hold return values */
std::vector<std::string> filenames;
po::options_description basic_opts("Basic Options");
po::options_description pop_opts("Population Options");
po::options_description indiv_opts("Individual Options");
po::options_description io_opts("Input/Output File Options");
po::options_description cmd_opts;
po::positional_options_description positional_opts;
po::variables_map vm;
/* Basic Options */
basic_opts.add_options()
("help,h", "print this help and exit")
("verbose,v", "print extra logging information");
pop_opts.add_options()
("generations,g",
po::value<size_t>(&opts.evolution_count_),
"Number of generations to evolve.")
("population-size,p",
po::value<size_t>(&opts.population_size_),
"Number of individuals in a population.")
("action-limit,a",
po::value<size_t>(&opts.action_count_limit_),
"Maximum number of actions to evaluate.")
("tournament-size,t",
po::value<size_t>(&opts.tournament_size_),
"Number of Individuals in a tournament.")
("proportional-tournament-rate,r",
po::value<double>(&opts.proportional_tournament_rate_),
"Rate that tournament is fitness based instead of parsimony based.");
indiv_opts.add_options()
("mutation,m",
po::value<double>(&opts.mutation_rate_),
"Rate of mutation per node in the tree.")
("nonterminal-crossover-rate,n",
po::value<double>(&opts.nonterminal_crossover_rate_),
"Rate that nonterminals are chosen as crossover point.")
("min-depth,d",
po::value<size_t>(&opts.tree_depth_min_),
"Minimum tree depth.")
("max-depth,x",
po::value<size_t>(&opts.tree_depth_max_),
"Maximum tree depth.");
io_opts.add_options()
("input,I",
po::value<std::vector<std::string>>(&opts.map_files_)->required(),
"Specify input file(s)")
("secondary,S",
po::value<std::vector<std::string>>(&opts.secondary_map_files_),
"Secondary set of input file(s) to compare against.")
("verification,V",
po::value<std::vector<std::string>>(&opts.verification_map_files_),
"Set of input file(s) to use for verification but not evolution.")
("graphviz,G",
po::value<std::string>(&opts.graphviz_file_),
"Specify the file for GraphViz output file.")
("output,O", po::value<std::string>(&opts.output_file_),
"Output file location for main GP population.")
("secondary-output,T",
po::value<std::string>(&opts.secondary_output_file_),
"Output file for secondary GP population.")
("verification-output,W",
po::value<std::string>(&opts.verification_output_file_),
"Output file for verification GP population.");
positional_opts.add("input", -1);
cmd_opts.add(basic_opts).add(pop_opts).add(indiv_opts).add(io_opts);
po::store(po::command_line_parser(argc, argv).options(cmd_opts)
.positional(positional_opts).run(), vm);
if (vm.count("help")) {
std::cout << GetUsageString(std::string(argv[0])) << std::endl;
std::cout << cmd_opts << std::endl;
exit(EXIT_SUCCESS);
}
po::notify(vm);
if (!vm.count("verbose")) {
std::clog.rdbuf(nullptr);
}
if (vm.count("input")) {
for (auto fn : opts.map_files_) {
if (!(std::ifstream(fn).good())) {
std::cerr << fn << " not found!" << std::endl;
exit(EXIT_FAILURE);
}
}
} else {
std::cerr << "Please specify input files" << std::endl;
std::cerr << GetUsageString(std::string(argv[0])) << std::endl;
std::cerr << cmd_opts << std::endl;
exit(EXIT_FAILURE);
}
if (vm.count("secondary")) {
for (auto fn : opts.secondary_map_files_) {
if (!(std::ifstream(fn).good())) {
std::cerr << fn << " not found!" << std::endl;
exit(EXIT_FAILURE);
}
}
opts.secondary_maps_exist_ = true;
} else {
opts.secondary_maps_exist_ = false;
}
if (vm.count("verification")) {
for (auto fn : opts.verification_map_files_) {
if (!(std::ifstream(fn).good())) {
std::cerr << fn << " not found!" << std::endl;
exit(EXIT_FAILURE);
}
}
opts.verification_maps_exist_ = true;
} else {
opts.verification_maps_exist_ = false;
}
if (vm.count("graphviz")) {
opts.graphviz_file_exists_ = true;
} else {
opts.graphviz_file_exists_ = false;
}
}
std::string GetUsageString(std::string program_name) {
size_t found = program_name.find_last_of("/\\");
std::string usage = "Usage: " + program_name.substr(found + 1);
usage += " [options] input_file_1 [input_file_2...]";
return usage;
}
std::vector<std::string> ParseDataFile(std::string filename) {
std::ifstream inf;
std::string line;
std::vector<std::string> map_file_contents;
inf.open(filename);
if (!inf) {
std::cerr << "Failed to open file: " << filename << std::endl;
exit(EXIT_FAILURE);
}
/* Parse input file */
while (std::getline(inf, line)) {
map_file_contents.push_back(line);
}
return map_file_contents;
}
void WriteOutputFile(std::ofstream &out, double best_fitness,
double avg_fitness, size_t best_solution_size,
size_t avg_size) {
out << best_fitness << "," << best_solution_size << ",";
out << avg_fitness << "," << avg_size << "\n";
}
std::string FormatOutputFile(double best_fitness, double avg_fitness,
size_t best_solution_size, size_t avg_size) {
std::stringstream ss;
ss << best_fitness << "," << best_solution_size << ",";
ss << avg_fitness << "," << avg_size;
return ss.str();
}<commit_msg>Removed FormatOutputFile and replaced usages with WriteOutputFile.<commit_after>/*
* main.cpp
* Copyright (C) 2015 Chris Waltrip <walt2178@vandals.uidaho.edu>
*
* This file is part of EvoComp-SantaFe
*
* EvoComp-SantaFe 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.
*
* EvoComp-SantaFe 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 EvoComp-SantaFe. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Source file containing the overall execution of the genetic program.
* Reads in command line arguments from the user including a map file to be
* used as a test for the Ant. It then creates a population of potential
* solutions, runs the evolution process and writes the results to file.
*
* @file
* @date 23 November 2015
*
*/
/**
* @todo Go through and make sure documentation is updated everywhere.
* @todo Implement some sort of parsimony pressure in addition to or
* instead of parsimony selection?
*/
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <boost/program_options.hpp>
#include "options.h"
#include "population.h"
#include "trail_map.h"
namespace po = boost::program_options;
/**
* Reads command line arguments for the program. Certain arguments will cause
* the execution of the program to halt, e.g. `--help` or `--input` with an
* an invalid filename.
* @param[in] argc Number of items in argv.
* @param[in] argv List of command line arguments.
* @param[out] opts Command line options that were specified.
*/
void ParseCommandLine(int argc, char **argv, Options &opt);
/**
* Returns the utility usage syntax.
* @param[in] program_name Name of the exectued program (i.e, argv[0]).
*
* @return Returns a `std::string` of usage details with the name of the
* calling program inserted into the string.
*/
std::string GetUsageString(std::string program_name);
/**
* Returns a vector of the lines in the given file. This is passed to the
* TrailMap to construct a new map object.
* @param[in] filename Name of the file to parse.
* @return Returns a `std::vector<std::string>` containing the
* contents of the file read in.
*/
std::vector<std::string> ParseDataFile(std::string filename);
/**
* Write the fitness and tree information to the file stream object passed in.
*
* @param[out] out File stream object to write to.
* @param[in] best_fitness The fitness score of the best indiviudal.
* @param[in] avg_fitness The average fitness of the generation.
* @param[in] best_solution_size Tree size of the best individual.
* @param[in] avg_size Average tree size of the generation.
*/
void WriteOutputFile(std::ofstream &out, double best_fitness,
double avg_fitness, size_t best_solution_size,
size_t avg_size);
/*
* All of the command line options are stored in this object and this object
* is passed where needed to read the options.
*/
static Options opts;
int main(int argc, char **argv, char **envp) {
ParseCommandLine(argc, argv, opts);
std::vector<TrailMap*> maps;
std::vector<TrailMap*> secondary_maps;
std::vector<TrailMap*> verification_maps;
std::vector<std::pair<Population*,std::ofstream&>> populations;
/* Create all the maps */
for (std::string fn : opts.map_files_) {
maps.emplace_back(new TrailMap(ParseDataFile(fn),
opts.action_count_limit_));
}
if (opts.secondary_maps_exist_) {
for (std::string fn : opts.secondary_map_files_) {
secondary_maps.emplace_back(new TrailMap(ParseDataFile(fn),
opts.action_count_limit_));
}
}
if (opts.verification_maps_exist_) {
for (std::string fn : opts.verification_map_files_) {
verification_maps.emplace_back(new TrailMap(ParseDataFile(fn),
opts.action_count_limit_));
}
}
/* Create the populations */
populations.emplace_back(
std::make_pair(new Population(opts, maps),
std::ofstream(opts.output_file_,
std::ios::out | std::ios::trunc)));
if (opts.secondary_maps_exist_) {
/** @todo Would secondary_output_file lose scope if declared here? */
populations.emplace_back(
std::make_pair(new Population(*(populations.front().first),
secondary_maps),
std::ofstream(opts.secondary_output_file_,
std::ios::out | std::ios::trunc)));
}
/* Evolve the populations in tandem */
for (size_t i = 0; i < opts.evolution_count_; ++i) {
for (auto p : populations) {
p.first->Evolve();
WriteOutputFile(p.second,
p.first->GetBestFitness(),
p.first->GetAverageFitness(),
p.first->GetBestTreeSize(),
p.first->GetAverageTreeSize());
p.second << "\n";
if (i % 10 == 0) {
std::clog << "Generation " << i << " completed.\n";
}
if (i % 100 == 0) {
std::clog << "Current best solution: \n";
std::clog << FormatOutputFile(p.first->GetBestFitness(),
p.first->GetAverageFitness(),
p.first->GetBestTreeSize(),
p.first->GetAverageTreeSize());
std::clog << "\n";
std::clog << p.first->GetBestSolutionGraphViz();
std::clog << "\n";
}
}
}
for (auto p : populations) {
p.second.flush(); /* @todo Does close() already do this? */
p.second.close();
}
/*
* Evolution is done. Write last of results to file. If a verification
* map set exists, then run all the populations through the maps.
*/
if (opts.verification_maps_exist_) {
std::ofstream verification_output_file;
verification_output_file.open(opts.verification_output_file_,
std::ios::out | std::ios::trunc);
for (auto p : populations) {
p.first->SetMaps(verification_maps);
p.first->CalculateFitness();
WriteOutputFile(verification_output_file,
p.first->GetBestFitness(),
p.first->GetAverageFitness(),
p.first->GetBestTreeSize(),
p.first->GetAverageTreeSize());
}
verification_output_file.flush();
verification_output_file.close();
}
return 0;
}
void ParseCommandLine(int argc, char **argv, Options &opts) {
/* Vector to hold return values */
std::vector<std::string> filenames;
po::options_description basic_opts("Basic Options");
po::options_description pop_opts("Population Options");
po::options_description indiv_opts("Individual Options");
po::options_description io_opts("Input/Output File Options");
po::options_description cmd_opts;
po::positional_options_description positional_opts;
po::variables_map vm;
/* Basic Options */
basic_opts.add_options()
("help,h", "print this help and exit")
("verbose,v", "print extra logging information");
pop_opts.add_options()
("generations,g",
po::value<size_t>(&opts.evolution_count_),
"Number of generations to evolve.")
("population-size,p",
po::value<size_t>(&opts.population_size_),
"Number of individuals in a population.")
("action-limit,a",
po::value<size_t>(&opts.action_count_limit_),
"Maximum number of actions to evaluate.")
("tournament-size,t",
po::value<size_t>(&opts.tournament_size_),
"Number of Individuals in a tournament.")
("proportional-tournament-rate,r",
po::value<double>(&opts.proportional_tournament_rate_),
"Rate that tournament is fitness based instead of parsimony based.");
indiv_opts.add_options()
("mutation,m",
po::value<double>(&opts.mutation_rate_),
"Rate of mutation per node in the tree.")
("nonterminal-crossover-rate,n",
po::value<double>(&opts.nonterminal_crossover_rate_),
"Rate that nonterminals are chosen as crossover point.")
("min-depth,d",
po::value<size_t>(&opts.tree_depth_min_),
"Minimum tree depth.")
("max-depth,x",
po::value<size_t>(&opts.tree_depth_max_),
"Maximum tree depth.");
io_opts.add_options()
("input,I",
po::value<std::vector<std::string>>(&opts.map_files_)->required(),
"Specify input file(s)")
("secondary,S",
po::value<std::vector<std::string>>(&opts.secondary_map_files_),
"Secondary set of input file(s) to compare against.")
("verification,V",
po::value<std::vector<std::string>>(&opts.verification_map_files_),
"Set of input file(s) to use for verification but not evolution.")
("graphviz,G",
po::value<std::string>(&opts.graphviz_file_),
"Specify the file for GraphViz output file.")
("output,O", po::value<std::string>(&opts.output_file_),
"Output file location for main GP population.")
("secondary-output,T",
po::value<std::string>(&opts.secondary_output_file_),
"Output file for secondary GP population.")
("verification-output,W",
po::value<std::string>(&opts.verification_output_file_),
"Output file for verification GP population.");
positional_opts.add("input", -1);
cmd_opts.add(basic_opts).add(pop_opts).add(indiv_opts).add(io_opts);
po::store(po::command_line_parser(argc, argv).options(cmd_opts)
.positional(positional_opts).run(), vm);
if (vm.count("help")) {
std::cout << GetUsageString(std::string(argv[0])) << std::endl;
std::cout << cmd_opts << std::endl;
exit(EXIT_SUCCESS);
}
po::notify(vm);
if (!vm.count("verbose")) {
std::clog.rdbuf(nullptr);
}
if (vm.count("input")) {
for (auto fn : opts.map_files_) {
if (!(std::ifstream(fn).good())) {
std::cerr << fn << " not found!" << std::endl;
exit(EXIT_FAILURE);
}
}
} else {
std::cerr << "Please specify input files" << std::endl;
std::cerr << GetUsageString(std::string(argv[0])) << std::endl;
std::cerr << cmd_opts << std::endl;
exit(EXIT_FAILURE);
}
if (vm.count("secondary")) {
for (auto fn : opts.secondary_map_files_) {
if (!(std::ifstream(fn).good())) {
std::cerr << fn << " not found!" << std::endl;
exit(EXIT_FAILURE);
}
}
opts.secondary_maps_exist_ = true;
} else {
opts.secondary_maps_exist_ = false;
}
if (vm.count("verification")) {
for (auto fn : opts.verification_map_files_) {
if (!(std::ifstream(fn).good())) {
std::cerr << fn << " not found!" << std::endl;
exit(EXIT_FAILURE);
}
}
opts.verification_maps_exist_ = true;
} else {
opts.verification_maps_exist_ = false;
}
if (vm.count("graphviz")) {
opts.graphviz_file_exists_ = true;
} else {
opts.graphviz_file_exists_ = false;
}
}
std::string GetUsageString(std::string program_name) {
size_t found = program_name.find_last_of("/\\");
std::string usage = "Usage: " + program_name.substr(found + 1);
usage += " [options] input_file_1 [input_file_2...]";
return usage;
}
std::vector<std::string> ParseDataFile(std::string filename) {
std::ifstream inf;
std::string line;
std::vector<std::string> map_file_contents;
inf.open(filename);
if (!inf) {
std::cerr << "Failed to open file: " << filename << std::endl;
exit(EXIT_FAILURE);
}
/* Parse input file */
while (std::getline(inf, line)) {
map_file_contents.push_back(line);
}
return map_file_contents;
}
void WriteOutputFile(std::ofstream &out, double best_fitness,
double avg_fitness, size_t best_solution_size,
size_t avg_size) {
out << best_fitness << "," << best_solution_size << ",";
out << avg_fitness << "," << avg_size << "\n";
}<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: onefuncstarter.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: obo $ $Date: 2006-09-17 03:49:28 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_testshl2.hxx"
#include <vector>
#include <stdio.h>
#include "registerfunc.h"
#ifndef _OSL_MODULE_HXX_
#include <osl/module.hxx>
#endif
#ifndef _OSL_PROCESS_H_
#include <osl/process.h>
#endif
#ifndef _OSL_FILE_HXX_
#include <osl/file.hxx>
#endif
#include <rtl/string.hxx>
#include <rtl/ustring.hxx>
typedef std::vector<FktPtr> FunctionList;
FunctionList m_Functions;
extern "C" bool SAL_CALL registerFunc(FktPtr _pFunc, const char* _sFuncName)
{
printf("Function register call for func(%s) successful.\n", _sFuncName);
m_Functions.push_back(_pFunc);
// FktPtr pFunc = _pFunc;
// if (_pFunc)
// {
// (_pFunc)();
// }
return true;
}
void callAll()
{
for(FunctionList::const_iterator it = m_Functions.begin();
it != m_Functions.end();
++it)
{
FktPtr pFunc = *it;
if (pFunc)
{
(pFunc)();
}
}
}
// void test_link_at_compiletime()
// {
// FktRegFuncPtr pRegisterFunc = ®isterFunc;
// registerAll(pRegisterFunc);
// callAll();
// }
// -----------------------------------------------------------------------------
rtl::OUString convertPath( rtl::OString const& sysPth )
{
// PRE: String should contain a filename, relativ or absolut
rtl::OUString sysPath( rtl::OUString::createFromAscii( sysPth.getStr() ) );
rtl::OUString fURL;
if ( sysPth.indexOf("..") == 0 )
{
// filepath contains '..' so it's a relative path make it absolut.
rtl::OUString curDirPth;
osl_getProcessWorkingDir( &curDirPth.pData );
osl::FileBase::getAbsoluteFileURL( curDirPth, sysPath, fURL );
}
else
{
osl::FileBase::getFileURLFromSystemPath( sysPath, fURL );
}
return fURL;
}
// -----------------------------------------------------------------------------
void test_link_at_runtime()
{
::osl::Module* pModule;
pModule = new ::osl::Module();
// create and load the module (shared library)
// pModule = new ::osl::Module();
#ifdef WNT
pModule->load( convertPath( rtl::OString( "onefunc_DLL.dll" ) ) );
#endif
#ifdef UNX
pModule->load( convertPath( rtl::OString( "libonefunc_DLL.so" ) ) );
#endif
// get entry pointer
FktRegAllPtr pFunc = (FktRegAllPtr) pModule->getSymbol( rtl::OUString::createFromAscii( "registerAllTestFunction" ) );
if (pFunc)
{
FktRegFuncPtr pRegisterFunc = ®isterFunc;
pFunc(pRegisterFunc);
callAll();
}
delete pModule;
}
// ----------------------------------- Main -----------------------------------
#if (defined UNX) || (defined OS2)
int main( int argc, char* argv[] )
#else
int _cdecl main( int argc, char* argv[] )
#endif
{
// test_link_at_compiletime();
test_link_at_runtime();
return 0;
}
<commit_msg>INTEGRATION: CWS rpt23fix02 (1.5.24); FILE MERGED 2007/07/23 11:15:59 lla 1.5.24.1: #i79902# make demos buildable<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: onefuncstarter.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: hr $ $Date: 2007-08-03 10:17:13 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_testshl2.hxx"
#include <vector>
#include <stdio.h>
#include "registerfunc.h"
#ifndef _OSL_MODULE_HXX_
#include <osl/module.hxx>
#endif
#ifndef _OSL_PROCESS_H_
#include <osl/process.h>
#endif
#ifndef _OSL_FILE_HXX_
#include <osl/file.hxx>
#endif
#include <rtl/string.hxx>
#include <rtl/ustring.hxx>
typedef std::vector<FktPtr> FunctionList;
FunctionList m_Functions;
extern "C" bool SAL_CALL registerFunc(FktPtr _pFunc, const char* _sFuncName)
{
printf("Function register call for func(%s) successful.\n", _sFuncName);
m_Functions.push_back(_pFunc);
// FktPtr pFunc = _pFunc;
// if (_pFunc)
// {
// (_pFunc)();
// }
return true;
}
void callAll()
{
for(FunctionList::const_iterator it = m_Functions.begin();
it != m_Functions.end();
++it)
{
FktPtr pFunc = *it;
if (pFunc)
{
(pFunc)();
}
}
}
// void test_link_at_compiletime()
// {
// FktRegFuncPtr pRegisterFunc = ®isterFunc;
// registerAll(pRegisterFunc);
// callAll();
// }
// -----------------------------------------------------------------------------
rtl::OUString convertPath( rtl::OString const& sysPth )
{
// PRE: String should contain a filename, relativ or absolut
rtl::OUString sysPath( rtl::OUString::createFromAscii( sysPth.getStr() ) );
rtl::OUString fURL;
if ( sysPth.indexOf("..") == 0 )
{
// filepath contains '..' so it's a relative path make it absolut.
rtl::OUString curDirPth;
osl_getProcessWorkingDir( &curDirPth.pData );
osl::FileBase::getAbsoluteFileURL( curDirPth, sysPath, fURL );
}
else
{
osl::FileBase::getFileURLFromSystemPath( sysPath, fURL );
}
return fURL;
}
// -----------------------------------------------------------------------------
void test_link_at_runtime()
{
::osl::Module* pModule;
pModule = new ::osl::Module();
// create and load the module (shared library)
// pModule = new ::osl::Module();
#ifdef WNT
pModule->load( convertPath( rtl::OString( "onefunc_DLL.dll" ) ) );
#endif
#ifdef UNX
pModule->load( convertPath( rtl::OString( "libonefunc_DLL.so" ) ) );
#endif
// get entry pointer
FktRegAllPtr pFunc = (FktRegAllPtr) pModule->getSymbol( rtl::OUString::createFromAscii( "registerAllTestFunction" ) );
if (pFunc)
{
FktRegFuncPtr pRegisterFunc = ®isterFunc;
pFunc(pRegisterFunc);
callAll();
}
delete pModule;
}
// ----------------------------------- Main -----------------------------------
#if (defined UNX) || (defined OS2)
int main( int argc, char* argv[] )
#else
int _cdecl main( int argc, char* argv[] )
#endif
{
(void) argc;
(void) argv;
// test_link_at_compiletime();
test_link_at_runtime();
return 0;
}
<|endoftext|> |
<commit_before>#include <unistd.h>
int main(int argc, char* argv[])
{
while (1) {
sleep(1);
}
return 0;
}
<commit_msg>Minor: Delete leftover dummy (timing_wait).<commit_after><|endoftext|> |
<commit_before>#include "platform.hpp"
#include "../base/assert.hpp"
#include "../base/macros.hpp"
#include "../base/logging.hpp"
#include "../defines.hpp"
#include <QtCore/QDir>
#include <QtCore/QFileInfo>
#include <QtCore/QTemporaryFile>
#include "../std/target_os.hpp"
#if defined(OMIM_OS_WINDOWS)
#include "../std/windows.hpp"
#include <shlobj.h>
#define DIR_SLASH "\\"
#elif defined(OMIM_OS_MAC)
#include <stdlib.h>
#include <mach-o/dyld.h>
#include <sys/param.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/sysctl.h>
#include <glob.h>
#include <NSSystemDirectories.h>
#define DIR_SLASH "/"
#elif defined(OMIM_OS_LINUX)
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#define DIR_SLASH "/"
#endif
#include "../base/start_mem_debug.hpp"
// default writable directory name for dev/standalone installs
#define MAPDATA_DIR "data"
// default writable dir name in LocalAppData or ~/Library/AppData/ folders
#define LOCALAPPDATA_DIR "MapsWithMe"
// default Resources read-only dir
#define RESOURCES_DIR "Resources"
#ifdef OMIM_OS_MAC
string ExpandTildePath(char const * path)
{
// ASSERT(path, ());
glob_t globbuf;
string result = path;
if (::glob(path, GLOB_TILDE, NULL, &globbuf) == 0) //success
{
if (globbuf.gl_pathc > 0)
result = globbuf.gl_pathv[0];
globfree(&globbuf);
}
return result;
}
#endif
static bool GetUserWritableDir(string & outDir)
{
#if defined(OMIM_OS_WINDOWS)
char pathBuf[MAX_PATH] = {0};
if (SUCCEEDED(::SHGetFolderPathA(NULL, CSIDL_LOCAL_APPDATA | CSIDL_FLAG_CREATE, NULL, SHGFP_TYPE_CURRENT, pathBuf)))
{
outDir = pathBuf;
::CreateDirectoryA(outDir.c_str(), NULL);
outDir += "\\" LOCALAPPDATA_DIR "\\";
::CreateDirectoryA(outDir.c_str(), NULL);
return true;
}
#elif defined(OMIM_OS_MAC)
char pathBuf[PATH_MAX];
NSSearchPathEnumerationState state = ::NSStartSearchPathEnumeration(NSApplicationSupportDirectory, NSUserDomainMask);
while ((state = NSGetNextSearchPathEnumeration(state, pathBuf)))
{
outDir = ExpandTildePath(pathBuf);
::mkdir(outDir.c_str(), 0755);
outDir += "/" LOCALAPPDATA_DIR "/";
::mkdir(outDir.c_str(), 0755);
return true;
}
#elif defined(OMIM_OS_LINUX)
char * path = ::getenv("HOME");
if (path)
{
outDir = path;
outDir += "." LOCALAPPDATA_DIR "/";
::mkdir(outDir.c_str(), 0755);
return true;
}
#else
#error "Implement code for your OS"
#endif
return false;
}
/// @return full path including binary itself
static bool GetPathToBinary(string & outPath)
{
#if defined(OMIM_OS_WINDOWS)
// get path to executable
char pathBuf[MAX_PATH] = {0};
if (0 < ::GetModuleFileNameA(NULL, pathBuf, MAX_PATH))
{
outPath = pathBuf;
return true;
}
#elif defined (OMIM_OS_MAC)
char path[MAXPATHLEN] = {0};
uint32_t pathSize = ARRAY_SIZE(path);
if (0 == ::_NSGetExecutablePath(path, &pathSize))
{
char fixedPath[MAXPATHLEN] = {0};
if (::realpath(path, fixedPath))
{
outPath = fixedPath;
return true;
}
}
#elif defined (OMIM_OS_LINUX)
char path[4096] = {0};
if (0 < ::readlink("/proc/self/exe", path, ARRAY_SIZE(path)))
{
outPath = path;
return true;
}
#else
#error "Add implementation for your operating system, please"
#endif
return false;
}
static bool IsDirectoryWritable(string const & dir)
{
if (!dir.empty())
{
QString qDir = dir.c_str();
if (dir[dir.size() - 1] != '/' && dir[dir.size() - 1] != '\\')
qDir.append('/');
QTemporaryFile file(qDir + "XXXXXX");
if (file.open())
return true;
}
return false;
}
////////////////////////////////////////////////////////////////////////////////////////
class QtPlatform : public BasePlatformImpl
{
static bool IsDirExists(string const & file)
{
QFileInfo fileInfo(file.c_str());
return fileInfo.exists();
}
/// Scans all upper directories for the presence of given directory
/// @param[in] startPath full path to lowest file in hierarchy (usually binary)
/// @param[in] dirName directory name we want to be present
/// @return if not empty, contains full path to existing directory
static string DirFinder(string const & startPath, string dirName)
{
dirName = DIR_SLASH + dirName + DIR_SLASH;
size_t slashPos = startPath.size();
while (slashPos > 0 && (slashPos = startPath.rfind(DIR_SLASH, slashPos - 1)) != string::npos)
{
string const dir = startPath.substr(0, slashPos) + dirName;
if (IsDirExists(dir))
return dir;
}
return string();
}
static bool GetOSSpecificResourcesDir(string const & exePath, string & dir)
{
dir = DirFinder(exePath, RESOURCES_DIR);
return !dir.empty();
}
static void InitResourcesDir(string & dir)
{
// Resources dir can be any "data" folder found in the nearest upper directory,
// where all necessary resources files are present and accessible
string exePath;
CHECK( GetPathToBinary(exePath), ("Can't get full path to executable") );
dir = DirFinder(exePath, MAPDATA_DIR);
if (dir.empty())
{
CHECK( GetOSSpecificResourcesDir(exePath, dir), ("Can't retrieve resources directory") );
}
/// @todo Check all necessary files
}
static void InitWritableDir(string & dir)
{
// Writable dir can be any "data" folder found in the nearest upper directory
// ./data - For Windows portable builds
// ../data
// ../../data - For developer builds
// etc. (for Mac in can be up to 6 levels above due to packages structure
// and if no _writable_ "data" folder was found, User/Application Data/MapsWithMe will be used
string path;
CHECK( GetPathToBinary(path), ("Can't get full path to executable") );
dir = DirFinder(path, MAPDATA_DIR);
if (dir.empty() || !IsDirectoryWritable(dir))
{
CHECK( GetUserWritableDir(dir), ("Can't get User's Application Data writable directory") );
}
}
public:
QtPlatform()
{
InitWritableDir(m_writableDir);
InitResourcesDir(m_resourcesDir);
}
virtual void GetFilesInDir(string const & directory, string const & mask, FilesList & outFiles) const
{
outFiles.clear();
QDir dir(directory.c_str(), mask.c_str(), QDir::Unsorted,
QDir::Files | QDir::Readable | QDir::Dirs | QDir::NoDotAndDotDot);
int const count = dir.count();
for (int i = 0; i < count; ++i)
outFiles.push_back(dir[i].toUtf8().data());
}
virtual bool RenameFileX(string const & original, string const & newName) const
{
return QFile::rename(original.c_str(), newName.c_str());
}
virtual int CpuCores() const
{
#if defined(OMIM_OS_WINDOWS)
SYSTEM_INFO sysinfo;
GetSystemInfo(&sysinfo);
DWORD numCPU = sysinfo.dwNumberOfProcessors;
if (numCPU >= 1)
return static_cast<int>(numCPU);
#elif defined(OMIM_OS_MAC)
int mib[2], numCPU = 0;
size_t len = sizeof(numCPU);
mib[0] = CTL_HW;
mib[1] = HW_AVAILCPU;
sysctl(mib, 2, &numCPU, &len, NULL, 0);
if (numCPU >= 1)
return numCPU;
// second try
mib[1] = HW_NCPU;
len = sizeof(numCPU);
sysctl(mib, 2, &numCPU, &len, NULL, 0);
if (numCPU >= 1)
return numCPU;
#elif defined(OMIM_OS_LINUX)
long numCPU = sysconf(_SC_NPROCESSORS_ONLN);
if (numCPU >= 1)
return static_cast<int>(numCPU);
#endif
return 1;
}
string QtPlatform::DeviceID() const
{
return "DesktopVersion";
}
};
extern "C" Platform & GetPlatform()
{
static QtPlatform platform;
return platform;
}
<commit_msg>Fixed compilation issue<commit_after>#include "platform.hpp"
#include "../base/assert.hpp"
#include "../base/macros.hpp"
#include "../base/logging.hpp"
#include "../defines.hpp"
#include <QtCore/QDir>
#include <QtCore/QFileInfo>
#include <QtCore/QTemporaryFile>
#include "../std/target_os.hpp"
#if defined(OMIM_OS_WINDOWS)
#include "../std/windows.hpp"
#include <shlobj.h>
#define DIR_SLASH "\\"
#elif defined(OMIM_OS_MAC)
#include <stdlib.h>
#include <mach-o/dyld.h>
#include <sys/param.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/sysctl.h>
#include <glob.h>
#include <NSSystemDirectories.h>
#define DIR_SLASH "/"
#elif defined(OMIM_OS_LINUX)
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#define DIR_SLASH "/"
#endif
#include "../base/start_mem_debug.hpp"
// default writable directory name for dev/standalone installs
#define MAPDATA_DIR "data"
// default writable dir name in LocalAppData or ~/Library/AppData/ folders
#define LOCALAPPDATA_DIR "MapsWithMe"
// default Resources read-only dir
#define RESOURCES_DIR "Resources"
#ifdef OMIM_OS_MAC
string ExpandTildePath(char const * path)
{
// ASSERT(path, ());
glob_t globbuf;
string result = path;
if (::glob(path, GLOB_TILDE, NULL, &globbuf) == 0) //success
{
if (globbuf.gl_pathc > 0)
result = globbuf.gl_pathv[0];
globfree(&globbuf);
}
return result;
}
#endif
static bool GetUserWritableDir(string & outDir)
{
#if defined(OMIM_OS_WINDOWS)
char pathBuf[MAX_PATH] = {0};
if (SUCCEEDED(::SHGetFolderPathA(NULL, CSIDL_LOCAL_APPDATA | CSIDL_FLAG_CREATE, NULL, SHGFP_TYPE_CURRENT, pathBuf)))
{
outDir = pathBuf;
::CreateDirectoryA(outDir.c_str(), NULL);
outDir += "\\" LOCALAPPDATA_DIR "\\";
::CreateDirectoryA(outDir.c_str(), NULL);
return true;
}
#elif defined(OMIM_OS_MAC)
char pathBuf[PATH_MAX];
NSSearchPathEnumerationState state = ::NSStartSearchPathEnumeration(NSApplicationSupportDirectory, NSUserDomainMask);
while ((state = NSGetNextSearchPathEnumeration(state, pathBuf)))
{
outDir = ExpandTildePath(pathBuf);
::mkdir(outDir.c_str(), 0755);
outDir += "/" LOCALAPPDATA_DIR "/";
::mkdir(outDir.c_str(), 0755);
return true;
}
#elif defined(OMIM_OS_LINUX)
char * path = ::getenv("HOME");
if (path)
{
outDir = path;
outDir += "." LOCALAPPDATA_DIR "/";
::mkdir(outDir.c_str(), 0755);
return true;
}
#else
#error "Implement code for your OS"
#endif
return false;
}
/// @return full path including binary itself
static bool GetPathToBinary(string & outPath)
{
#if defined(OMIM_OS_WINDOWS)
// get path to executable
char pathBuf[MAX_PATH] = {0};
if (0 < ::GetModuleFileNameA(NULL, pathBuf, MAX_PATH))
{
outPath = pathBuf;
return true;
}
#elif defined (OMIM_OS_MAC)
char path[MAXPATHLEN] = {0};
uint32_t pathSize = ARRAY_SIZE(path);
if (0 == ::_NSGetExecutablePath(path, &pathSize))
{
char fixedPath[MAXPATHLEN] = {0};
if (::realpath(path, fixedPath))
{
outPath = fixedPath;
return true;
}
}
#elif defined (OMIM_OS_LINUX)
char path[4096] = {0};
if (0 < ::readlink("/proc/self/exe", path, ARRAY_SIZE(path)))
{
outPath = path;
return true;
}
#else
#error "Add implementation for your operating system, please"
#endif
return false;
}
static bool IsDirectoryWritable(string const & dir)
{
if (!dir.empty())
{
QString qDir = dir.c_str();
if (dir[dir.size() - 1] != '/' && dir[dir.size() - 1] != '\\')
qDir.append('/');
QTemporaryFile file(qDir + "XXXXXX");
if (file.open())
return true;
}
return false;
}
////////////////////////////////////////////////////////////////////////////////////////
class QtPlatform : public BasePlatformImpl
{
static bool IsDirExists(string const & file)
{
QFileInfo fileInfo(file.c_str());
return fileInfo.exists();
}
/// Scans all upper directories for the presence of given directory
/// @param[in] startPath full path to lowest file in hierarchy (usually binary)
/// @param[in] dirName directory name we want to be present
/// @return if not empty, contains full path to existing directory
static string DirFinder(string const & startPath, string dirName)
{
dirName = DIR_SLASH + dirName + DIR_SLASH;
size_t slashPos = startPath.size();
while (slashPos > 0 && (slashPos = startPath.rfind(DIR_SLASH, slashPos - 1)) != string::npos)
{
string const dir = startPath.substr(0, slashPos) + dirName;
if (IsDirExists(dir))
return dir;
}
return string();
}
static bool GetOSSpecificResourcesDir(string const & exePath, string & dir)
{
dir = DirFinder(exePath, RESOURCES_DIR);
return !dir.empty();
}
static void InitResourcesDir(string & dir)
{
// Resources dir can be any "data" folder found in the nearest upper directory,
// where all necessary resources files are present and accessible
string exePath;
CHECK( GetPathToBinary(exePath), ("Can't get full path to executable") );
dir = DirFinder(exePath, MAPDATA_DIR);
if (dir.empty())
{
CHECK( GetOSSpecificResourcesDir(exePath, dir), ("Can't retrieve resources directory") );
}
/// @todo Check all necessary files
}
static void InitWritableDir(string & dir)
{
// Writable dir can be any "data" folder found in the nearest upper directory
// ./data - For Windows portable builds
// ../data
// ../../data - For developer builds
// etc. (for Mac in can be up to 6 levels above due to packages structure
// and if no _writable_ "data" folder was found, User/Application Data/MapsWithMe will be used
string path;
CHECK( GetPathToBinary(path), ("Can't get full path to executable") );
dir = DirFinder(path, MAPDATA_DIR);
if (dir.empty() || !IsDirectoryWritable(dir))
{
CHECK( GetUserWritableDir(dir), ("Can't get User's Application Data writable directory") );
}
}
public:
QtPlatform()
{
InitWritableDir(m_writableDir);
InitResourcesDir(m_resourcesDir);
}
virtual void GetFilesInDir(string const & directory, string const & mask, FilesList & outFiles) const
{
outFiles.clear();
QDir dir(directory.c_str(), mask.c_str(), QDir::Unsorted,
QDir::Files | QDir::Readable | QDir::Dirs | QDir::NoDotAndDotDot);
int const count = dir.count();
for (int i = 0; i < count; ++i)
outFiles.push_back(dir[i].toUtf8().data());
}
virtual bool RenameFileX(string const & original, string const & newName) const
{
return QFile::rename(original.c_str(), newName.c_str());
}
virtual int CpuCores() const
{
#if defined(OMIM_OS_WINDOWS)
SYSTEM_INFO sysinfo;
GetSystemInfo(&sysinfo);
DWORD numCPU = sysinfo.dwNumberOfProcessors;
if (numCPU >= 1)
return static_cast<int>(numCPU);
#elif defined(OMIM_OS_MAC)
int mib[2], numCPU = 0;
size_t len = sizeof(numCPU);
mib[0] = CTL_HW;
mib[1] = HW_AVAILCPU;
sysctl(mib, 2, &numCPU, &len, NULL, 0);
if (numCPU >= 1)
return numCPU;
// second try
mib[1] = HW_NCPU;
len = sizeof(numCPU);
sysctl(mib, 2, &numCPU, &len, NULL, 0);
if (numCPU >= 1)
return numCPU;
#elif defined(OMIM_OS_LINUX)
long numCPU = sysconf(_SC_NPROCESSORS_ONLN);
if (numCPU >= 1)
return static_cast<int>(numCPU);
#endif
return 1;
}
string DeviceID() const
{
return "DesktopVersion";
}
};
extern "C" Platform & GetPlatform()
{
static QtPlatform platform;
return platform;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: glyphset.hxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: rt $ $Date: 2004-09-08 14:01:23 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _PSPRINT_GLYPHSET_HXX_
#define _PSPRINT_GLYPHSET_HXX_
#ifndef _PSPRINT_FONTMANAGER_HXX_
#include <psprint/fontmanager.hxx>
#endif
#ifndef _OSL_FILE_HXX_
#include <osl/file.hxx>
#endif
#ifndef _RTL_STRING_HXX_
#include <rtl/string.hxx>
#endif
#ifndef _SV_GEN_HXX
#include <tools/gen.hxx>
#endif
#ifndef __SGI_STL_LIST
#include <list>
#endif
#include <hash_map>
namespace psp {
class PrinterGfx;
class PrintFontManager;
class GlyphSet
{
private:
sal_Int32 mnFontID;
sal_Bool mbVertical;
rtl::OString maBaseName;
fonttype::type meBaseType;
rtl_TextEncoding mnBaseEncoding;
bool mbUseFontEncoding;
typedef std::hash_map< sal_Unicode, sal_uInt8 > char_map_t;
typedef std::list< char_map_t > char_list_t;
typedef std::hash_map< sal_uInt32, sal_uInt8 > glyph_map_t;
typedef std::list< glyph_map_t > glyph_list_t;
char_list_t maCharList;
glyph_list_t maGlyphList;
rtl::OString GetGlyphSetName (sal_Int32 nGlyphSetID);
rtl::OString GetCharSetName (sal_Int32 nGlyphSetID);
sal_Int32 GetGlyphSetEncoding (sal_Int32 nGlyphSetID);
rtl::OString GetGlyphSetEncodingName (sal_Int32 nGlyphSetID);
rtl::OString GetReencodedFontName (sal_Int32 nGlyphSetID);
void PSDefineReencodedFont (osl::File* pOutFile,
sal_Int32 nGlyphSetID);
sal_Bool GetCharID (sal_Unicode nChar,
sal_uChar* nOutGlyphID, sal_Int32* nOutGlyphSetID);
sal_Bool LookupCharID (sal_Unicode nChar,
sal_uChar* nOutGlyphID, sal_Int32* nOutGlyphSetID);
sal_Bool AddCharID (sal_Unicode nChar,
sal_uChar* nOutGlyphID,
sal_Int32* nOutGlyphSetID);
sal_Bool GetGlyphID (sal_uInt32 nGlyph, sal_Unicode nUnicode,
sal_uChar* nOutGlyphID, sal_Int32* nOutGlyphSetID);
sal_Bool LookupGlyphID (sal_uInt32 nGlyph,
sal_uChar* nOutGlyphID, sal_Int32* nOutGlyphSetID);
sal_Bool AddGlyphID (sal_uInt32 nGlyph, sal_Unicode nUnicode,
sal_uChar* nOutGlyphID,
sal_Int32* nOutGlyphSetID);
void AddNotdef (char_map_t &rCharMap);
void AddNotdef (glyph_map_t &rGlyphMap);
sal_uChar GetAnsiMapping (sal_Unicode nUnicodeChar);
sal_uChar GetSymbolMapping (sal_Unicode nUnicodeChar);
void ImplDrawText (PrinterGfx &rGfx, const Point& rPoint,
const sal_Unicode* pStr, sal_Int16 nLen);
void ImplDrawText (PrinterGfx &rGfx, const Point& rPoint,
const sal_Unicode* pStr, sal_Int16 nLen,
const sal_Int32* pDeltaArray);
public:
GlyphSet ();
GlyphSet (sal_Int32 nFontID, sal_Bool bVertical);
~GlyphSet ();
sal_Int32 GetFontID ();
fonttype::type GetFontType ();
static rtl::OString
GetReencodedFontName (rtl_TextEncoding nEnc,
const rtl::OString &rFontName);
static rtl::OString
GetGlyphSetEncodingName (rtl_TextEncoding nEnc,
const rtl::OString &rFontName);
sal_Bool IsVertical ();
sal_Bool SetFont (sal_Int32 nFontID, sal_Bool bVertical);
void DrawText (PrinterGfx &rGfx, const Point& rPoint,
const sal_Unicode* pStr, sal_Int16 nLen,
const sal_Int32* pDeltaArray = NULL);
void DrawGlyphs (PrinterGfx& rGfx,
const Point& rPoint,
const sal_uInt32* pGlyphIds,
const sal_Unicode* pUnicodes,
sal_Int16 nLen,
const sal_Int32* pDeltaArray );
sal_Bool PSUploadEncoding(osl::File* pOutFile, PrinterGfx &rGfx);
sal_Bool PSUploadFont (osl::File& rOutFile, PrinterGfx &rGfx, bool bAsType42, std::list< rtl::OString >& rSuppliedFonts );
};
} /* namespace psp */
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.8.54); FILE MERGED 2005/09/05 12:06:48 rt 1.8.54.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: glyphset.hxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: rt $ $Date: 2005-09-08 16:46:19 $
*
* 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 _PSPRINT_GLYPHSET_HXX_
#define _PSPRINT_GLYPHSET_HXX_
#ifndef _PSPRINT_FONTMANAGER_HXX_
#include <psprint/fontmanager.hxx>
#endif
#ifndef _OSL_FILE_HXX_
#include <osl/file.hxx>
#endif
#ifndef _RTL_STRING_HXX_
#include <rtl/string.hxx>
#endif
#ifndef _SV_GEN_HXX
#include <tools/gen.hxx>
#endif
#ifndef __SGI_STL_LIST
#include <list>
#endif
#include <hash_map>
namespace psp {
class PrinterGfx;
class PrintFontManager;
class GlyphSet
{
private:
sal_Int32 mnFontID;
sal_Bool mbVertical;
rtl::OString maBaseName;
fonttype::type meBaseType;
rtl_TextEncoding mnBaseEncoding;
bool mbUseFontEncoding;
typedef std::hash_map< sal_Unicode, sal_uInt8 > char_map_t;
typedef std::list< char_map_t > char_list_t;
typedef std::hash_map< sal_uInt32, sal_uInt8 > glyph_map_t;
typedef std::list< glyph_map_t > glyph_list_t;
char_list_t maCharList;
glyph_list_t maGlyphList;
rtl::OString GetGlyphSetName (sal_Int32 nGlyphSetID);
rtl::OString GetCharSetName (sal_Int32 nGlyphSetID);
sal_Int32 GetGlyphSetEncoding (sal_Int32 nGlyphSetID);
rtl::OString GetGlyphSetEncodingName (sal_Int32 nGlyphSetID);
rtl::OString GetReencodedFontName (sal_Int32 nGlyphSetID);
void PSDefineReencodedFont (osl::File* pOutFile,
sal_Int32 nGlyphSetID);
sal_Bool GetCharID (sal_Unicode nChar,
sal_uChar* nOutGlyphID, sal_Int32* nOutGlyphSetID);
sal_Bool LookupCharID (sal_Unicode nChar,
sal_uChar* nOutGlyphID, sal_Int32* nOutGlyphSetID);
sal_Bool AddCharID (sal_Unicode nChar,
sal_uChar* nOutGlyphID,
sal_Int32* nOutGlyphSetID);
sal_Bool GetGlyphID (sal_uInt32 nGlyph, sal_Unicode nUnicode,
sal_uChar* nOutGlyphID, sal_Int32* nOutGlyphSetID);
sal_Bool LookupGlyphID (sal_uInt32 nGlyph,
sal_uChar* nOutGlyphID, sal_Int32* nOutGlyphSetID);
sal_Bool AddGlyphID (sal_uInt32 nGlyph, sal_Unicode nUnicode,
sal_uChar* nOutGlyphID,
sal_Int32* nOutGlyphSetID);
void AddNotdef (char_map_t &rCharMap);
void AddNotdef (glyph_map_t &rGlyphMap);
sal_uChar GetAnsiMapping (sal_Unicode nUnicodeChar);
sal_uChar GetSymbolMapping (sal_Unicode nUnicodeChar);
void ImplDrawText (PrinterGfx &rGfx, const Point& rPoint,
const sal_Unicode* pStr, sal_Int16 nLen);
void ImplDrawText (PrinterGfx &rGfx, const Point& rPoint,
const sal_Unicode* pStr, sal_Int16 nLen,
const sal_Int32* pDeltaArray);
public:
GlyphSet ();
GlyphSet (sal_Int32 nFontID, sal_Bool bVertical);
~GlyphSet ();
sal_Int32 GetFontID ();
fonttype::type GetFontType ();
static rtl::OString
GetReencodedFontName (rtl_TextEncoding nEnc,
const rtl::OString &rFontName);
static rtl::OString
GetGlyphSetEncodingName (rtl_TextEncoding nEnc,
const rtl::OString &rFontName);
sal_Bool IsVertical ();
sal_Bool SetFont (sal_Int32 nFontID, sal_Bool bVertical);
void DrawText (PrinterGfx &rGfx, const Point& rPoint,
const sal_Unicode* pStr, sal_Int16 nLen,
const sal_Int32* pDeltaArray = NULL);
void DrawGlyphs (PrinterGfx& rGfx,
const Point& rPoint,
const sal_uInt32* pGlyphIds,
const sal_Unicode* pUnicodes,
sal_Int16 nLen,
const sal_Int32* pDeltaArray );
sal_Bool PSUploadEncoding(osl::File* pOutFile, PrinterGfx &rGfx);
sal_Bool PSUploadFont (osl::File& rOutFile, PrinterGfx &rGfx, bool bAsType42, std::list< rtl::OString >& rSuppliedFonts );
};
} /* namespace psp */
#endif
<|endoftext|> |
<commit_before>//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html
#include "StackGenerator.h"
#include "CastUniquePointer.h"
#include "libmesh/replicated_mesh.h"
#include "libmesh/distributed_mesh.h"
#include "libmesh/boundary_info.h"
#include "libmesh/mesh_modification.h"
#include "libmesh/bounding_box.h"
#include "libmesh/mesh_tools.h"
#include "libmesh/point.h"
#include <typeinfo>
registerMooseObject("MooseApp", StackGenerator);
template <>
InputParameters
validParams<StackGenerator>()
{
InputParameters params = validParams<MeshGenerator>();
params.addRequiredParam<std::vector<MeshGeneratorName>>("inputs", "The meshes we want to stitch together");
params.addParam<Real>("bottom_height", 0, "The height of the bottom of the final mesh");
// z boundary names
params.addParam<BoundaryName>("front_boundary", "front", "name of the front (z) boundary");
params.addParam<BoundaryName>("back_boundary", "back", "name of the back (z) boundary");
params.addClassDescription("Use the supplied meshes and stitch them on top of each other");
return params;
}
StackGenerator::StackGenerator(const InputParameters & parameters)
: MeshGenerator(parameters),
_input_names(getParam<std::vector<MeshGeneratorName>>("inputs")),
_bottom_height(getParam<Real>("bottom_height"))
{
// Grab the input meshes
_mesh_ptrs.reserve(_input_names.size());
for (auto i = beginIndex(_input_names); i < _input_names.size(); ++i)
_mesh_ptrs.push_back(&getMeshByName(_input_names[i]));
}
std::unique_ptr<MeshBase>
StackGenerator::generate()
{
std::unique_ptr<ReplicatedMesh> mesh = dynamic_pointer_cast<ReplicatedMesh>(*_mesh_ptrs[0]);
if (mesh->mesh_dimension() != 3 )
mooseError("The first mesh is not in 3D !");
// Reserve spaces for the other meshes (no need to store the first one another time)
_meshes.reserve(_input_names.size() - 1);
// Read in all of the other meshes
for (auto i = beginIndex(_input_names, 1); i < _input_names.size(); ++i)
_meshes.push_back(dynamic_pointer_cast<ReplicatedMesh>(*_mesh_ptrs[i]));
// Check that we have 3D meshes
for (auto i = beginIndex(_meshes); i < _meshes.size(); ++i)
if (_meshes[i]->mesh_dimension() != 3)
mooseError("Mesh from MeshGenerator : ", _input_names[i+1], " is not in 3D.");
boundary_id_type front =
mesh->get_boundary_info().get_id_by_name(getParam<BoundaryName>("front_boundary"));
boundary_id_type back =
mesh->get_boundary_info().get_id_by_name(getParam<BoundaryName>("back_boundary"));
// Getting the z width of each mesh
std::vector<Real> z_heights;
z_heights.push_back(zWidth(*mesh) + _bottom_height);
for (auto i = beginIndex(_meshes); i < _meshes.size(); ++i)
z_heights.push_back(zWidth(*_meshes[i]) + *z_heights.rbegin());
MeshTools::Modification::translate(*mesh, 0, 0, _bottom_height);
for (auto i = beginIndex(_meshes); i < _meshes.size(); ++i)
{
MeshTools::Modification::translate(*_meshes[i], 0, 0, z_heights[i]);
mesh->stitch_meshes(*_meshes[i], front, back, TOLERANCE, /*clear_stitched_boundary_ids=*/true);
}
return dynamic_pointer_cast<MeshBase>(mesh);
}
Real
StackGenerator::zWidth(const MeshBase & mesh)
{
std::set<subdomain_id_type> sub_ids;
mesh.subdomain_ids(sub_ids);
BoundingBox bbox(Point(std::numeric_limits<Real>::max(), std::numeric_limits<Real>::max(), std::numeric_limits<Real>::max()),
Point(std::numeric_limits<Real>::lowest(), std::numeric_limits<Real>::lowest(), std::numeric_limits<Real>::lowest()));
for (auto id : sub_ids)
{
BoundingBox sub_bbox = MeshTools::create_subdomain_bounding_box(mesh, id);
bbox.union_with(sub_bbox);
}
return bbox.max()(2) - bbox.min()(2);
}
<commit_msg>Apply clang-format.<commit_after>//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html
#include "StackGenerator.h"
#include "CastUniquePointer.h"
#include "libmesh/replicated_mesh.h"
#include "libmesh/distributed_mesh.h"
#include "libmesh/boundary_info.h"
#include "libmesh/mesh_modification.h"
#include "libmesh/bounding_box.h"
#include "libmesh/mesh_tools.h"
#include "libmesh/point.h"
#include <typeinfo>
registerMooseObject("MooseApp", StackGenerator);
template <>
InputParameters
validParams<StackGenerator>()
{
InputParameters params = validParams<MeshGenerator>();
params.addRequiredParam<std::vector<MeshGeneratorName>>("inputs",
"The meshes we want to stitch together");
params.addParam<Real>("bottom_height", 0, "The height of the bottom of the final mesh");
// z boundary names
params.addParam<BoundaryName>("front_boundary", "front", "name of the front (z) boundary");
params.addParam<BoundaryName>("back_boundary", "back", "name of the back (z) boundary");
params.addClassDescription("Use the supplied meshes and stitch them on top of each other");
return params;
}
StackGenerator::StackGenerator(const InputParameters & parameters)
: MeshGenerator(parameters),
_input_names(getParam<std::vector<MeshGeneratorName>>("inputs")),
_bottom_height(getParam<Real>("bottom_height"))
{
// Grab the input meshes
_mesh_ptrs.reserve(_input_names.size());
for (auto i = beginIndex(_input_names); i < _input_names.size(); ++i)
_mesh_ptrs.push_back(&getMeshByName(_input_names[i]));
}
std::unique_ptr<MeshBase>
StackGenerator::generate()
{
std::unique_ptr<ReplicatedMesh> mesh = dynamic_pointer_cast<ReplicatedMesh>(*_mesh_ptrs[0]);
if (mesh->mesh_dimension() != 3)
mooseError("The first mesh is not in 3D !");
// Reserve spaces for the other meshes (no need to store the first one another time)
_meshes.reserve(_input_names.size() - 1);
// Read in all of the other meshes
for (auto i = beginIndex(_input_names, 1); i < _input_names.size(); ++i)
_meshes.push_back(dynamic_pointer_cast<ReplicatedMesh>(*_mesh_ptrs[i]));
// Check that we have 3D meshes
for (auto i = beginIndex(_meshes); i < _meshes.size(); ++i)
if (_meshes[i]->mesh_dimension() != 3)
mooseError("Mesh from MeshGenerator : ", _input_names[i + 1], " is not in 3D.");
boundary_id_type front =
mesh->get_boundary_info().get_id_by_name(getParam<BoundaryName>("front_boundary"));
boundary_id_type back =
mesh->get_boundary_info().get_id_by_name(getParam<BoundaryName>("back_boundary"));
// Getting the z width of each mesh
std::vector<Real> z_heights;
z_heights.push_back(zWidth(*mesh) + _bottom_height);
for (auto i = beginIndex(_meshes); i < _meshes.size(); ++i)
z_heights.push_back(zWidth(*_meshes[i]) + *z_heights.rbegin());
MeshTools::Modification::translate(*mesh, 0, 0, _bottom_height);
for (auto i = beginIndex(_meshes); i < _meshes.size(); ++i)
{
MeshTools::Modification::translate(*_meshes[i], 0, 0, z_heights[i]);
mesh->stitch_meshes(*_meshes[i], front, back, TOLERANCE, /*clear_stitched_boundary_ids=*/true);
}
return dynamic_pointer_cast<MeshBase>(mesh);
}
Real
StackGenerator::zWidth(const MeshBase & mesh)
{
std::set<subdomain_id_type> sub_ids;
mesh.subdomain_ids(sub_ids);
BoundingBox bbox(Point(std::numeric_limits<Real>::max(),
std::numeric_limits<Real>::max(),
std::numeric_limits<Real>::max()),
Point(std::numeric_limits<Real>::lowest(),
std::numeric_limits<Real>::lowest(),
std::numeric_limits<Real>::lowest()));
for (auto id : sub_ids)
{
BoundingBox sub_bbox = MeshTools::create_subdomain_bounding_box(mesh, id);
bbox.union_with(sub_bbox);
}
return bbox.max()(2) - bbox.min()(2);
}
<|endoftext|> |
<commit_before>#include <QtGlobal>
#include <QFileInfo>
#include <QDir>
#include <QProcess>
#include <QtDebug>
void runModelMoc(const QString& header, const QStringList& arguments)
{
QFile inf(header);
if(!inf.open(QFile::ReadOnly))
qFatal("Could not open header file for reading");
QTextStream in(&inf);
QProcess p;
p.setProcessChannelMode( QProcess::ForwardedChannels );
p.start(QString(QT_MOC_PATH), arguments, QIODevice::WriteOnly);
if(!p.waitForStarted()) {
qFatal("mmoc: failed to run command '%s'", QT_MOC_PATH);
}
QString spaces = "\\s*";
QString comma = ",";
QString colon = ":";
QString parenO = "\\(";
QString parenC = "\\)";
QString emptyParen = "\\(\\)";
QString angleO = "<";
QString angleC = ">";
QString braceO = "\\{";
QString nameSpace = "(?:\\w+::)";
QString typeName = "\\w+";
QString pointer = "\\*";
QString templateName = "\\w+";
QString plainParam = "(\\w+)";
QString boolParam = "(true|false)";
QString anyParam = "(.+)";
QRegExp propertyRegExp(
spaces+
"M_MODEL_PROPERTY"+
spaces+parenO+spaces+
"("+
"(?:"+
nameSpace+"{,1}"+
typeName+
spaces+
pointer+"{,1}"+
")"+
"|"+
"(?:"+
templateName+
angleO+
spaces+
typeName+
spaces+
pointer+"{,1}"+
spaces+
angleC+
")"+
")"+
spaces+comma+spaces+
plainParam+
spaces+comma+spaces+
plainParam+
spaces+comma+spaces+
plainParam+
spaces+comma+spaces+
anyParam+
spaces+parenC+spaces );
QRegExp propertyPtrRegExp(
spaces+
"M_MODEL_PTR_PROPERTY"+
spaces+parenO+spaces+
"("+
"(?:"+
nameSpace+"{,1}"+
typeName+
spaces+
pointer+"{,1}"+
spaces+
")"+
"|"+
"(?:"+
templateName+
angleO+
spaces+
typeName+
spaces+
pointer+"{,1}"+
spaces+
angleC+
")"+
")"+
spaces+comma+spaces+
plainParam+
spaces+comma+spaces+
plainParam+
spaces+comma+spaces+
boolParam+
spaces+comma+spaces+
anyParam+
spaces+parenC+spaces );
QString line;
while(true) {
line = in.readLine();
if(line.isNull()) {
break;
}
line.replace(propertyRegExp, " Q_PROPERTY(\\1 \\2 READ \\2 WRITE set\\3)");
line.replace(propertyPtrRegExp, " Q_PROPERTY(\\1 \\2 READ \\2 WRITE set\\3)");
p.write(QString(line + "\n").toLatin1());
}
p.closeWriteChannel();
if(!p.waitForFinished()) {
qFatal("mmoc: failed to run command '%s'", QT_MOC_PATH);
}
}
void runStyleMoc(const QString& header, const QStringList& arguments)
{
QFile inf(header);
if(!inf.open(QFile::ReadOnly))
qFatal("Could not open header file for reading");
QTextStream in(&inf);
QProcess p;
p.setProcessChannelMode( QProcess::ForwardedChannels );
p.start(QString(QT_MOC_PATH), arguments);
if(!p.waitForStarted()) {
qFatal("mmoc: failed to run command '%s'", QT_MOC_PATH);
}
QRegExp attributeRegExp("\\s*M_STYLE_ATTRIBUTE\\s*\\(\\s*(\\w+\\:*\\w*)\\s*,\\s*(\\w+)\\s*,\\s*(\\w+)\\s*\\)\\s*");
QRegExp attributePtrRegExp("\\s*M_STYLE_PTR_ATTRIBUTE\\s*\\(\\s*(\\w+\\:*\\w*\\s*\\*+)\\s*,\\s*(\\w+)\\s*,\\s*(\\w+)\\s*\\)\\s*");
QString line;
while(true) {
line = in.readLine();
if(line.isNull()) {
break;
}
line.replace(attributeRegExp, " Q_PROPERTY(\\1 \\2 READ \\2 WRITE set\\3)");
line.replace(attributePtrRegExp, " Q_PROPERTY(const \\1 \\2 READ \\2 WRITE set\\3)");
p.write(QString(line + "\n").toLatin1());
}
p.closeWriteChannel();
if(!p.waitForFinished()) {
qFatal("mmoc: failed to run command '%s'", QT_MOC_PATH);
}
}
void runQtMoc(const QStringList& arguments)
{
QProcess p;
p.setProcessChannelMode( QProcess::ForwardedChannels );
p.start(QString(QT_MOC_PATH), arguments);
if(!p.waitForStarted()) {
qFatal("mmoc: failed to run command '%s'", QT_MOC_PATH);
}
if(!p.waitForFinished()) {
qFatal("mmoc: failed to run command '%s'", QT_MOC_PATH);
}
}
enum HeaderType {
Model,
Style
};
int main(int argc, const char *argv[])
{
HeaderType type=Model;
QStringList commandLineParameters;
QString filename;
for(int i=1; i<argc; ++i) {
if(QString(argv[i]).endsWith("style.h")) {
type = Style;
filename = argv[i];
} else if(QString(argv[i]).endsWith("model.h")) {
type = Model;
filename = argv[i];
} else {
commandLineParameters << QString(argv[i]);
}
}
if(filename.isEmpty()) {
runQtMoc(commandLineParameters);
} else {
commandLineParameters << "-f" + filename;
if(type == Model) {
runModelMoc(filename, commandLineParameters);
} else if(type == Style) {
runStyleMoc(filename, commandLineParameters);
}
}
return 0; //success
}
<commit_msg>Changes: fix mmoc handling of qt moc exit codes<commit_after>#include <QtGlobal>
#include <QFileInfo>
#include <QDir>
#include <QProcess>
#include <QtDebug>
void runModelMoc(const QString& header, const QStringList& arguments)
{
QFile inf(header);
if(!inf.open(QFile::ReadOnly))
qFatal("Could not open header file for reading");
QTextStream in(&inf);
QProcess p;
p.setProcessChannelMode( QProcess::ForwardedChannels );
p.start(QString(QT_MOC_PATH), arguments, QIODevice::WriteOnly);
if(!p.waitForStarted()) {
qFatal("mmoc: failed to run command '%s'", QT_MOC_PATH);
}
QString spaces = "\\s*";
QString comma = ",";
QString colon = ":";
QString parenO = "\\(";
QString parenC = "\\)";
QString emptyParen = "\\(\\)";
QString angleO = "<";
QString angleC = ">";
QString braceO = "\\{";
QString nameSpace = "(?:\\w+::)";
QString typeName = "\\w+";
QString pointer = "\\*";
QString templateName = "\\w+";
QString plainParam = "(\\w+)";
QString boolParam = "(true|false)";
QString anyParam = "(.+)";
QRegExp propertyRegExp(
spaces+
"M_MODEL_PROPERTY"+
spaces+parenO+spaces+
"("+
"(?:"+
nameSpace+"{,1}"+
typeName+
spaces+
pointer+"{,1}"+
")"+
"|"+
"(?:"+
templateName+
angleO+
spaces+
typeName+
spaces+
pointer+"{,1}"+
spaces+
angleC+
")"+
")"+
spaces+comma+spaces+
plainParam+
spaces+comma+spaces+
plainParam+
spaces+comma+spaces+
plainParam+
spaces+comma+spaces+
anyParam+
spaces+parenC+spaces );
QRegExp propertyPtrRegExp(
spaces+
"M_MODEL_PTR_PROPERTY"+
spaces+parenO+spaces+
"("+
"(?:"+
nameSpace+"{,1}"+
typeName+
spaces+
pointer+"{,1}"+
spaces+
")"+
"|"+
"(?:"+
templateName+
angleO+
spaces+
typeName+
spaces+
pointer+"{,1}"+
spaces+
angleC+
")"+
")"+
spaces+comma+spaces+
plainParam+
spaces+comma+spaces+
plainParam+
spaces+comma+spaces+
boolParam+
spaces+comma+spaces+
anyParam+
spaces+parenC+spaces );
QString line;
while(true) {
line = in.readLine();
if(line.isNull()) {
break;
}
line.replace(propertyRegExp, " Q_PROPERTY(\\1 \\2 READ \\2 WRITE set\\3)");
line.replace(propertyPtrRegExp, " Q_PROPERTY(\\1 \\2 READ \\2 WRITE set\\3)");
p.write(QString(line + "\n").toLatin1());
}
p.closeWriteChannel();
if(!p.waitForFinished()) {
qFatal("mmoc: failed to run command '%s'", QT_MOC_PATH);
}
if ( p.exitCode() != 0 ) {
qFatal("mmoc: qt moc ended with error: %i", p.exitCode() );
}
}
void runStyleMoc(const QString& header, const QStringList& arguments)
{
QFile inf(header);
if(!inf.open(QFile::ReadOnly))
qFatal("Could not open header file for reading");
QTextStream in(&inf);
QProcess p;
p.setProcessChannelMode( QProcess::ForwardedChannels );
p.start(QString(QT_MOC_PATH), arguments);
if(!p.waitForStarted()) {
qFatal("mmoc: failed to run command '%s'", QT_MOC_PATH);
}
QRegExp attributeRegExp("\\s*M_STYLE_ATTRIBUTE\\s*\\(\\s*(\\w+\\:*\\w*)\\s*,\\s*(\\w+)\\s*,\\s*(\\w+)\\s*\\)\\s*");
QRegExp attributePtrRegExp("\\s*M_STYLE_PTR_ATTRIBUTE\\s*\\(\\s*(\\w+\\:*\\w*\\s*\\*+)\\s*,\\s*(\\w+)\\s*,\\s*(\\w+)\\s*\\)\\s*");
QString line;
while(true) {
line = in.readLine();
if(line.isNull()) {
break;
}
line.replace(attributeRegExp, " Q_PROPERTY(\\1 \\2 READ \\2 WRITE set\\3)");
line.replace(attributePtrRegExp, " Q_PROPERTY(const \\1 \\2 READ \\2 WRITE set\\3)");
p.write(QString(line + "\n").toLatin1());
}
p.closeWriteChannel();
if(!p.waitForFinished()) {
qFatal("mmoc: failed to run command '%s'", QT_MOC_PATH);
}
if ( p.exitCode() != 0 ) {
qFatal("mmoc: qt moc ended with error: %i", p.exitCode() );
}
}
void runQtMoc(const QStringList& arguments)
{
QProcess p;
p.setProcessChannelMode( QProcess::ForwardedChannels );
p.start(QString(QT_MOC_PATH), arguments);
if(!p.waitForStarted()) {
qFatal("mmoc: failed to run command '%s'", QT_MOC_PATH);
}
if(!p.waitForFinished()) {
qFatal("mmoc: failed to run command '%s'", QT_MOC_PATH);
}
if ( p.exitCode() != 0 ) {
qFatal("mmoc: qt moc ended with error: %i", p.exitCode() );
}
}
enum HeaderType {
Model,
Style
};
int main(int argc, const char *argv[])
{
HeaderType type=Model;
QStringList commandLineParameters;
QString filename;
for(int i=1; i<argc; ++i) {
if(QString(argv[i]).endsWith("style.h")) {
type = Style;
filename = argv[i];
} else if(QString(argv[i]).endsWith("model.h")) {
type = Model;
filename = argv[i];
} else {
commandLineParameters << QString(argv[i]);
}
}
if(filename.isEmpty()) {
runQtMoc(commandLineParameters);
} else {
commandLineParameters << "-f" + filename;
if(type == Model) {
runModelMoc(filename, commandLineParameters);
} else if(type == Style) {
runStyleMoc(filename, commandLineParameters);
}
}
return 0; //success
}
<|endoftext|> |
<commit_before>/// \file RNTupleDescriptorFmt.cxx
/// \ingroup NTuple ROOT7
/// \author Jakob Blomer <jblomer@cern.ch>
/// \date 2019-08-25
/// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback
/// is welcome!
/*************************************************************************
* Copyright (C) 1995-2019, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#include <ROOT/RColumnElement.hxx>
#include <ROOT/RColumnModel.hxx>
#include <ROOT/RNTupleDescriptor.hxx>
#include <ROOT/RNTupleUtil.hxx>
#include <algorithm>
#include <iomanip>
#include <ostream>
#include <unordered_map>
#include <vector>
namespace {
struct ClusterInfo {
std::uint64_t fFirstEntry = 0;
std::uint32_t fNPages = 0;
std::uint32_t fNEntries = 0;
std::uint32_t fBytesOnStorage = 0;
std::uint32_t fBytesInMemory = 0;
bool operator ==(const ClusterInfo &other) const {
return fFirstEntry == other.fFirstEntry;
}
bool operator <(const ClusterInfo &other) const {
return fFirstEntry < other.fFirstEntry;
}
};
struct ColumnInfo {
ROOT::Experimental::DescriptorId_t fColumnId = 0;
ROOT::Experimental::DescriptorId_t fFieldId = 0;
std::uint64_t fLocalOrder = 0;
std::uint64_t fNElements = 0;
std::uint64_t fNPages = 0;
std::uint64_t fBytesOnStorage = 0;
std::uint32_t fElementSize = 0;
ROOT::Experimental::EColumnType fType;
std::string fFieldName;
std::string fFieldDescription;
bool operator <(const ColumnInfo &other) const {
if (fFieldName == other.fFieldName)
return fLocalOrder < other.fLocalOrder;
return fFieldName < other.fFieldName;
}
};
static std::string GetFieldName(ROOT::Experimental::DescriptorId_t fieldId,
const ROOT::Experimental::RNTupleDescriptor &ntupleDesc)
{
const auto &fieldDesc = ntupleDesc.GetFieldDescriptor(fieldId);
if (fieldDesc.GetParentId() == ROOT::Experimental::kInvalidDescriptorId)
return fieldDesc.GetFieldName();
return GetFieldName(fieldDesc.GetParentId(), ntupleDesc) + "." + fieldDesc.GetFieldName();
}
static std::string GetFieldDescription(ROOT::Experimental::DescriptorId_t fFieldId,
const ROOT::Experimental::RNTupleDescriptor &ntupleDesc)
{
const auto &fieldDesc = ntupleDesc.GetFieldDescriptor(fFieldId);
return fieldDesc.GetFieldDescription();
}
} // anonymous namespace
void ROOT::Experimental::RNTupleDescriptor::PrintInfo(std::ostream &output) const
{
std::vector<ColumnInfo> columns;
std::vector<ClusterInfo> clusters;
std::unordered_map<DescriptorId_t, unsigned int> cluster2Idx;
for (const auto &cluster : fClusterDescriptors) {
ClusterInfo info;
info.fFirstEntry = cluster.second.GetFirstEntryIndex();
info.fNEntries = cluster.second.GetNEntries();
cluster2Idx[cluster.first] = clusters.size();
clusters.emplace_back(info);
}
std::uint64_t bytesOnStorage = 0;
std::uint64_t bytesInMemory = 0;
std::uint64_t nPages = 0;
int compression = -1;
for (const auto &column : fColumnDescriptors) {
// We generate the default memory representation for the given column type in order
// to report the size _in memory_ of column elements
auto elementSize = Detail::RColumnElementBase::Generate(column.second.GetModel().GetType())->GetSize();
ColumnInfo info;
info.fColumnId = column.second.GetId();
info.fFieldId = column.second.GetFieldId();
info.fLocalOrder = column.second.GetIndex();
info.fElementSize = elementSize;
info.fType = column.second.GetModel().GetType();
for (const auto &cluster : fClusterDescriptors) {
auto columnRange = cluster.second.GetColumnRange(column.first);
info.fNElements += columnRange.fNElements;
if (compression == -1) {
compression = columnRange.fCompressionSettings;
}
const auto &pageRange = cluster.second.GetPageRange(column.first);
auto idx = cluster2Idx[cluster.first];
for (const auto &page : pageRange.fPageInfos) {
bytesOnStorage += page.fLocator.fBytesOnStorage;
bytesInMemory += page.fNElements * elementSize;
clusters[idx].fBytesOnStorage += page.fLocator.fBytesOnStorage;
clusters[idx].fBytesInMemory += page.fNElements * elementSize;
++clusters[idx].fNPages;
info.fBytesOnStorage += page.fLocator.fBytesOnStorage;
++info.fNPages;
++nPages;
}
}
columns.emplace_back(info);
}
auto headerSize = GetHeaderSize();
auto footerSize = GetFooterSize();
output << "============================================================" << std::endl;
output << "NTUPLE: " << GetName() << std::endl;
output << "Compression: " << compression << std::endl;
output << "------------------------------------------------------------" << std::endl;
output << " # Entries: " << GetNEntries() << std::endl;
output << " # Fields: " << GetNFields() << std::endl;
output << " # Columns: " << GetNColumns() << std::endl;
output << " # Pages: " << nPages << std::endl;
output << " # Clusters: " << GetNClusters() << std::endl;
output << " Size on storage: " << bytesOnStorage << " B" << std::endl;
output << " Compression rate: " << std::fixed << std::setprecision(2)
<< float(bytesInMemory) / float(bytesOnStorage) << std::endl;
output << " Header size: " << headerSize << " B" << std::endl;
output << " Footer size: " << footerSize << " B" << std::endl;
output << " Meta-data / data: " << std::fixed << std::setprecision(3)
<< float(headerSize + footerSize) / float(bytesOnStorage) << std::endl;
output << "------------------------------------------------------------" << std::endl;
output << "CLUSTER DETAILS" << std::endl;
output << "------------------------------------------------------------" << std::endl;
std::sort(clusters.begin(), clusters.end());
for (unsigned int i = 0; i < clusters.size(); ++i) {
output << " # " << std::setw(5) << i
<< " Entry range: [" << clusters[i].fFirstEntry << ".."
<< clusters[i].fFirstEntry + clusters[i].fNEntries - 1 << "] -- " << clusters[i].fNEntries << std::endl;
output << " "
<< " # Pages: " << clusters[i].fNPages << std::endl;
output << " "
<< " Size on storage: " << clusters[i].fBytesOnStorage << " B" << std::endl;
output << " "
<< " Compression: " << std::fixed << std::setprecision(2)
<< float(clusters[i].fBytesInMemory) / float(float(clusters[i].fBytesOnStorage)) << std::endl;
}
output << "------------------------------------------------------------" << std::endl;
output << "COLUMN DETAILS" << std::endl;
output << "------------------------------------------------------------" << std::endl;
for (auto &col : columns) {
col.fFieldName = GetFieldName(col.fFieldId, *this).substr(1);
col.fFieldDescription = GetFieldDescription(col.fFieldId, *this);
}
std::sort(columns.begin(), columns.end());
for (const auto &col : columns) {
auto avgPageSize = (col.fNPages == 0) ? 0 : (col.fBytesOnStorage / col.fNPages);
auto avgElementsPerPage = (col.fNPages == 0) ? 0 : (col.fNElements / col.fNPages);
std::string nameAndType = std::string(" ") + col.fFieldName + " [#" + std::to_string(col.fLocalOrder) + "]"
+ " -- " + Detail::RColumnElementBase::GetTypeName(col.fType);
std::string id = std::string("{id:") + std::to_string(col.fColumnId) + "}";
output << nameAndType << std::setw(60 - nameAndType.length()) << id << std::endl;
if(col.fFieldDescription != "")
output << " Description: " << col.fFieldDescription << std::endl;
output << " # Elements: " << col.fNElements << std::endl;
output << " # Pages: " << col.fNPages << std::endl;
output << " Avg elements / page: " << avgElementsPerPage << std::endl;
output << " Avg page size: " << avgPageSize << " B" << std::endl;
output << " Size on storage: " << col.fBytesOnStorage << " B" << std::endl;
output << " Compression: " << std::fixed << std::setprecision(2)
<< float(col.fElementSize * col.fNElements) / float(col.fBytesOnStorage) << std::endl;
output << "............................................................" << std::endl;
}
}
<commit_msg>checking if description is empty in better way<commit_after>/// \file RNTupleDescriptorFmt.cxx
/// \ingroup NTuple ROOT7
/// \author Jakob Blomer <jblomer@cern.ch>
/// \date 2019-08-25
/// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback
/// is welcome!
/*************************************************************************
* Copyright (C) 1995-2019, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#include <ROOT/RColumnElement.hxx>
#include <ROOT/RColumnModel.hxx>
#include <ROOT/RNTupleDescriptor.hxx>
#include <ROOT/RNTupleUtil.hxx>
#include <algorithm>
#include <iomanip>
#include <ostream>
#include <unordered_map>
#include <vector>
namespace {
struct ClusterInfo {
std::uint64_t fFirstEntry = 0;
std::uint32_t fNPages = 0;
std::uint32_t fNEntries = 0;
std::uint32_t fBytesOnStorage = 0;
std::uint32_t fBytesInMemory = 0;
bool operator ==(const ClusterInfo &other) const {
return fFirstEntry == other.fFirstEntry;
}
bool operator <(const ClusterInfo &other) const {
return fFirstEntry < other.fFirstEntry;
}
};
struct ColumnInfo {
ROOT::Experimental::DescriptorId_t fColumnId = 0;
ROOT::Experimental::DescriptorId_t fFieldId = 0;
std::uint64_t fLocalOrder = 0;
std::uint64_t fNElements = 0;
std::uint64_t fNPages = 0;
std::uint64_t fBytesOnStorage = 0;
std::uint32_t fElementSize = 0;
ROOT::Experimental::EColumnType fType;
std::string fFieldName;
std::string fFieldDescription;
bool operator <(const ColumnInfo &other) const {
if (fFieldName == other.fFieldName)
return fLocalOrder < other.fLocalOrder;
return fFieldName < other.fFieldName;
}
};
static std::string GetFieldName(ROOT::Experimental::DescriptorId_t fieldId,
const ROOT::Experimental::RNTupleDescriptor &ntupleDesc)
{
const auto &fieldDesc = ntupleDesc.GetFieldDescriptor(fieldId);
if (fieldDesc.GetParentId() == ROOT::Experimental::kInvalidDescriptorId)
return fieldDesc.GetFieldName();
return GetFieldName(fieldDesc.GetParentId(), ntupleDesc) + "." + fieldDesc.GetFieldName();
}
static std::string GetFieldDescription(ROOT::Experimental::DescriptorId_t fFieldId,
const ROOT::Experimental::RNTupleDescriptor &ntupleDesc)
{
const auto &fieldDesc = ntupleDesc.GetFieldDescriptor(fFieldId);
return fieldDesc.GetFieldDescription();
}
} // anonymous namespace
void ROOT::Experimental::RNTupleDescriptor::PrintInfo(std::ostream &output) const
{
std::vector<ColumnInfo> columns;
std::vector<ClusterInfo> clusters;
std::unordered_map<DescriptorId_t, unsigned int> cluster2Idx;
for (const auto &cluster : fClusterDescriptors) {
ClusterInfo info;
info.fFirstEntry = cluster.second.GetFirstEntryIndex();
info.fNEntries = cluster.second.GetNEntries();
cluster2Idx[cluster.first] = clusters.size();
clusters.emplace_back(info);
}
std::uint64_t bytesOnStorage = 0;
std::uint64_t bytesInMemory = 0;
std::uint64_t nPages = 0;
int compression = -1;
for (const auto &column : fColumnDescriptors) {
// We generate the default memory representation for the given column type in order
// to report the size _in memory_ of column elements
auto elementSize = Detail::RColumnElementBase::Generate(column.second.GetModel().GetType())->GetSize();
ColumnInfo info;
info.fColumnId = column.second.GetId();
info.fFieldId = column.second.GetFieldId();
info.fLocalOrder = column.second.GetIndex();
info.fElementSize = elementSize;
info.fType = column.second.GetModel().GetType();
for (const auto &cluster : fClusterDescriptors) {
auto columnRange = cluster.second.GetColumnRange(column.first);
info.fNElements += columnRange.fNElements;
if (compression == -1) {
compression = columnRange.fCompressionSettings;
}
const auto &pageRange = cluster.second.GetPageRange(column.first);
auto idx = cluster2Idx[cluster.first];
for (const auto &page : pageRange.fPageInfos) {
bytesOnStorage += page.fLocator.fBytesOnStorage;
bytesInMemory += page.fNElements * elementSize;
clusters[idx].fBytesOnStorage += page.fLocator.fBytesOnStorage;
clusters[idx].fBytesInMemory += page.fNElements * elementSize;
++clusters[idx].fNPages;
info.fBytesOnStorage += page.fLocator.fBytesOnStorage;
++info.fNPages;
++nPages;
}
}
columns.emplace_back(info);
}
auto headerSize = GetHeaderSize();
auto footerSize = GetFooterSize();
output << "============================================================" << std::endl;
output << "NTUPLE: " << GetName() << std::endl;
output << "Compression: " << compression << std::endl;
output << "------------------------------------------------------------" << std::endl;
output << " # Entries: " << GetNEntries() << std::endl;
output << " # Fields: " << GetNFields() << std::endl;
output << " # Columns: " << GetNColumns() << std::endl;
output << " # Pages: " << nPages << std::endl;
output << " # Clusters: " << GetNClusters() << std::endl;
output << " Size on storage: " << bytesOnStorage << " B" << std::endl;
output << " Compression rate: " << std::fixed << std::setprecision(2)
<< float(bytesInMemory) / float(bytesOnStorage) << std::endl;
output << " Header size: " << headerSize << " B" << std::endl;
output << " Footer size: " << footerSize << " B" << std::endl;
output << " Meta-data / data: " << std::fixed << std::setprecision(3)
<< float(headerSize + footerSize) / float(bytesOnStorage) << std::endl;
output << "------------------------------------------------------------" << std::endl;
output << "CLUSTER DETAILS" << std::endl;
output << "------------------------------------------------------------" << std::endl;
std::sort(clusters.begin(), clusters.end());
for (unsigned int i = 0; i < clusters.size(); ++i) {
output << " # " << std::setw(5) << i
<< " Entry range: [" << clusters[i].fFirstEntry << ".."
<< clusters[i].fFirstEntry + clusters[i].fNEntries - 1 << "] -- " << clusters[i].fNEntries << std::endl;
output << " "
<< " # Pages: " << clusters[i].fNPages << std::endl;
output << " "
<< " Size on storage: " << clusters[i].fBytesOnStorage << " B" << std::endl;
output << " "
<< " Compression: " << std::fixed << std::setprecision(2)
<< float(clusters[i].fBytesInMemory) / float(float(clusters[i].fBytesOnStorage)) << std::endl;
}
output << "------------------------------------------------------------" << std::endl;
output << "COLUMN DETAILS" << std::endl;
output << "------------------------------------------------------------" << std::endl;
for (auto &col : columns) {
col.fFieldName = GetFieldName(col.fFieldId, *this).substr(1);
col.fFieldDescription = GetFieldDescription(col.fFieldId, *this);
}
std::sort(columns.begin(), columns.end());
for (const auto &col : columns) {
auto avgPageSize = (col.fNPages == 0) ? 0 : (col.fBytesOnStorage / col.fNPages);
auto avgElementsPerPage = (col.fNPages == 0) ? 0 : (col.fNElements / col.fNPages);
std::string nameAndType = std::string(" ") + col.fFieldName + " [#" + std::to_string(col.fLocalOrder) + "]"
+ " -- " + Detail::RColumnElementBase::GetTypeName(col.fType);
std::string id = std::string("{id:") + std::to_string(col.fColumnId) + "}";
output << nameAndType << std::setw(60 - nameAndType.length()) << id << std::endl;
if (!col.fFieldDescription.empty())
output << " Description: " << col.fFieldDescription << std::endl;
output << " # Elements: " << col.fNElements << std::endl;
output << " # Pages: " << col.fNPages << std::endl;
output << " Avg elements / page: " << avgElementsPerPage << std::endl;
output << " Avg page size: " << avgPageSize << " B" << std::endl;
output << " Size on storage: " << col.fBytesOnStorage << " B" << std::endl;
output << " Compression: " << std::fixed << std::setprecision(2)
<< float(col.fElementSize * col.fNElements) / float(col.fBytesOnStorage) << std::endl;
output << "............................................................" << std::endl;
}
}
<|endoftext|> |
<commit_before>/* bzflag
* Copyright (c) 1993 - 2004 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include <math.h>
#include "common.h"
#include "global.h"
#include "PyramidBuilding.h"
#include "Intersect.h"
#include "TriWallSceneNode.h"
#include "QuadWallSceneNode.h"
#include "BZDBCache.h"
#include "PyramidSceneNodeGenerator.h"
std::string PyramidBuilding::typeName("PyramidBuilding");
PyramidBuilding::PyramidBuilding(const float* p, float a,
float w, float b, float h, bool drive, bool shoot) :
Obstacle(p, a, w, b, h,drive,shoot)
{
// do nothing
}
PyramidBuilding::~PyramidBuilding()
{
// do nothing
}
std::string PyramidBuilding::getType() const
{
return typeName;
}
std::string PyramidBuilding::getClassName() // const
{
return typeName;
}
float PyramidBuilding::intersect(const Ray& r) const
{
return timeRayHitsPyramids(r, getPosition(), getRotation(),
getWidth(), getBreadth(), getHeight(),
getZFlip());
}
void PyramidBuilding::getNormal(const float* p,
float* n) const
{
// get normal in z = const plane
const float s = shrinkFactor(p[2]);
getNormalRect(p, getPosition(), getRotation(),
s * getWidth(), s * getBreadth(), n);
// make sure we are not way above or way below it
// above is good so we can drive on it when it's fliped
float top = getPosition()[2]+getHeight();
float bottom = getPosition()[2];
if (s ==0){
if (this->getZFlip()){
if (p[2] >= top){
n[0] = n[1] = 0;
n[2] = 1;
return;
}
}else{
if (p[2] <= bottom){
n[0] = n[1] = 0;
n[2] = -1;
return;
}
}
}
// now angle it due to slope of wall
// FIXME -- this assumes the pyramid has a square base!
const float h = 1.0f / hypotf(getHeight(), getWidth());
n[0] *= h * getHeight();
n[1] *= h * getHeight();
n[2] = h * getWidth();
if (this->getZFlip())
n[2] *= -1;
}
void PyramidBuilding::get3DNormal(const float* p,
float* n) const
{
const float epsilon = ZERO_TOLERANCE;
// get normal in z = const plane
const float s = shrinkFactor(p[2]);
getNormalRect(p, getPosition(), getRotation(),
s * getWidth(), s * getBreadth(), n);
// make sure we are not way above or way below it
// above is good so we can drive on it when it's fliped
float top = getPosition()[2]+getHeight();
float bottom = getPosition()[2];
if (s == 0) {
if (getZFlip()) {
if (p[2] >= top) {
n[0] = n[1] = 0;
n[2] = 1;
return;
}
} else {
if (p[2] <= bottom) {
n[0] = n[1] = 0;
n[2] = -1;
return;
}
}
}
if (s >= 1.0f - epsilon) {
n[0] = n[1] = 0;
if (getZFlip()) {
n[2] = 1;
} else {
n[2] = -1;
}
return;
}
// now angle it due to slope of wall
// FIXME -- this assumes the pyramid has a square base!
const float h = 1.0f / hypotf(getHeight(), getWidth());
n[0] *= h * getHeight();
n[1] *= h * getHeight();
n[2] = h * getWidth();
if (this->getZFlip())
n[2] *= -1;
}
bool PyramidBuilding::isInside(const float* p,
float radius) const
{
// really rough -- doesn't decrease size with height
return (p[2] <= getHeight())
&& ((p[2]+BZDBCache::tankHeight) >= getPosition()[2])
&& testRectCircle(getPosition(), getRotation(), getWidth(), getBreadth(), p, radius);
}
bool PyramidBuilding::isInside(const float* p, float a,
float dx, float dy) const
{
// Tank is below pyramid ?
if (p[2] + BZDBCache::tankHeight < getPosition()[2])
return false;
// Tank is above pyramid ?
if (p[2] >= getPosition()[2] + getHeight())
return false;
// Could be inside. Then check collision with the rectangle at object height
// This is a rectangle reduced by shrinking but pass the height that we are
// not so sure where collision can be
const float s = shrinkFactor(p[2], BZDBCache::tankHeight);
return testRectRect(getPosition(), getRotation(),
s * getWidth(), s * getBreadth(), p, a, dx, dy);
}
bool PyramidBuilding::isCrossing(const float* p, float a,
float dx, float dy, float* plane) const
{
// if not inside or contained then not crossing
if (!isInside(p, a, dx, dy) ||
testRectInRect(getPosition(), getRotation(),
getWidth(), getBreadth(), p, a, dx, dy))
return false;
if (!plane) return true;
// it's crossing -- choose which wall is being crossed (this
// is a guestimate, should really do a careful test). just
// see which wall the point is closest to.
const float* p2 = getPosition();
const float a2 = getRotation();
const float c = cosf(-a2), s = sinf(-a2);
const float x = c * (p[0] - p2[0]) - s * (p[1] - p2[1]);
const float y = c * (p[1] - p2[1]) + s * (p[0] - p2[0]);
float pw[2];
if (fabsf(fabsf(x) - getWidth()) < fabsf(fabsf(y) - getBreadth())) {
plane[0] = ((x < 0.0) ? -cosf(a2) : cosf(a2));
plane[1] = ((x < 0.0) ? -sinf(a2) : sinf(a2));
pw[0] = p2[0] + getWidth() * plane[0];
pw[1] = p2[1] + getWidth() * plane[1];
}
else {
plane[0] = ((y < 0.0) ? sinf(a2) : -sinf(a2));
plane[1] = ((y < 0.0) ? -cosf(a2) : cosf(a2));
pw[0] = p2[0] + getBreadth() * plane[0];
pw[1] = p2[1] + getBreadth() * plane[1];
}
// now finish off plane equation (FIXME -- assumes a square base)
const float h = 1.0f / hypotf(getHeight(), getWidth());
plane[0] *= h * getHeight();
plane[1] *= h * getHeight();
plane[2] = h * getWidth();
plane[3] = -(plane[0] * pw[0] + plane[1] * pw[1]);
return true;
}
bool PyramidBuilding::getHitNormal(
const float* pos1, float,
const float* pos2, float,
float, float, float height,
float* normal) const
{
// pyramids height and flipping
// normalize height sign and report that in flip
float oHeight = getHeight();
bool flip = getZFlip();
if (oHeight < 0) {
flip = !flip;
oHeight = -oHeight;
}
// get Bottom and Top of building
float oBottom = getPosition()[2];
float oTop = oBottom + oHeight;
// get higher and lower point of base of colliding object
float objHigh = pos1[2];
float objLow = pos2[2];
if (objHigh < objLow) {
float temp = objHigh;
objHigh = objLow;
objLow = temp;
}
normal[0] = normal[1] = 0;
if (flip && objHigh > oTop) {
// base of higher object is over the plateau
normal[2] = 1;
return true;
} else if (!flip && objLow + height < oBottom) {
// top of lower object is below the base
normal[2] = -1;
return true;
}
// get normal in z = const plane
const float s = shrinkFactor(pos1[2], height);
getNormalRect(pos1, getPosition(), getRotation(),
s * getWidth(), s * getBreadth(), normal);
// now angle it due to slope of wall
// FIXME -- this assumes the pyramid has a square base!
const float h = 1.0f / hypotf(oHeight, getWidth());
normal[0] *= h * oHeight;
normal[1] *= h * oHeight;
normal[2] = h * getWidth();
if (flip)
normal[2] = -normal[2];
return true;
}
ObstacleSceneNodeGenerator* PyramidBuilding::newSceneNodeGenerator() const
{
return new PyramidSceneNodeGenerator(this);
}
void PyramidBuilding::getCorner(int index,
float* pos) const
{
const float* base = getPosition();
const float c = cosf(getRotation());
const float s = sinf(getRotation());
const float w = getWidth();
const float h = getBreadth();
const float top = getHeight() + base[2];
switch (index) {
case 0:
pos[0] = base[0] + c * w - s * h;
pos[1] = base[1] + s * w + c * h;
if (getZFlip())
pos[2] = top;
else
pos[2] = base[2];
break;
case 1:
pos[0] = base[0] - c * w - s * h;
pos[1] = base[1] - s * w + c * h;
if (getZFlip())
pos[2] = top;
else
pos[2] = base[2];
break;
case 2:
pos[0] = base[0] - c * w + s * h;
pos[1] = base[1] - s * w - c * h;
if (getZFlip())
pos[2] = top;
else
pos[2] = base[2];
break;
case 3:
pos[0] = base[0] + c * w + s * h;
pos[1] = base[1] + s * w - c * h;
if (getZFlip())
pos[2] = top;
else
pos[2] = base[2];
break;
case 4:
pos[0] = base[0];
pos[1] = base[1];
if (getZFlip())
pos[2] = base[2];
else
pos[2] = top;
break;
}
}
float PyramidBuilding::shrinkFactor(float z,
float height) const
{
float shrink;
// Normalize Height and flip to have height > 0
float oHeight = getHeight();
bool flip = getZFlip();
if (oHeight < 0) {
flip = !flip;
oHeight = - oHeight;
}
// Remove heights bias
const float *pos = getPosition();
z -= pos[2];
if (oHeight <= ZERO_TOLERANCE) {
shrink = 1.0f;
} else {
// Normalize heights
z /= oHeight;
// if flipped the bigger intersection is at top of obiect
if (flip) {
// Normalize the object height, we have not done yet
z += height / oHeight;
}
// shrink is that
if (flip) {
shrink = z;
} else {
shrink = 1.0f - z;
}
}
// clamp in 0 .. 1
if (shrink < 0.0)
shrink = 0.0;
else if (shrink > 1.0)
shrink = 1.0;
return shrink;
}
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>un-stick inverted pyramids, and a little indenting<commit_after>/* bzflag
* Copyright (c) 1993 - 2004 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include <math.h>
#include "common.h"
#include "global.h"
#include "PyramidBuilding.h"
#include "Intersect.h"
#include "TriWallSceneNode.h"
#include "QuadWallSceneNode.h"
#include "BZDBCache.h"
#include "PyramidSceneNodeGenerator.h"
std::string PyramidBuilding::typeName("PyramidBuilding");
PyramidBuilding::PyramidBuilding(const float* p, float a,
float w, float b, float h, bool drive, bool shoot) :
Obstacle(p, a, w, b, h,drive,shoot)
{
// do nothing
}
PyramidBuilding::~PyramidBuilding()
{
// do nothing
}
std::string PyramidBuilding::getType() const
{
return typeName;
}
std::string PyramidBuilding::getClassName() // const
{
return typeName;
}
float PyramidBuilding::intersect(const Ray& r) const
{
return timeRayHitsPyramids(r, getPosition(), getRotation(),
getWidth(), getBreadth(), getHeight(),
getZFlip());
}
void PyramidBuilding::getNormal(const float* p,
float* n) const
{
// get normal in z = const plane
const float s = shrinkFactor(p[2]);
getNormalRect(p, getPosition(), getRotation(),
s * getWidth(), s * getBreadth(), n);
// make sure we are not way above or way below it
// above is good so we can drive on it when it's fliped
float top = getPosition()[2]+getHeight();
float bottom = getPosition()[2];
if (s ==0){
if (this->getZFlip()){
if (p[2] >= top){
n[0] = n[1] = 0;
n[2] = 1;
return;
}
}else{
if (p[2] <= bottom){
n[0] = n[1] = 0;
n[2] = -1;
return;
}
}
}
// now angle it due to slope of wall
// FIXME -- this assumes the pyramid has a square base!
const float h = 1.0f / hypotf(getHeight(), getWidth());
n[0] *= h * getHeight();
n[1] *= h * getHeight();
n[2] = h * getWidth();
if (this->getZFlip())
n[2] *= -1;
}
void PyramidBuilding::get3DNormal(const float* p,
float* n) const
{
const float epsilon = ZERO_TOLERANCE;
// get normal in z = const plane
const float s = shrinkFactor(p[2]);
getNormalRect(p, getPosition(), getRotation(),
s * getWidth(), s * getBreadth(), n);
// make sure we are not way above or way below it
// above is good so we can drive on it when it's fliped
float top = getPosition()[2]+getHeight();
float bottom = getPosition()[2];
if (s == 0) {
if (getZFlip()) {
if (p[2] >= top) {
n[0] = n[1] = 0;
n[2] = 1;
return;
}
} else {
if (p[2] <= bottom) {
n[0] = n[1] = 0;
n[2] = -1;
return;
}
}
}
if (s >= 1.0f - epsilon) {
n[0] = n[1] = 0;
if (getZFlip()) {
n[2] = 1;
} else {
n[2] = -1;
}
return;
}
// now angle it due to slope of wall
// FIXME -- this assumes the pyramid has a square base!
const float h = 1.0f / hypotf(getHeight(), getWidth());
n[0] *= h * getHeight();
n[1] *= h * getHeight();
n[2] = h * getWidth();
if (this->getZFlip())
n[2] *= -1;
}
bool PyramidBuilding::isInside(const float* p,
float radius) const
{
// really rough -- doesn't decrease size with height
return (p[2] <= getHeight())
&& ((p[2]+BZDBCache::tankHeight) >= getPosition()[2])
&& testRectCircle(getPosition(), getRotation(), getWidth(), getBreadth(), p, radius);
}
bool PyramidBuilding::isInside(const float* p, float a,
float dx, float dy) const
{
// Tank is below pyramid ?
if (p[2] + BZDBCache::tankHeight < getPosition()[2])
return false;
// Tank is above pyramid ?
if (p[2] > getPosition()[2] + getHeight())
return false;
// Could be inside. Then check collision with the rectangle at object height
// This is a rectangle reduced by shrinking but pass the height that we are
// not so sure where collision can be
const float s = shrinkFactor(p[2], BZDBCache::tankHeight);
return testRectRect(getPosition(), getRotation(),
s * getWidth(), s * getBreadth(), p, a, dx, dy);
}
bool PyramidBuilding::isCrossing(const float* p, float a,
float dx, float dy, float* plane) const
{
// if not inside or contained then not crossing
if (!isInside(p, a, dx, dy) ||
testRectInRect(getPosition(), getRotation(),
getWidth(), getBreadth(), p, a, dx, dy))
return false;
if (!plane) return true;
// it's crossing -- choose which wall is being crossed (this
// is a guestimate, should really do a careful test). just
// see which wall the point is closest to.
const float* p2 = getPosition();
const float a2 = getRotation();
const float c = cosf(-a2), s = sinf(-a2);
const float x = c * (p[0] - p2[0]) - s * (p[1] - p2[1]);
const float y = c * (p[1] - p2[1]) + s * (p[0] - p2[0]);
float pw[2];
if (fabsf(fabsf(x) - getWidth()) < fabsf(fabsf(y) - getBreadth())) {
plane[0] = ((x < 0.0) ? -cosf(a2) : cosf(a2));
plane[1] = ((x < 0.0) ? -sinf(a2) : sinf(a2));
pw[0] = p2[0] + getWidth() * plane[0];
pw[1] = p2[1] + getWidth() * plane[1];
}
else {
plane[0] = ((y < 0.0) ? sinf(a2) : -sinf(a2));
plane[1] = ((y < 0.0) ? -cosf(a2) : cosf(a2));
pw[0] = p2[0] + getBreadth() * plane[0];
pw[1] = p2[1] + getBreadth() * plane[1];
}
// now finish off plane equation (FIXME -- assumes a square base)
const float h = 1.0f / hypotf(getHeight(), getWidth());
plane[0] *= h * getHeight();
plane[1] *= h * getHeight();
plane[2] = h * getWidth();
plane[3] = -(plane[0] * pw[0] + plane[1] * pw[1]);
return true;
}
bool PyramidBuilding::getHitNormal(
const float* pos1, float,
const float* pos2, float,
float, float, float height,
float* normal) const
{
// pyramids height and flipping
// normalize height sign and report that in flip
float oHeight = getHeight();
bool flip = getZFlip();
if (oHeight < 0) {
flip = !flip;
oHeight = -oHeight;
}
// get Bottom and Top of building
float oBottom = getPosition()[2];
float oTop = oBottom + oHeight;
// get higher and lower point of base of colliding object
float objHigh = pos1[2];
float objLow = pos2[2];
if (objHigh < objLow) {
float temp = objHigh;
objHigh = objLow;
objLow = temp;
}
normal[0] = normal[1] = 0;
if (flip && objHigh > oTop) {
// base of higher object is over the plateau
normal[2] = 1;
return true;
} else if (!flip && objLow + height < oBottom) {
// top of lower object is below the base
normal[2] = -1;
return true;
}
// get normal in z = const plane
const float s = shrinkFactor(pos1[2], height);
getNormalRect(pos1, getPosition(), getRotation(),
s * getWidth(), s * getBreadth(), normal);
// now angle it due to slope of wall
// FIXME -- this assumes the pyramid has a square base!
const float h = 1.0f / hypotf(oHeight, getWidth());
normal[0] *= h * oHeight;
normal[1] *= h * oHeight;
normal[2] = h * getWidth();
if (flip)
normal[2] = -normal[2];
return true;
}
ObstacleSceneNodeGenerator* PyramidBuilding::newSceneNodeGenerator() const
{
return new PyramidSceneNodeGenerator(this);
}
void PyramidBuilding::getCorner(int index,
float* pos) const
{
const float* base = getPosition();
const float c = cosf(getRotation());
const float s = sinf(getRotation());
const float w = getWidth();
const float h = getBreadth();
const float top = getHeight() + base[2];
switch (index) {
case 0:
pos[0] = base[0] + c * w - s * h;
pos[1] = base[1] + s * w + c * h;
if (getZFlip())
pos[2] = top;
else
pos[2] = base[2];
break;
case 1:
pos[0] = base[0] - c * w - s * h;
pos[1] = base[1] - s * w + c * h;
if (getZFlip())
pos[2] = top;
else
pos[2] = base[2];
break;
case 2:
pos[0] = base[0] - c * w + s * h;
pos[1] = base[1] - s * w - c * h;
if (getZFlip())
pos[2] = top;
else
pos[2] = base[2];
break;
case 3:
pos[0] = base[0] + c * w + s * h;
pos[1] = base[1] + s * w - c * h;
if (getZFlip())
pos[2] = top;
else
pos[2] = base[2];
break;
case 4:
pos[0] = base[0];
pos[1] = base[1];
if (getZFlip())
pos[2] = base[2];
else
pos[2] = top;
break;
}
}
float PyramidBuilding::shrinkFactor(float z,
float height) const
{
float shrink;
// Normalize Height and flip to have height > 0
float oHeight = getHeight();
bool flip = getZFlip();
if (oHeight < 0) {
flip = !flip;
oHeight = - oHeight;
}
// Remove heights bias
const float *pos = getPosition();
z -= pos[2];
if (oHeight <= ZERO_TOLERANCE) {
shrink = 1.0f;
} else {
// Normalize heights
z /= oHeight;
// if flipped the bigger intersection is at top of the object
if (flip) {
// Normalize the object height, we have not done yet
z += height / oHeight;
}
// shrink is that
if (flip) {
shrink = z;
} else {
shrink = 1.0f - z;
}
}
// clamp in 0 .. 1
if (shrink < 0.0)
shrink = 0.0;
else if (shrink > 1.0)
shrink = 1.0;
return shrink;
}
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|> |
<commit_before>/*
Copyright (C) 2006 by Andrew Robberts
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "cssysdef.h"
#include "iutil/objreg.h"
#include "iutil/plugin.h"
#include "iutil/object.h"
#include "iengine/mesh.h"
#include "iengine/engine.h"
#include "iengine/movable.h"
#include "imesh/genmesh.h"
#include "iengine/material.h"
#include "imesh/object.h"
#include "ivideo/material.h"
#include "iutil/eventq.h"
#include "csgeom/tri.h"
#include "csgfx/renderbuffer.h"
#include "csgfx/shadervarcontext.h"
#include "csutil/event.h"
#include "csutil/eventhandlers.h"
#include "cstool/collider.h"
#include "decalmanager.h"
#include "decal.h"
#include "decaltemplate.h"
csDecal::csDecal(iObjectRegistry * objectReg, csDecalManager * decalManager)
: objectReg(objectReg), decalManager(decalManager),
indexCount(0), vertexCount(0), width(0), height(0), currMesh(0)
{
engine = csQueryRegistry<iEngine>(objectReg);
vertexBuffer = csRenderBuffer::CreateRenderBuffer(
CS_DECAL_MAX_VERTS_PER_DECAL, CS_BUF_STATIC, CS_BUFCOMP_FLOAT, 3);
texCoordBuffer = csRenderBuffer::CreateRenderBuffer(
CS_DECAL_MAX_VERTS_PER_DECAL, CS_BUF_STATIC, CS_BUFCOMP_FLOAT, 2);
normalBuffer = csRenderBuffer::CreateRenderBuffer(
CS_DECAL_MAX_VERTS_PER_DECAL, CS_BUF_STATIC, CS_BUFCOMP_FLOAT, 3);
colorBuffer = csRenderBuffer::CreateRenderBuffer(
CS_DECAL_MAX_VERTS_PER_DECAL, CS_BUF_STATIC, CS_BUFCOMP_FLOAT, 4);
indexBuffer = csRenderBuffer::CreateIndexRenderBuffer(
CS_DECAL_MAX_TRIS_PER_DECAL*3, CS_BUF_STATIC,
CS_BUFCOMP_UNSIGNED_INT, 0, CS_DECAL_MAX_TRIS_PER_DECAL*3-1);
bufferHolder.AttachNew(new csRenderBufferHolder);
bufferHolder->SetRenderBuffer(CS_BUFFER_INDEX, indexBuffer);
bufferHolder->SetRenderBuffer(CS_BUFFER_POSITION, vertexBuffer);
bufferHolder->SetRenderBuffer(CS_BUFFER_TEXCOORD0, texCoordBuffer);
bufferHolder->SetRenderBuffer(CS_BUFFER_NORMAL, normalBuffer);
bufferHolder->SetRenderBuffer(CS_BUFFER_COLOR, colorBuffer);
}
csDecal::~csDecal()
{
ClearRenderMeshes();
}
void csDecal::Initialize(iDecalTemplate * decalTemplate,
const csVector3 & normal, const csVector3 & pos, const csVector3 & up,
const csVector3 & right, float width, float height)
{
this->indexCount = 0;
this->vertexCount = 0;
this->currMesh = 0;
this->decalTemplate = decalTemplate;
this->normal = normal;
this->pos = pos;
this->width = width;
this->height = height;
radius = sqrt(width*width + height*height);
invWidth = 1.0f / width;
invHeight = 1.0f / height;
this->up = up;
this->right = right;
life = 0;
topPlaneDist = 0.0f;
bottomPlaneDist = 0.0f;
ClearRenderMeshes();
}
void csDecal::BeginMesh(iMeshWrapper * mesh)
{
// check if InitializePosition has been called with decent parameters
if (width <= 0.01f || height <= 0.01f)
return;
// check if we hit our maximum allowed triangles
if (indexCount >= CS_DECAL_MAX_TRIS_PER_DECAL * 3)
return;
currMesh = 0;
firstIndex = indexCount;
const csReversibleTransform& trans =
mesh->GetMovable()->GetFullTransform();
localNormal = trans.Other2ThisRelative(normal);
localUp = trans.Other2ThisRelative(up);
localRight = trans.Other2ThisRelative(right);
vertOffset = localNormal * decalTemplate->GetDecalOffset();
relPos = trans.Other2This(pos);
#ifdef CS_DECAL_CLIP_DECAL
// up
clipPlanes[0] = csPlane3(-localUp, -height*0.5f + localUp * relPos);
// down
clipPlanes[1] = csPlane3( localUp, -height*0.5f - localUp * relPos);
// left
clipPlanes[2] = csPlane3(-localRight, -width*0.5f + localRight * relPos);
// right
clipPlanes[3] = csPlane3( localRight, -width*0.5f - localRight * relPos);
numClipPlanes = 4;
// top
if (decalTemplate->HasTopClipping())
{
topPlaneDist = decalTemplate->GetTopClippingScale() * radius;
clipPlanes[numClipPlanes++] = csPlane3(-localNormal,
-topPlaneDist + localNormal * relPos);
}
// bottom
if (decalTemplate->HasBottomClipping())
{
bottomPlaneDist = decalTemplate->GetBottomClippingScale() * radius;
clipPlanes[numClipPlanes++] = csPlane3( localNormal,
-bottomPlaneDist - localNormal * relPos);
}
#endif // CS_DECAL_CLIP_DECAL
// we didn't encounter any errors, so validate the current mesh
currMesh = mesh;
}
void csDecal::AddStaticPoly(const csPoly3D & p)
{
if (!currMesh)
return;
size_t a;
CS::TriangleT<int> tri;
csPoly3D poly = p;
#ifdef CS_DECAL_CLIP_DECAL
for (a=0; a<numClipPlanes; ++a)
poly.CutToPlane(clipPlanes[a]);
#endif // CS_DECAL_CLIP_DECAL
size_t vertCount = poly.GetVertexCount();
// only support triangles and up
if (vertCount < 3)
return;
// ensure the polygon isn't facing away from the decal's normal too much
csVector3 polyNorm = poly.ComputeNormal();
float polyNormThresholdValue = -polyNorm * localNormal;
if (polyNormThresholdValue < decalTemplate->GetPolygonNormalThreshold())
return;
// check if we hit our maximum allowed vertices
if (vertexCount + vertCount > CS_DECAL_MAX_VERTS_PER_DECAL)
vertCount = CS_DECAL_MAX_VERTS_PER_DECAL - vertexCount;
if (vertCount < 3)
return;
// check if we hit our maximum allowed indecies
size_t idxCount = (vertCount - 2) * 3;
if (indexCount + idxCount > CS_DECAL_MAX_TRIS_PER_DECAL*3)
return;
// if this face is too perpendicular, then we'll need to push it out a bit
// to avoid z-fighting. We do this by pushing the bottom of the face out
// more than the top of the face
#ifdef CS_DECAL_CLIP_DECAL
bool doFaceOffset = false;
float faceHighDot = 0.0f;
float invHighLowFaceDist = 0.0f;
csVector3 faceBottomOffset;
csVector3 faceCenter;
if (fabs(polyNormThresholdValue)
< decalTemplate->GetPerpendicularFaceThreshold())
{
doFaceOffset = true;
csVector3 faceHighVert, faceLowVert;
float faceLowDot;
faceLowVert = faceHighVert = *poly.GetVertex(0);
faceLowDot = faceHighDot = (faceLowVert - relPos) * localNormal;
faceCenter = faceLowVert;
for (a=1; a<vertCount; ++a)
{
const csVector3 * vertPos = poly.GetVertex(a);
faceCenter += *vertPos;
float dot = (*vertPos - relPos) * localNormal;
if (dot > faceHighDot)
{
faceHighVert = *vertPos;
faceHighDot = dot;
}
if (dot < faceLowDot)
{
faceLowVert = *vertPos;
faceLowDot = dot;
}
}
invHighLowFaceDist = 1.0f / (faceHighDot - faceLowDot);
faceBottomOffset = -decalTemplate->GetPerpendicularFaceOffset() * polyNorm;
faceCenter /= (float)vertCount;
}
#endif // CS_DECAL_CLIP_DECAL
const csVector2 & minTexCoord = decalTemplate->GetMinTexCoord();
csVector2 texCoordRange = decalTemplate->GetMaxTexCoord() - minTexCoord;
tri[0] = vertexCount;
for (a=0; a<vertCount; ++a)
{
#ifdef CS_DECAL_CLIP_DECAL
csVector3 vertPos = *poly.GetVertex(a);
float distToPos = (vertPos - relPos) * localNormal;
if (doFaceOffset)
{
// linear interpolation where high vert goes nowhere and low vert is
// full offset
float offsetVal = (faceHighDot - distToPos) * invHighLowFaceDist;
vertPos += offsetVal * faceBottomOffset;
// spread out the base to avoid vertical seams
vertPos += (vertPos - faceCenter).Unit()
* (decalTemplate->GetPerpendicularFaceOffset() * 2.0f);
}
vertPos += vertOffset;
#else
csVector3 vertPos = *poly.GetVertex(a);
#endif // CS_DECAL_CLIP_DECAL
csVector3 relVert = vertPos - relPos;
size_t vertIdx = vertexCount+a;
// copy over vertex data
vertexBuffer->CopyInto(&vertPos, 1, vertIdx);
// copy over color
csColor4 color;
if (-distToPos >= 0.0f)
{
float t = 0.0f;
if (topPlaneDist >= 0.01f)
t = -distToPos / topPlaneDist;
color = decalTemplate->GetMainColor() * (1.0f - t) + decalTemplate->GetTopColor() * t;
}
else
{
float t = 0.0f;
if (bottomPlaneDist >= 0.01f)
t = distToPos / bottomPlaneDist;
color = decalTemplate->GetMainColor() * (1.0f - t) + decalTemplate->GetBottomColor() * t;
}
colorBuffer->CopyInto(&color, 1, vertIdx);
// create the index buffer for each triangle in the poly
if (a >= 2)
{
tri[1] = vertIdx-1;
tri[2] = vertIdx;
indexBuffer->CopyInto(&tri, 3, indexCount);
indexCount += 3;
}
// generate uv coordinates
csVector2 texCoord(
minTexCoord.x + texCoordRange.x * 0.5f +
texCoordRange.x * localRight * invWidth * relVert,
minTexCoord.y + texCoordRange.y * 0.5f -
texCoordRange.y * localUp * invHeight * relVert);
texCoordBuffer->CopyInto(&texCoord, 1, vertIdx);
// copy over normal
normalBuffer->CopyInto(&localNormal, 1, vertIdx);
}
vertexCount += vertCount;
}
void csDecal::EndMesh()
{
if (!currMesh)
return;
// make sure we actually added some geometry before we create a rendermesh
if (indexCount == firstIndex)
return;
// create a rendermesh for this mesh
csRenderMesh* pRenderMesh = decalManager->renderMeshAllocator.Alloc();
csDecalRenderMeshInfo renderMeshInfo;
renderMeshInfo.pRenderMesh = pRenderMesh;
renderMeshInfo.mesh = currMesh;
renderMeshInfos.Push(renderMeshInfo);
pRenderMesh->mixmode = decalTemplate->GetMixMode();
pRenderMesh->meshtype = CS_MESHTYPE_TRIANGLES;
pRenderMesh->indexstart = firstIndex;
pRenderMesh->indexend = indexCount;
pRenderMesh->material = decalTemplate->GetMaterialWrapper();
pRenderMesh->buffers = bufferHolder;
pRenderMesh->geometryInstance = (void *)bufferHolder;
//variableContext.AttachNew(new csShaderVariableContext);
//pRenderMesh->variablecontext = variableContext;
currMesh->AddExtraRenderMesh(pRenderMesh,
decalTemplate->GetRenderPriority(), decalTemplate->GetZBufMode());
}
bool csDecal::Age (csTicks ticks)
{
const float lifespan = decalTemplate->GetTimeToLive ();
if (lifespan <= 0.0f)
return true;
life += (float)ticks * 0.001f;
return life < lifespan;
}
void csDecal::ClearRenderMeshes()
{
const size_t len = renderMeshInfos.GetSize();
for (size_t a=0; a<len; ++a)
{
renderMeshInfos[a].mesh->RemoveExtraRenderMesh(
renderMeshInfos[a].pRenderMesh);
decalManager->renderMeshAllocator.Free(renderMeshInfos[a].pRenderMesh);
}
renderMeshInfos.Empty();
}
<commit_msg>- Revert variable moves due to leaving in improper state.<commit_after>/*
Copyright (C) 2006 by Andrew Robberts
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "cssysdef.h"
#include "iutil/objreg.h"
#include "iutil/plugin.h"
#include "iutil/object.h"
#include "iengine/mesh.h"
#include "iengine/engine.h"
#include "iengine/movable.h"
#include "imesh/genmesh.h"
#include "iengine/material.h"
#include "imesh/object.h"
#include "ivideo/material.h"
#include "iutil/eventq.h"
#include "csgeom/tri.h"
#include "csgfx/renderbuffer.h"
#include "csgfx/shadervarcontext.h"
#include "csutil/event.h"
#include "csutil/eventhandlers.h"
#include "cstool/collider.h"
#include "decalmanager.h"
#include "decal.h"
#include "decaltemplate.h"
csDecal::csDecal(iObjectRegistry * objectReg, csDecalManager * decalManager)
: objectReg(objectReg), decalManager(decalManager),
indexCount(0), vertexCount(0), width(0), height(0), currMesh(0)
{
engine = csQueryRegistry<iEngine>(objectReg);
vertexBuffer = csRenderBuffer::CreateRenderBuffer(
CS_DECAL_MAX_VERTS_PER_DECAL, CS_BUF_STATIC, CS_BUFCOMP_FLOAT, 3);
texCoordBuffer = csRenderBuffer::CreateRenderBuffer(
CS_DECAL_MAX_VERTS_PER_DECAL, CS_BUF_STATIC, CS_BUFCOMP_FLOAT, 2);
normalBuffer = csRenderBuffer::CreateRenderBuffer(
CS_DECAL_MAX_VERTS_PER_DECAL, CS_BUF_STATIC, CS_BUFCOMP_FLOAT, 3);
colorBuffer = csRenderBuffer::CreateRenderBuffer(
CS_DECAL_MAX_VERTS_PER_DECAL, CS_BUF_STATIC, CS_BUFCOMP_FLOAT, 4);
indexBuffer = csRenderBuffer::CreateIndexRenderBuffer(
CS_DECAL_MAX_TRIS_PER_DECAL*3, CS_BUF_STATIC,
CS_BUFCOMP_UNSIGNED_INT, 0, CS_DECAL_MAX_TRIS_PER_DECAL*3-1);
bufferHolder.AttachNew(new csRenderBufferHolder);
bufferHolder->SetRenderBuffer(CS_BUFFER_INDEX, indexBuffer);
bufferHolder->SetRenderBuffer(CS_BUFFER_POSITION, vertexBuffer);
bufferHolder->SetRenderBuffer(CS_BUFFER_TEXCOORD0, texCoordBuffer);
bufferHolder->SetRenderBuffer(CS_BUFFER_NORMAL, normalBuffer);
bufferHolder->SetRenderBuffer(CS_BUFFER_COLOR, colorBuffer);
}
csDecal::~csDecal()
{
ClearRenderMeshes();
}
void csDecal::Initialize(iDecalTemplate * decalTemplate,
const csVector3 & normal, const csVector3 & pos, const csVector3 & up,
const csVector3 & right, float width, float height)
{
this->indexCount = 0;
this->vertexCount = 0;
this->currMesh = 0;
this->decalTemplate = decalTemplate;
this->normal = normal;
this->pos = pos;
this->width = width;
this->height = height;
radius = sqrt(width*width + height*height);
invWidth = 1.0f / width;
invHeight = 1.0f / height;
this->up = up;
this->right = right;
life = 0;
topPlaneDist = 0.0f;
bottomPlaneDist = 0.0f;
ClearRenderMeshes();
}
void csDecal::BeginMesh(iMeshWrapper * mesh)
{
currMesh = 0;
// check if InitializePosition has been called with decent parameters
if (width <= 0.01f || height <= 0.01f)
return;
// check if we hit our maximum allowed triangles
if (indexCount >= CS_DECAL_MAX_TRIS_PER_DECAL * 3)
return;
firstIndex = indexCount;
const csReversibleTransform& trans =
mesh->GetMovable()->GetFullTransform();
localNormal = trans.Other2ThisRelative(normal);
localUp = trans.Other2ThisRelative(up);
localRight = trans.Other2ThisRelative(right);
vertOffset = localNormal * decalTemplate->GetDecalOffset();
relPos = trans.Other2This(pos);
#ifdef CS_DECAL_CLIP_DECAL
// up
clipPlanes[0] = csPlane3(-localUp, -height*0.5f + localUp * relPos);
// down
clipPlanes[1] = csPlane3( localUp, -height*0.5f - localUp * relPos);
// left
clipPlanes[2] = csPlane3(-localRight, -width*0.5f + localRight * relPos);
// right
clipPlanes[3] = csPlane3( localRight, -width*0.5f - localRight * relPos);
numClipPlanes = 4;
// top
if (decalTemplate->HasTopClipping())
{
topPlaneDist = decalTemplate->GetTopClippingScale() * radius;
clipPlanes[numClipPlanes++] = csPlane3(-localNormal,
-topPlaneDist + localNormal * relPos);
}
// bottom
if (decalTemplate->HasBottomClipping())
{
bottomPlaneDist = decalTemplate->GetBottomClippingScale() * radius;
clipPlanes[numClipPlanes++] = csPlane3( localNormal,
-bottomPlaneDist - localNormal * relPos);
}
#endif // CS_DECAL_CLIP_DECAL
// we didn't encounter any errors, so validate the current mesh
currMesh = mesh;
}
void csDecal::AddStaticPoly(const csPoly3D & p)
{
if (!currMesh)
return;
size_t a;
CS::TriangleT<int> tri;
csPoly3D poly = p;
#ifdef CS_DECAL_CLIP_DECAL
for (a=0; a<numClipPlanes; ++a)
poly.CutToPlane(clipPlanes[a]);
#endif // CS_DECAL_CLIP_DECAL
size_t vertCount = poly.GetVertexCount();
// only support triangles and up
if (vertCount < 3)
return;
// ensure the polygon isn't facing away from the decal's normal too much
csVector3 polyNorm = poly.ComputeNormal();
float polyNormThresholdValue = -polyNorm * localNormal;
if (polyNormThresholdValue < decalTemplate->GetPolygonNormalThreshold())
return;
// check if we hit our maximum allowed vertices
if (vertexCount + vertCount > CS_DECAL_MAX_VERTS_PER_DECAL)
vertCount = CS_DECAL_MAX_VERTS_PER_DECAL - vertexCount;
if (vertCount < 3)
return;
// check if we hit our maximum allowed indecies
size_t idxCount = (vertCount - 2) * 3;
if (indexCount + idxCount > CS_DECAL_MAX_TRIS_PER_DECAL*3)
return;
// if this face is too perpendicular, then we'll need to push it out a bit
// to avoid z-fighting. We do this by pushing the bottom of the face out
// more than the top of the face
#ifdef CS_DECAL_CLIP_DECAL
bool doFaceOffset = false;
float faceHighDot = 0.0f;
float invHighLowFaceDist = 0.0f;
csVector3 faceBottomOffset;
csVector3 faceCenter;
if (fabs(polyNormThresholdValue)
< decalTemplate->GetPerpendicularFaceThreshold())
{
doFaceOffset = true;
csVector3 faceHighVert, faceLowVert;
float faceLowDot;
faceLowVert = faceHighVert = *poly.GetVertex(0);
faceLowDot = faceHighDot = (faceLowVert - relPos) * localNormal;
faceCenter = faceLowVert;
for (a=1; a<vertCount; ++a)
{
const csVector3 * vertPos = poly.GetVertex(a);
faceCenter += *vertPos;
float dot = (*vertPos - relPos) * localNormal;
if (dot > faceHighDot)
{
faceHighVert = *vertPos;
faceHighDot = dot;
}
if (dot < faceLowDot)
{
faceLowVert = *vertPos;
faceLowDot = dot;
}
}
invHighLowFaceDist = 1.0f / (faceHighDot - faceLowDot);
faceBottomOffset = -decalTemplate->GetPerpendicularFaceOffset() * polyNorm;
faceCenter /= (float)vertCount;
}
#endif // CS_DECAL_CLIP_DECAL
const csVector2 & minTexCoord = decalTemplate->GetMinTexCoord();
csVector2 texCoordRange = decalTemplate->GetMaxTexCoord() - minTexCoord;
tri[0] = vertexCount;
for (a=0; a<vertCount; ++a)
{
#ifdef CS_DECAL_CLIP_DECAL
csVector3 vertPos = *poly.GetVertex(a);
float distToPos = (vertPos - relPos) * localNormal;
if (doFaceOffset)
{
// linear interpolation where high vert goes nowhere and low vert is
// full offset
float offsetVal = (faceHighDot - distToPos) * invHighLowFaceDist;
vertPos += offsetVal * faceBottomOffset;
// spread out the base to avoid vertical seams
vertPos += (vertPos - faceCenter).Unit()
* (decalTemplate->GetPerpendicularFaceOffset() * 2.0f);
}
vertPos += vertOffset;
#else
csVector3 vertPos = *poly.GetVertex(a);
#endif // CS_DECAL_CLIP_DECAL
csVector3 relVert = vertPos - relPos;
size_t vertIdx = vertexCount+a;
// copy over vertex data
vertexBuffer->CopyInto(&vertPos, 1, vertIdx);
// copy over color
csColor4 color;
if (-distToPos >= 0.0f)
{
float t = 0.0f;
if (topPlaneDist >= 0.01f)
t = -distToPos / topPlaneDist;
color = decalTemplate->GetMainColor() * (1.0f - t) + decalTemplate->GetTopColor() * t;
}
else
{
float t = 0.0f;
if (bottomPlaneDist >= 0.01f)
t = distToPos / bottomPlaneDist;
color = decalTemplate->GetMainColor() * (1.0f - t) + decalTemplate->GetBottomColor() * t;
}
colorBuffer->CopyInto(&color, 1, vertIdx);
// create the index buffer for each triangle in the poly
if (a >= 2)
{
tri[1] = vertIdx-1;
tri[2] = vertIdx;
indexBuffer->CopyInto(&tri, 3, indexCount);
indexCount += 3;
}
// generate uv coordinates
csVector2 texCoord(
minTexCoord.x + texCoordRange.x * 0.5f +
texCoordRange.x * localRight * invWidth * relVert,
minTexCoord.y + texCoordRange.y * 0.5f -
texCoordRange.y * localUp * invHeight * relVert);
texCoordBuffer->CopyInto(&texCoord, 1, vertIdx);
// copy over normal
normalBuffer->CopyInto(&localNormal, 1, vertIdx);
}
vertexCount += vertCount;
}
void csDecal::EndMesh()
{
if (!currMesh)
return;
// make sure we actually added some geometry before we create a rendermesh
if (indexCount == firstIndex)
return;
// create a rendermesh for this mesh
csRenderMesh* pRenderMesh = decalManager->renderMeshAllocator.Alloc();
csDecalRenderMeshInfo renderMeshInfo;
renderMeshInfo.pRenderMesh = pRenderMesh;
renderMeshInfo.mesh = currMesh;
renderMeshInfos.Push(renderMeshInfo);
pRenderMesh->mixmode = decalTemplate->GetMixMode();
pRenderMesh->meshtype = CS_MESHTYPE_TRIANGLES;
pRenderMesh->indexstart = firstIndex;
pRenderMesh->indexend = indexCount;
pRenderMesh->material = decalTemplate->GetMaterialWrapper();
pRenderMesh->buffers = bufferHolder;
pRenderMesh->geometryInstance = (void *)bufferHolder;
//variableContext.AttachNew(new csShaderVariableContext);
//pRenderMesh->variablecontext = variableContext;
currMesh->AddExtraRenderMesh(pRenderMesh,
decalTemplate->GetRenderPriority(), decalTemplate->GetZBufMode());
}
bool csDecal::Age (csTicks ticks)
{
const float lifespan = decalTemplate->GetTimeToLive ();
life += (float)ticks * 0.001f;
if (lifespan <= 0.0f)
return true;
return life < lifespan;
}
void csDecal::ClearRenderMeshes()
{
const size_t len = renderMeshInfos.GetSize();
for (size_t a=0; a<len; ++a)
{
renderMeshInfos[a].mesh->RemoveExtraRenderMesh(
renderMeshInfos[a].pRenderMesh);
decalManager->renderMeshAllocator.Free(renderMeshInfos[a].pRenderMesh);
}
renderMeshInfos.Empty();
}
<|endoftext|> |
<commit_before>/* ---------------------------------------------------------------------
* Numenta Platform for Intelligent Computing (NuPIC)
* Copyright (C) 2016, Numenta, Inc. Unless you have an agreement
* with Numenta, Inc., for a separate license for this software code, the
* following terms and conditions apply:
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero Public License version 3 as
* published by the Free Software Foundation.
*
* 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 Public License for more details.
*
* You should have received a copy of the GNU Affero Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*
* http://numenta.org/licenses/
* ---------------------------------------------------------------------
*/
/** @file
* Implementation of Network test
*/
#include "gtest/gtest.h"
#include <nupic/engine/NetworkFactory.hpp>
#include <nupic/engine/Network.hpp>
#include <nupic/engine/NuPIC.hpp>
#include <nupic/engine/Region.hpp>
#include <nupic/os/Path.hpp>
#include <nupic/utils/Log.hpp>
using namespace nupic;
// macro to ease nesting
#define GP Path::getParent
const std::string UNIT_TESTS_EXECUTABLE_PATH = Path::getExecutablePath();
const std::string NUPIC_CORE_PATH = GP(GP(GP(GP(UNIT_TESTS_EXECUTABLE_PATH))));
const std::string PATH_TO_FIXTURES = Path::join(NUPIC_CORE_PATH, "/src/test/unit/engine/fixtures");
TEST(NetworkFactory, ValidYamlTest)
{
NetworkFactory nf;
Network *n;
n = nf.createNetwork(Path::join(PATH_TO_FIXTURES, "network.yaml"));
const Collection<Region*> regionList = n->getRegions();
ASSERT_EQ((UInt32)3, regionList.getCount());
// make sure no region specified in the yaml is null.
Region *l1, *l2, *l3;
l1 = regionList.getByName("level 1");
l2 = regionList.getByName("level 2");
l3 = regionList.getByName("level 3");
ASSERT_TRUE(l1);
ASSERT_TRUE(l2);
ASSERT_TRUE(l3);
ASSERT_TRUE(l1->getOutput("bottomUpOut"));
ASSERT_TRUE(l2->getOutput("bottomUpOut"));
ASSERT_TRUE(l3->getOutput("bottomUpOut"));
ASSERT_TRUE(l1->getInput("bottomUpIn"));
ASSERT_TRUE(l2->getInput("bottomUpIn"));
ASSERT_TRUE(l3->getInput("bottomUpIn"));
}
TEST(NetworkFactory, MissingLinkFieldsFile)
{
NetworkFactory nf;
EXPECT_THROW(nf.createNetwork(Path::join(PATH_TO_FIXTURES, "missing-link-fields.yaml")),
std::exception);
}
TEST(NetworkFactory, MissingRegionFieldsFile)
{
NetworkFactory nf;
EXPECT_THROW(nf.createNetwork(Path::join(PATH_TO_FIXTURES, "missing-region-fields.yaml")),
std::exception);
}
TEST(NetworkFactory, ExtraFieldFile)
{
NetworkFactory nf;
EXPECT_THROW(nf.createNetwork(Path::join(PATH_TO_FIXTURES, "extra-yaml-fields.yaml")),
std::exception);
}
TEST(NetworkFactory, NoRegionsFile)
{
NetworkFactory nf;
EXPECT_THROW(nf.createNetwork(Path::join(PATH_TO_FIXTURES, "no-regions.yaml")),
std::exception);
}
TEST(NetworkFactory, NoLinksFile)
{
NetworkFactory nf;
EXPECT_THROW(nf.createNetwork(Path::join(PATH_TO_FIXTURES, "no-links.yaml")),
std::exception);
}
<commit_msg>network-factory calls destructor in test that doesn't fail<commit_after>/* ---------------------------------------------------------------------
* Numenta Platform for Intelligent Computing (NuPIC)
* Copyright (C) 2016, Numenta, Inc. Unless you have an agreement
* with Numenta, Inc., for a separate license for this software code, the
* following terms and conditions apply:
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero Public License version 3 as
* published by the Free Software Foundation.
*
* 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 Public License for more details.
*
* You should have received a copy of the GNU Affero Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*
* http://numenta.org/licenses/
* ---------------------------------------------------------------------
*/
/** @file
* Implementation of Network test
*/
#include "gtest/gtest.h"
#include <nupic/engine/NetworkFactory.hpp>
#include <nupic/engine/Network.hpp>
#include <nupic/engine/NuPIC.hpp>
#include <nupic/engine/Region.hpp>
#include <nupic/os/Path.hpp>
#include <nupic/utils/Log.hpp>
using namespace nupic;
// macro to ease nesting
#define GP Path::getParent
const std::string UNIT_TESTS_EXECUTABLE_PATH = Path::getExecutablePath();
const std::string NUPIC_CORE_PATH = GP(GP(GP(GP(UNIT_TESTS_EXECUTABLE_PATH))));
const std::string PATH_TO_FIXTURES = Path::join(NUPIC_CORE_PATH, "/src/test/unit/engine/fixtures");
TEST(NetworkFactory, ValidYamlTest)
{
NetworkFactory nf;
Network *n;
n = nf.createNetwork(Path::join(PATH_TO_FIXTURES, "network.yaml"));
const Collection<Region*> regionList = n->getRegions();
ASSERT_EQ((UInt32)3, regionList.getCount());
// make sure no region specified in the yaml is null.
Region *l1, *l2, *l3;
l1 = regionList.getByName("level 1");
l2 = regionList.getByName("level 2");
l3 = regionList.getByName("level 3");
ASSERT_TRUE(l1);
ASSERT_TRUE(l2);
ASSERT_TRUE(l3);
ASSERT_TRUE(l1->getOutput("bottomUpOut"));
ASSERT_TRUE(l2->getOutput("bottomUpOut"));
ASSERT_TRUE(l3->getOutput("bottomUpOut"));
ASSERT_TRUE(l1->getInput("bottomUpIn"));
ASSERT_TRUE(l2->getInput("bottomUpIn"));
ASSERT_TRUE(l3->getInput("bottomUpIn"));
delete n; //make sure to unregister the network.
}
TEST(NetworkFactory, MissingLinkFieldsFile)
{
NetworkFactory nf;
EXPECT_THROW(nf.createNetwork(Path::join(PATH_TO_FIXTURES, "missing-link-fields.yaml")),
std::exception);
}
TEST(NetworkFactory, MissingRegionFieldsFile)
{
NetworkFactory nf;
EXPECT_THROW(nf.createNetwork(Path::join(PATH_TO_FIXTURES, "missing-region-fields.yaml")),
std::exception);
}
TEST(NetworkFactory, ExtraFieldFile)
{
NetworkFactory nf;
EXPECT_THROW(nf.createNetwork(Path::join(PATH_TO_FIXTURES, "extra-yaml-fields.yaml")),
std::exception);
}
TEST(NetworkFactory, NoRegionsFile)
{
NetworkFactory nf;
EXPECT_THROW(nf.createNetwork(Path::join(PATH_TO_FIXTURES, "no-regions.yaml")),
std::exception);
}
TEST(NetworkFactory, NoLinksFile)
{
NetworkFactory nf;
EXPECT_THROW(nf.createNetwork(Path::join(PATH_TO_FIXTURES, "no-links.yaml")),
std::exception);
}
<|endoftext|> |
<commit_before>/*************************************************************************
* Copyright (c) 2013 eProsima. All rights reserved.
*
* This copy of FastCdr is licensed to you under the terms described in the
* EPROSIMARTPS_LIBRARY_LICENSE file included in this distribution.
*
*************************************************************************/
/*
* StatelessTest.cpp
*
* Created on: Feb 26, 2014
* Author: Gonzalo Rodriguez Canosa
* email: gonzalorodriguez@eprosima.com
* grcanosa@gmail.com
*/
#include <stdio.h>
#include <string>
#include <iostream>
#include <iomanip>
#include <bitset>
#include <cstdint>
//
#include "eprosimartps/dds/DomainParticipant.h"
#include "eprosimartps/Participant.h"
#include "eprosimartps/dds/Publisher.h"
#include "eprosimartps/dds/Subscriber.h"
#include "eprosimartps/common/colors.h"
#include "eprosimartps/dds/ParameterList.h"
#include "eprosimartps/utils/RTPSLog.h"
#include "boost/date_time/posix_time/posix_time.hpp"
#include "boost/date_time/gregorian/gregorian.hpp"
using namespace eprosima;
using namespace dds;
using namespace rtps;
using namespace std;
#define WR 1 //Writer 1, Reader 2
#if defined(__LITTLE_ENDIAN__)
const Endianness_t DEFAULT_ENDIAN = LITTLEEND;
#elif defined (__BIG_ENDIAN__)
const Endianness_t DEFAULT_ENDIAN = BIGEND;
#endif
#if defined(_WIN32)
#define COPYSTR strcpy_s
#else
#define COPYSTR strcpy
#endif
typedef struct LatencyType{
int64_t seqnum;
unsigned char data[500];
LatencyType()
{
seqnum = 0;
}
}LatencyType;
void LatencySer(SerializedPayload_t* payload,void*data)
{
memcpy(payload->data,data,sizeof(LatencyType));
}
void LatencyDeSer(SerializedPayload_t* payload,void*data)
{
memcpy(data,payload->data,sizeof(LatencyType));
}
void LatencyGetKey(void* data,InstanceHandle_t* handle )
{
handle->value[0] = 0;
handle->value[1] = 0;
handle->value[2] = 0;
handle->value[3] = 5; //length of string in CDR BE
handle->value[4] = 1;
handle->value[5] = 2;
handle->value[6] = 3;
handle->value[7] = 4;
handle->value[8] = 5;
for(uint8_t i=9;i<16;i++)
handle->value[i] = 0;
}
boost::posix_time::ptime t1,t2,t3;
void newMsgCallback()
{
t2 = boost::posix_time::microsec_clock::local_time();
cout << MAGENTA"New Message Callback" <<DEF<< endl;
}
int main(int argc, char** argv){
RTPSLog::setVerbosity(RTPSLog::EPROSIMA_DEBUGINFO_VERBOSITY_LEVEL);
cout << "Starting "<< endl;
pInfo("Starting"<<endl)
int type;
if(argc > 1)
{
RTPSLog::Info << "Parsing arguments: " << argv[1] << endl;
RTPSLog::printInfo();
if(strcmp(argv[1],"publisher")==0)
type = 1;
if(strcmp(argv[1],"subscriber")==0)
type = 2;
}
else
type = WR;
boost::posix_time::time_duration overhead;
//CLOCK OVERHEAD
t1 = boost::posix_time::microsec_clock::local_time();
for(int i=0;i<400;i++)
t2= boost::posix_time::microsec_clock::local_time();
overhead = (t2-t1);
long overhead_value = ceil(overhead.total_microseconds()/400);
cout << "Overhead " << overhead_value << endl;
LatencyType Latency;
//*********** PARTICIPANT ******************//
ParticipantParams_t PParam;
PParam.defaultSendPort = 10042;
Participant* p = DomainParticipant::createParticipant(PParam);
//Registrar tipo de dato.
DomainParticipant::registerType(std::string("LatencyType"),&LatencySer,&LatencyDeSer,&LatencyGetKey,sizeof(LatencyType));
//************* PUBLISHER **********************//
if(type == 1)
{
WriterParams_t Wparam;
Wparam.pushMode = true;
Wparam.stateKind = STATEFUL;
Wparam.topicKind = WITH_KEY;
Wparam.topicDataType = std::string("LatencyType");
Wparam.topicName = std::string("This is a test topic");
Wparam.historySize = 10;
Wparam.reliablility.heartbeatPeriod.seconds = 2;
Wparam.reliablility.nackResponseDelay.seconds = 2;
Wparam.reliablility.kind = RELIABLE;
Publisher* pub = DomainParticipant::createPublisher(p,Wparam);
if(pub == NULL)
return 0;
//Reader Proxy
Locator_t loc;
loc.kind = 1;
loc.port = 10043;
loc.set_IP4_address(192,168,1,23);
GUID_t readerGUID;
readerGUID.entityId = ENTITYID_UNKNOWN;
pub->addReaderProxy(loc,readerGUID,true);
for(uint8_t i = 0;i<10;i++)
{
if(i == 2 || 0i==4||i==5)
p->loose_next_change();
pub->write((void*)&Latency);
cout << "Going to sleep "<< (int)i <<endl;
sleep(1);
cout << "Wakes "<<endl;
}
}
else if (type ==2) //********** SUBSCRIBER **************//
{
ReaderParams_t Rparam;
Rparam.historySize = 15;
Rparam.stateKind = STATEFUL;
Rparam.topicDataType = std::string("LatencyType");
Rparam.topicName = std::string("This is a test topic");
Subscriber* sub = DomainParticipant::createSubscriber(p,Rparam);
while(1)
{
cout << "Waiting for new message "<<endl;
sub->blockUntilNewMessage();
sub->readLastAdded((void*)&Latency);
}
}
return 0;
}
<commit_msg>StatefulTest change<commit_after>/*************************************************************************
* Copyright (c) 2013 eProsima. All rights reserved.
*
* This copy of FastCdr is licensed to you under the terms described in the
* EPROSIMARTPS_LIBRARY_LICENSE file included in this distribution.
*
*************************************************************************/
/*
* StatelessTest.cpp
*
* Created on: Feb 26, 2014
* Author: Gonzalo Rodriguez Canosa
* email: gonzalorodriguez@eprosima.com
* grcanosa@gmail.com
*/
#include <stdio.h>
#include <string>
#include <iostream>
#include <iomanip>
#include <bitset>
#include <cstdint>
//
#include "eprosimartps/dds/DomainParticipant.h"
#include "eprosimartps/Participant.h"
#include "eprosimartps/dds/Publisher.h"
#include "eprosimartps/dds/Subscriber.h"
#include "eprosimartps/common/colors.h"
#include "eprosimartps/dds/ParameterList.h"
#include "eprosimartps/utils/RTPSLog.h"
#include "boost/date_time/posix_time/posix_time.hpp"
#include "boost/date_time/gregorian/gregorian.hpp"
using namespace eprosima;
using namespace dds;
using namespace rtps;
using namespace std;
#define WR 1 //Writer 1, Reader 2
#if defined(__LITTLE_ENDIAN__)
const Endianness_t DEFAULT_ENDIAN = LITTLEEND;
#elif defined (__BIG_ENDIAN__)
const Endianness_t DEFAULT_ENDIAN = BIGEND;
#endif
#if defined(_WIN32)
#define COPYSTR strcpy_s
#else
#define COPYSTR strcpy
#endif
typedef struct LatencyType{
int64_t seqnum;
unsigned char data[500];
LatencyType()
{
seqnum = 0;
}
}LatencyType;
void LatencySer(SerializedPayload_t* payload,void*data)
{
memcpy(payload->data,data,sizeof(LatencyType));
}
void LatencyDeSer(SerializedPayload_t* payload,void*data)
{
memcpy(data,payload->data,sizeof(LatencyType));
}
void LatencyGetKey(void* data,InstanceHandle_t* handle )
{
handle->value[0] = 0;
handle->value[1] = 0;
handle->value[2] = 0;
handle->value[3] = 5; //length of string in CDR BE
handle->value[4] = 1;
handle->value[5] = 2;
handle->value[6] = 3;
handle->value[7] = 4;
handle->value[8] = 5;
for(uint8_t i=9;i<16;i++)
handle->value[i] = 0;
}
boost::posix_time::ptime t1,t2,t3;
void newMsgCallback()
{
t2 = boost::posix_time::microsec_clock::local_time();
cout << MAGENTA"New Message Callback" <<DEF<< endl;
}
int main(int argc, char** argv){
RTPSLog::setVerbosity(RTPSLog::EPROSIMA_DEBUGINFO_VERBOSITY_LEVEL);
cout << "Starting "<< endl;
pInfo("Starting"<<endl)
int type;
if(argc > 1)
{
RTPSLog::Info << "Parsing arguments: " << argv[1] << endl;
RTPSLog::printInfo();
if(strcmp(argv[1],"publisher")==0)
type = 1;
if(strcmp(argv[1],"subscriber")==0)
type = 2;
}
else
type = WR;
boost::posix_time::time_duration overhead;
//CLOCK OVERHEAD
t1 = boost::posix_time::microsec_clock::local_time();
for(int i=0;i<400;i++)
t2= boost::posix_time::microsec_clock::local_time();
overhead = (t2-t1);
long overhead_value = ceil(overhead.total_microseconds()/400);
cout << "Overhead " << overhead_value << endl;
LatencyType Latency;
//*********** PARTICIPANT ******************//
ParticipantParams_t PParam;
PParam.defaultSendPort = 10042;
Participant* p = DomainParticipant::createParticipant(PParam);
//Registrar tipo de dato.
DomainParticipant::registerType(std::string("LatencyType"),&LatencySer,&LatencyDeSer,&LatencyGetKey,sizeof(LatencyType));
//************* PUBLISHER **********************//
if(type == 1)
{
WriterParams_t Wparam;
Wparam.pushMode = true;
Wparam.stateKind = STATEFUL;
Wparam.topicKind = WITH_KEY;
Wparam.topicDataType = std::string("LatencyType");
Wparam.topicName = std::string("This is a test topic");
Wparam.historySize = 10;
Wparam.reliablility.heartbeatPeriod.seconds = 2;
Wparam.reliablility.nackResponseDelay.seconds = 2;
Wparam.reliablility.kind = RELIABLE;
Publisher* pub = DomainParticipant::createPublisher(p,Wparam);
if(pub == NULL)
return 0;
//Reader Proxy
Locator_t loc;
loc.kind = 1;
loc.port = 10043;
loc.set_IP4_address(192,168,1,23);
GUID_t readerGUID;
readerGUID.entityId = ENTITYID_UNKNOWN;
pub->addReaderProxy(loc,readerGUID,true);
for(uint8_t i = 0;i<10;i++)
{
if(i == 2 || i==4||i==5)
p->loose_next_change();
pub->write((void*)&Latency);
cout << "Going to sleep "<< (int)i <<endl;
sleep(1);
cout << "Wakes "<<endl;
}
}
else if (type ==2) //********** SUBSCRIBER **************//
{
ReaderParams_t Rparam;
Rparam.historySize = 15;
Rparam.stateKind = STATEFUL;
Rparam.topicDataType = std::string("LatencyType");
Rparam.topicName = std::string("This is a test topic");
Subscriber* sub = DomainParticipant::createSubscriber(p,Rparam);
while(1)
{
cout << "Waiting for new message "<<endl;
sub->blockUntilNewMessage();
sub->readLastAdded((void*)&Latency);
}
}
return 0;
}
<|endoftext|> |
<commit_before>/**
* @file bin_file_collection.cc
* @author Stavros Papadopoulos <stavrosp@csail.mit.edu>
*
* @section LICENSE
*
* The MIT License
*
* @copyright Copyright (c) 2014 Stavros Papadopoulos <stavrosp@csail.mit.edu>
*
* 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.
*
* @section DESCRIPTION
*
* This file implements the BINFileCollection class.
*/
#include "bin_file_collection.h"
#include "utils.h"
#include <assert.h>
#include <iostream>
#include <queue>
/******************************************************
************* CONSTRUCTORS & DESTRUCTORS **************
******************************************************/
template<class T>
BINFileCollection<T>::BINFileCollection(const std::string& path)
: workspace_(path) {
write_state_max_size_ = WRITE_STATE_MAX_SIZE;
segment_size_ = SEGMENT_SIZE;
pq_ = NULL;
}
template<class T>
BINFileCollection<T>::~BINFileCollection() {
close();
}
/******************************************************
******************** BASIC METHODS ********************
******************************************************/
template<class T>
int BINFileCollection<T>::close() {
// Clear BIN files
int bin_files_num = int(bin_files_.size());
for(int i=0; i<bin_files_num; ++i) {
bin_files_[i]->close();
delete bin_files_[i];
}
bin_files_.clear();
// Clear cells
for(int i=0; i<cells_.size(); ++i)
delete cells_[i];
cells_.clear();
// Clear the priority queue
if(pq_ != NULL) {
std::priority_queue<std::pair<const Cell*, int>,
std::vector<std::pair<const Cell*, int> >,
Cell::Succeeds<T> >*
pq = static_cast<std::priority_queue<
std::pair<const Cell*, int>,
std::vector<std::pair<const Cell*, int> >,
Cell::Succeeds<T> >*>(pq_);
while(!pq->empty()) {
delete pq->top().first;
pq->pop();
}
delete pq;
pq_ = NULL;
}
// Clear last popped cell
if(last_popped_cell_ != NULL)
delete last_popped_cell_;
// Delete directory
delete_directory(workspace_);
return 0;
}
template<class T>
int BINFileCollection<T>::open(
const ArraySchema* array_schema,
int id_num,
const std::string& path,
bool sorted) {
// Initialization
array_schema_ = array_schema;
sorted_ = sorted;
last_accessed_file_ = -1;
last_popped_cell_ = NULL;
id_num_ = id_num;
// Create directory
create_directory(workspace_);
// Gather all files in path
if(is_file(path)) {
filenames_.push_back(path);
} else if(is_dir(path)) {
filenames_ = get_filenames(path);
} else {
std::cerr << ERROR_MSG_HEADER
<< " Path '" << path << "' does not exists.\n";
return TILEDB_EFILE;
}
// Create priority queue
std::priority_queue<std::pair<const Cell*, int>,
std::vector<std::pair<const Cell*, int> >,
Cell::Succeeds<T> >* pq;
if(sorted) {
pq = new std::priority_queue<std::pair<const Cell*, int>,
std::vector<std::pair<const Cell*, int> >,
Cell::Succeeds<T> >;
pq_ = pq;
}
// Open files and prepare first cells
int file_num = int(filenames_.size());
BINFile* bin_file;
Cell* cell;
for(int i=0; i<file_num; ++i) {
bin_file = new BINFile(array_schema_, id_num_);
if(is_file(filenames_[i]))
bin_file->open(filenames_[i], "r");
else
bin_file->open(path + "/" + filenames_[i], "r");
bin_files_.push_back(bin_file);
cell = new Cell(array_schema_, id_num_);
*bin_file >> *cell;
if(sorted)
pq->push(std::pair<const Cell*, int>(cell,i));
else
cells_.push_back(cell);
}
return 0;
}
/******************************************************
********************** OPERATORS **********************
******************************************************/
template<class T>
bool BINFileCollection<T>::operator>>(Cell& cell) {
assert(bin_files_.size());
cell.set_cell(NULL);
std::priority_queue<std::pair<const Cell*, int>,
std::vector<std::pair<const Cell*, int> >,
Cell::Succeeds<T> >*
pq = static_cast<std::priority_queue<
std::pair<const Cell*, int>,
std::vector<std::pair<const Cell*, int> >,
Cell::Succeeds<T> >*>(pq_);
// Update the cell of the lastly accessed file
if(last_accessed_file_ != -1) {
if(sorted_) {
Cell* cell = new Cell(array_schema_, id_num_);
*bin_files_[last_accessed_file_] >> *cell;
if(cell->cell() != NULL)
pq->push(std::pair<const Cell*, int>(cell,last_accessed_file_));
} else {
*bin_files_[last_accessed_file_] >> *cells_[last_accessed_file_];
}
}
// In the case of 'sorted', we need to search for the
// the cell that appears first in the cell order
if(!sorted_) { // UNSORTED
if(last_accessed_file_ == -1)
last_accessed_file_ = 0;
if(last_accessed_file_ < bin_files_.size()) {
// Get the next cell
if(cells_[last_accessed_file_]->cell() != NULL) {
cell = *cells_[last_accessed_file_];
} else {
++last_accessed_file_;
if(last_accessed_file_ < bin_files_.size())
cell = *cells_[last_accessed_file_];
else
cell.set_cell(NULL);
}
} else {
cell.set_cell(NULL);
}
} else { // SORTED
if(!pq->empty()) {
if(last_popped_cell_ != NULL)
delete last_popped_cell_;
cell = *(pq->top()).first;
last_popped_cell_ = (pq->top()).first;
last_accessed_file_ = (pq->top()).second;
pq->pop();
}
}
if(cell.cell() != NULL)
return true;
else
return false;
}
// Explicit template instantiations
template class BINFileCollection<int>;
template class BINFileCollection<int64_t>;
template class BINFileCollection<float>;
template class BINFileCollection<double>;
<commit_msg>Bug fix in BINFileCollection.<commit_after>/**
* @file bin_file_collection.cc
* @author Stavros Papadopoulos <stavrosp@csail.mit.edu>
*
* @section LICENSE
*
* The MIT License
*
* @copyright Copyright (c) 2014 Stavros Papadopoulos <stavrosp@csail.mit.edu>
*
* 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.
*
* @section DESCRIPTION
*
* This file implements the BINFileCollection class.
*/
#include "bin_file_collection.h"
#include "utils.h"
#include <assert.h>
#include <iostream>
#include <queue>
/******************************************************
************* CONSTRUCTORS & DESTRUCTORS **************
******************************************************/
template<class T>
BINFileCollection<T>::BINFileCollection(const std::string& path)
: workspace_(path) {
write_state_max_size_ = WRITE_STATE_MAX_SIZE;
segment_size_ = SEGMENT_SIZE;
pq_ = NULL;
}
template<class T>
BINFileCollection<T>::~BINFileCollection() {
close();
}
/******************************************************
******************** BASIC METHODS ********************
******************************************************/
template<class T>
int BINFileCollection<T>::close() {
// Clear BIN files
int bin_files_num = int(bin_files_.size());
for(int i=0; i<bin_files_num; ++i) {
bin_files_[i]->close();
delete bin_files_[i];
}
bin_files_.clear();
// Clear cells
for(int i=0; i<cells_.size(); ++i)
delete cells_[i];
cells_.clear();
// Clear the priority queue
if(pq_ != NULL) {
std::priority_queue<std::pair<const Cell*, int>,
std::vector<std::pair<const Cell*, int> >,
Cell::Succeeds<T> >*
pq = static_cast<std::priority_queue<
std::pair<const Cell*, int>,
std::vector<std::pair<const Cell*, int> >,
Cell::Succeeds<T> >*>(pq_);
while(!pq->empty()) {
delete pq->top().first;
pq->pop();
}
delete pq;
pq_ = NULL;
}
// Clear last popped cell
if(last_popped_cell_ != NULL) {
delete last_popped_cell_;
last_popped_cell_ = NULL;
}
// Delete directory
delete_directory(workspace_);
return 0;
}
template<class T>
int BINFileCollection<T>::open(
const ArraySchema* array_schema,
int id_num,
const std::string& path,
bool sorted) {
// Initialization
array_schema_ = array_schema;
sorted_ = sorted;
last_accessed_file_ = -1;
last_popped_cell_ = NULL;
id_num_ = id_num;
// Create directory
create_directory(workspace_);
// Gather all files in path
if(is_file(path)) {
filenames_.push_back(path);
} else if(is_dir(path)) {
filenames_ = get_filenames(path);
} else {
std::cerr << ERROR_MSG_HEADER
<< " Path '" << path << "' does not exists.\n";
return TILEDB_EFILE;
}
// Create priority queue
std::priority_queue<std::pair<const Cell*, int>,
std::vector<std::pair<const Cell*, int> >,
Cell::Succeeds<T> >* pq;
if(sorted) {
pq = new std::priority_queue<std::pair<const Cell*, int>,
std::vector<std::pair<const Cell*, int> >,
Cell::Succeeds<T> >;
pq_ = pq;
}
// Open files and prepare first cells
int file_num = int(filenames_.size());
BINFile* bin_file;
Cell* cell;
for(int i=0; i<file_num; ++i) {
bin_file = new BINFile(array_schema_, id_num_);
if(is_file(filenames_[i]))
bin_file->open(filenames_[i], "r");
else
bin_file->open(path + "/" + filenames_[i], "r");
bin_files_.push_back(bin_file);
cell = new Cell(array_schema_, id_num_);
*bin_file >> *cell;
if(sorted)
pq->push(std::pair<const Cell*, int>(cell,i));
else
cells_.push_back(cell);
}
return 0;
}
/******************************************************
********************** OPERATORS **********************
******************************************************/
template<class T>
bool BINFileCollection<T>::operator>>(Cell& cell) {
assert(bin_files_.size());
cell.set_cell(NULL);
std::priority_queue<std::pair<const Cell*, int>,
std::vector<std::pair<const Cell*, int> >,
Cell::Succeeds<T> >*
pq = static_cast<std::priority_queue<
std::pair<const Cell*, int>,
std::vector<std::pair<const Cell*, int> >,
Cell::Succeeds<T> >*>(pq_);
// Update the cell of the lastly accessed file
if(last_accessed_file_ != -1) {
if(sorted_) {
Cell* cell = new Cell(array_schema_, id_num_);
*bin_files_[last_accessed_file_] >> *cell;
if(cell->cell() != NULL)
pq->push(std::pair<const Cell*, int>(cell,last_accessed_file_));
} else {
*bin_files_[last_accessed_file_] >> *cells_[last_accessed_file_];
}
}
// In the case of 'sorted', we need to search for the
// the cell that appears first in the cell order
if(!sorted_) { // UNSORTED
if(last_accessed_file_ == -1)
last_accessed_file_ = 0;
if(last_accessed_file_ < bin_files_.size()) {
// Get the next cell
if(cells_[last_accessed_file_]->cell() != NULL) {
cell = *cells_[last_accessed_file_];
} else {
++last_accessed_file_;
if(last_accessed_file_ < bin_files_.size())
cell = *cells_[last_accessed_file_];
else
cell.set_cell(NULL);
}
} else {
cell.set_cell(NULL);
}
} else { // SORTED
if(!pq->empty()) {
if(last_popped_cell_ != NULL)
delete last_popped_cell_;
cell = *(pq->top()).first;
last_popped_cell_ = (pq->top()).first;
last_accessed_file_ = (pq->top()).second;
pq->pop();
}
}
if(cell.cell() != NULL)
return true;
else
return false;
}
// Explicit template instantiations
template class BINFileCollection<int>;
template class BINFileCollection<int64_t>;
template class BINFileCollection<float>;
template class BINFileCollection<double>;
<|endoftext|> |
<commit_before>/**
* @author Parikshit Ram (pram@cc.gatech.edu)
* @file nbc_main.cpp
*
* This program runs the Simple Naive Bayes Classifier.
*
* This classifier does parametric naive bayes classification assuming that the
* features are sampled from a Gaussian distribution.
*/
#include <mlpack/core.hpp>
#include "naive_bayes_classifier.hpp"
PROGRAM_INFO("Parametric Naive Bayes Classifier",
"This program trains the Naive Bayes classifier on the given labeled "
"training set and then uses the trained classifier to classify the points "
"in the given test set.\n"
"\n"
"Labels are expected to be the last row of the training set (--train_file),"
" but labels can also be passed in separately as their own file "
"(--labels_file).");
PARAM_STRING_REQ("train_file", "A file containing the training set.", "t");
PARAM_STRING_REQ("test_file", "A file containing the test set.", "T");
PARAM_STRING("labels_file", "A file containing labels for the training set.",
"l", "");
PARAM_STRING("output", "The file in which the predicted labels for the test set"
" will be written.", "o", "output.csv");
using namespace mlpack;
using namespace mlpack::naive_bayes;
using namespace std;
using namespace arma;
int main(int argc, char* argv[])
{
CLI::ParseCommandLine(argc, argv);
// Check input parameters.
const string trainingDataFilename = CLI::GetParam<string>("train_file");
mat trainingData;
data::Load(trainingDataFilename, trainingData, true);
// Normalize labels.
Col<size_t> labels;
vec mappings;
// Did the user pass in labels?
const string labelsFilename = CLI::GetParam<string>("labels_file");
if (labelsFilename != "")
{
// Load labels.
mat rawLabels;
data::Load(labelsFilename, rawLabels, true, false);
// Do the labels need to be transposed?
if (rawLabels.n_rows == 1)
rawLabels = rawLabels.t();
data::NormalizeLabels(rawLabels.unsafe_col(0), labels, mappings);
}
else
{
// Use the last row of the training data as the labels.
Log::Info << "Using last dimension of training data as training labels."
<< std::endl;
vec rawLabels = trans(trainingData.row(trainingData.n_rows - 1));
data::NormalizeLabels(rawLabels, labels, mappings);
// Remove the label row.
trainingData.shed_row(trainingData.n_rows - 1);
}
const string testingDataFilename = CLI::GetParam<std::string>("test_file");
mat testingData;
data::Load(testingDataFilename, testingData, true);
if (testingData.n_rows != trainingData.n_rows)
Log::Fatal << "Test data dimensionality (" << testingData.n_rows << ") "
<< "must be the same as training data (" << trainingData.n_rows - 1
<< ")!" << std::endl;
// Calculate number of classes.
size_t classes = (size_t) max(trainingData.row(trainingData.n_rows - 1)) + 1;
// Create and train the classifier.
Timer::Start("training");
NaiveBayesClassifier<> nbc(trainingData, labels, classes);
Timer::Stop("training");
// Time the running of the Naive Bayes Classifier.
Col<size_t> results;
Timer::Start("testing");
nbc.Classify(testingData, results);
Timer::Stop("testing");
// Un-normalize labels to prepare output.
vec rawResults;
data::RevertLabels(results, mappings, rawResults);
// Output results.
const string outputFilename = CLI::GetParam<string>("output");
data::Save(outputFilename, results, true);
}
<commit_msg>Get the number of classes correctly.<commit_after>/**
* @author Parikshit Ram (pram@cc.gatech.edu)
* @file nbc_main.cpp
*
* This program runs the Simple Naive Bayes Classifier.
*
* This classifier does parametric naive bayes classification assuming that the
* features are sampled from a Gaussian distribution.
*/
#include <mlpack/core.hpp>
#include "naive_bayes_classifier.hpp"
PROGRAM_INFO("Parametric Naive Bayes Classifier",
"This program trains the Naive Bayes classifier on the given labeled "
"training set and then uses the trained classifier to classify the points "
"in the given test set.\n"
"\n"
"Labels are expected to be the last row of the training set (--train_file),"
" but labels can also be passed in separately as their own file "
"(--labels_file).");
PARAM_STRING_REQ("train_file", "A file containing the training set.", "t");
PARAM_STRING_REQ("test_file", "A file containing the test set.", "T");
PARAM_STRING("labels_file", "A file containing labels for the training set.",
"l", "");
PARAM_STRING("output", "The file in which the predicted labels for the test set"
" will be written.", "o", "output.csv");
using namespace mlpack;
using namespace mlpack::naive_bayes;
using namespace std;
using namespace arma;
int main(int argc, char* argv[])
{
CLI::ParseCommandLine(argc, argv);
// Check input parameters.
const string trainingDataFilename = CLI::GetParam<string>("train_file");
mat trainingData;
data::Load(trainingDataFilename, trainingData, true);
// Normalize labels.
Col<size_t> labels;
vec mappings;
// Did the user pass in labels?
const string labelsFilename = CLI::GetParam<string>("labels_file");
if (labelsFilename != "")
{
// Load labels.
mat rawLabels;
data::Load(labelsFilename, rawLabels, true, false);
// Do the labels need to be transposed?
if (rawLabels.n_rows == 1)
rawLabels = rawLabels.t();
data::NormalizeLabels(rawLabels.unsafe_col(0), labels, mappings);
}
else
{
// Use the last row of the training data as the labels.
Log::Info << "Using last dimension of training data as training labels."
<< std::endl;
vec rawLabels = trans(trainingData.row(trainingData.n_rows - 1));
data::NormalizeLabels(rawLabels, labels, mappings);
// Remove the label row.
trainingData.shed_row(trainingData.n_rows - 1);
}
const string testingDataFilename = CLI::GetParam<std::string>("test_file");
mat testingData;
data::Load(testingDataFilename, testingData, true);
if (testingData.n_rows != trainingData.n_rows)
Log::Fatal << "Test data dimensionality (" << testingData.n_rows << ") "
<< "must be the same as training data (" << trainingData.n_rows - 1
<< ")!" << std::endl;
// Create and train the classifier.
Timer::Start("training");
NaiveBayesClassifier<> nbc(trainingData, labels, mappings.n_elem);
Timer::Stop("training");
// Time the running of the Naive Bayes Classifier.
Col<size_t> results;
Timer::Start("testing");
nbc.Classify(testingData, results);
Timer::Stop("testing");
// Un-normalize labels to prepare output.
vec rawResults;
data::RevertLabels(results, mappings, rawResults);
// Output results.
const string outputFilename = CLI::GetParam<string>("output");
data::Save(outputFilename, results, true);
}
<|endoftext|> |
<commit_before>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 2000-2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
#include "FunctionNormalizeSpace.hpp"
#include <xalanc/DOMSupport/DOMServices.hpp>
#include "XObjectFactory.hpp"
XALAN_CPP_NAMESPACE_BEGIN
FunctionNormalizeSpace::FunctionNormalizeSpace()
{
}
FunctionNormalizeSpace::~FunctionNormalizeSpace()
{
}
XObjectPtr
FunctionNormalizeSpace::execute(
XPathExecutionContext& executionContext,
XalanNode* context,
const LocatorType* locator) const
{
if (context == 0)
{
executionContext.error(
"The normalize-space() function requires a non-null context node!",
context,
locator);
// Dummy return value...
return XObjectPtr(0);
}
else
{
// The XPath standard says that if there are no arguments,
// the default is to turn the context node into a string value.
// DOMServices::getNodeData() will give us the data.
// Get a cached string...
XPathExecutionContext::GetAndReleaseCachedString theData(executionContext);
XalanDOMString& theString = theData.get();
DOMServices::getNodeData(*context, theString);
return normalize(executionContext, theString);
}
}
XObjectPtr
FunctionNormalizeSpace::execute(
XPathExecutionContext& executionContext,
XalanNode* /* context */,
const XObjectPtr arg1,
const LocatorType* /* locator */) const
{
assert(arg1.null() == false);
return normalize(executionContext, arg1);
}
XObjectPtr
FunctionNormalizeSpace::normalize(
XPathExecutionContext& executionContext,
const XalanDOMString& theString) const
{
const XalanDOMString::size_type theStringLength = length(theString);
// A string contain the result...
XPathExecutionContext::GetAndReleaseCachedString theResult(executionContext);
XalanDOMString& theNewString = theResult.get();
assert(length(theNewString) == 0);
// The result string can only be as large as the source string, so
// just reserve the space now.
reserve(theNewString, theStringLength);
bool fPreviousIsSpace = false;
// OK, strip out any multiple spaces...
for (unsigned int i = 0; i < theStringLength; i++)
{
const XalanDOMChar theCurrentChar = charAt(theString, i);
if (isXMLWhitespace(theCurrentChar) == true)
{
// If the previous character wasn't a space, and we've
// encountered some non-space characters, and it's not
// the last character in the string, then push the
// space character (not the original character).
if (fPreviousIsSpace == false)
{
if (length(theNewString) > 0 &&
i < theStringLength - 1)
{
append(theNewString, XalanDOMChar(XalanUnicode::charSpace));
}
fPreviousIsSpace = true;
}
}
else
{
append(theNewString, theCurrentChar);
fPreviousIsSpace = false;
}
}
const XalanDOMString::size_type theNewStringLength = length(theNewString);
if (theNewStringLength == 0)
{
return executionContext.getXObjectFactory().createString(XalanDOMString());
}
else
{
// We may have a space character at end, since we don't look ahead,
// so removed it now...
if (charAt(theNewString, theNewStringLength - 1) ==
XalanDOMChar(XalanUnicode::charSpace))
{
theNewString.erase(theNewStringLength - 1, 1);
}
return executionContext.getXObjectFactory().createString(theResult);
}
}
XObjectPtr
FunctionNormalizeSpace::normalize(
XPathExecutionContext& executionContext,
const XObjectPtr& theArg) const
{
const XalanDOMString& theString = theArg->str();
if (needsNormalization(theString) == false)
{
return theArg;
}
else
{
return normalize(executionContext, theString);
}
}
#if defined(XALAN_NO_COVARIANT_RETURN_TYPE)
Function*
#else
FunctionNormalizeSpace*
#endif
FunctionNormalizeSpace::clone() const
{
return new FunctionNormalizeSpace(*this);
}
const XalanDOMString
FunctionNormalizeSpace::getError() const
{
return StaticStringToDOMString(XALAN_STATIC_UCODE_STRING("The normalize-space() function takes zero arguments or one argument!"));
}
bool
FunctionNormalizeSpace::needsNormalization(const XalanDOMString& theString) const
{
const XalanDOMString::size_type theStringLength = length(theString);
bool fNormalize = false;
bool fPreviousIsSpace = false;
// OK, search for multiple spaces, or whitespace that is not the
// space character...
for (XalanDOMString::size_type i = 0; i < theStringLength && fNormalize == false; ++i)
{
const XalanDOMChar theCurrentChar = charAt(theString, i);
if (isXMLWhitespace(theCurrentChar) == false)
{
fPreviousIsSpace = false;
}
else
{
if (i == 0 ||
i == theStringLength - 1 ||
theCurrentChar != XalanDOMChar(XalanUnicode::charSpace) ||
fPreviousIsSpace == true)
{
fNormalize = true;
}
else
{
fPreviousIsSpace = true;
}
}
}
return fNormalize;
}
XALAN_CPP_NAMESPACE_END
<commit_msg>Make sure when optimizing, that we return a string. Fixes Bugzilla 22218.<commit_after>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 2000-2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
#include "FunctionNormalizeSpace.hpp"
#include <xalanc/DOMSupport/DOMServices.hpp>
#include "XObjectFactory.hpp"
XALAN_CPP_NAMESPACE_BEGIN
FunctionNormalizeSpace::FunctionNormalizeSpace()
{
}
FunctionNormalizeSpace::~FunctionNormalizeSpace()
{
}
XObjectPtr
FunctionNormalizeSpace::execute(
XPathExecutionContext& executionContext,
XalanNode* context,
const LocatorType* locator) const
{
if (context == 0)
{
executionContext.error(
"The normalize-space() function requires a non-null context node!",
context,
locator);
// Dummy return value...
return XObjectPtr(0);
}
else
{
// The XPath standard says that if there are no arguments,
// the default is to turn the context node into a string value.
// DOMServices::getNodeData() will give us the data.
// Get a cached string...
XPathExecutionContext::GetAndReleaseCachedString theData(executionContext);
XalanDOMString& theString = theData.get();
DOMServices::getNodeData(*context, theString);
return normalize(executionContext, theString);
}
}
XObjectPtr
FunctionNormalizeSpace::execute(
XPathExecutionContext& executionContext,
XalanNode* /* context */,
const XObjectPtr arg1,
const LocatorType* /* locator */) const
{
assert(arg1.null() == false);
return normalize(executionContext, arg1);
}
XObjectPtr
FunctionNormalizeSpace::normalize(
XPathExecutionContext& executionContext,
const XalanDOMString& theString) const
{
const XalanDOMString::size_type theStringLength = length(theString);
// A string contain the result...
XPathExecutionContext::GetAndReleaseCachedString theResult(executionContext);
XalanDOMString& theNewString = theResult.get();
assert(length(theNewString) == 0);
// The result string can only be as large as the source string, so
// just reserve the space now.
reserve(theNewString, theStringLength);
bool fPreviousIsSpace = false;
// OK, strip out any multiple spaces...
for (unsigned int i = 0; i < theStringLength; i++)
{
const XalanDOMChar theCurrentChar = charAt(theString, i);
if (isXMLWhitespace(theCurrentChar) == true)
{
// If the previous character wasn't a space, and we've
// encountered some non-space characters, and it's not
// the last character in the string, then push the
// space character (not the original character).
if (fPreviousIsSpace == false)
{
if (length(theNewString) > 0 &&
i < theStringLength - 1)
{
append(theNewString, XalanDOMChar(XalanUnicode::charSpace));
}
fPreviousIsSpace = true;
}
}
else
{
append(theNewString, theCurrentChar);
fPreviousIsSpace = false;
}
}
const XalanDOMString::size_type theNewStringLength = length(theNewString);
if (theNewStringLength == 0)
{
return executionContext.getXObjectFactory().createString(XalanDOMString());
}
else
{
// We may have a space character at end, since we don't look ahead,
// so removed it now...
if (charAt(theNewString, theNewStringLength - 1) ==
XalanDOMChar(XalanUnicode::charSpace))
{
theNewString.erase(theNewStringLength - 1, 1);
}
return executionContext.getXObjectFactory().createString(theResult);
}
}
XObjectPtr
FunctionNormalizeSpace::normalize(
XPathExecutionContext& executionContext,
const XObjectPtr& theArg) const
{
const XalanDOMString& theString = theArg->str();
if (needsNormalization(theString) == false)
{
if (theArg->getType() == XObject::eTypeString)
{
return theArg;
}
else
{
return executionContext.getXObjectFactory().createStringAdapter(theArg);
}
}
else
{
return normalize(executionContext, theString);
}
}
#if defined(XALAN_NO_COVARIANT_RETURN_TYPE)
Function*
#else
FunctionNormalizeSpace*
#endif
FunctionNormalizeSpace::clone() const
{
return new FunctionNormalizeSpace(*this);
}
const XalanDOMString
FunctionNormalizeSpace::getError() const
{
return StaticStringToDOMString(XALAN_STATIC_UCODE_STRING("The normalize-space() function takes zero arguments or one argument!"));
}
bool
FunctionNormalizeSpace::needsNormalization(const XalanDOMString& theString) const
{
const XalanDOMString::size_type theStringLength = length(theString);
bool fNormalize = false;
bool fPreviousIsSpace = false;
// OK, search for multiple spaces, or whitespace that is not the
// space character...
for (XalanDOMString::size_type i = 0; i < theStringLength && fNormalize == false; ++i)
{
const XalanDOMChar theCurrentChar = charAt(theString, i);
if (isXMLWhitespace(theCurrentChar) == false)
{
fPreviousIsSpace = false;
}
else
{
if (i == 0 ||
i == theStringLength - 1 ||
theCurrentChar != XalanDOMChar(XalanUnicode::charSpace) ||
fPreviousIsSpace == true)
{
fNormalize = true;
}
else
{
fPreviousIsSpace = true;
}
}
}
return fNormalize;
}
XALAN_CPP_NAMESPACE_END
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "rtp_dump_impl.h"
#include <cassert>
#include <stdio.h>
#include "critical_section_wrapper.h"
#include "trace.h"
#if defined(_WIN32)
#include <Windows.h>
#include <mmsystem.h>
#elif defined(WEBRTC_LINUX) || defined(WEBRTC_MAC)
#include <string.h>
#include <sys/time.h>
#include <time.h>
#endif
#if (defined(_DEBUG) && defined(_WIN32))
#define DEBUG_PRINT(expr) OutputDebugString(##expr)
#define DEBUG_PRINTP(expr, p) \
{ \
char msg[128]; \
sprintf(msg, ##expr, p); \
OutputDebugString(msg); \
}
#else
#define DEBUG_PRINT(expr) ((void)0)
#define DEBUG_PRINTP(expr,p) ((void)0)
#endif // defined(_DEBUG) && defined(_WIN32)
namespace webrtc {
const WebRtc_Word8 RTPFILE_VERSION [] = "1.0";
const WebRtc_UWord32 MAX_UWORD32 = 0xffffffff;
// This stucture is specified in the rtpdump documentation.
// This struct corresponds to RD_packet_t in
// http://www.cs.columbia.edu/irt/software/rtptools/
typedef struct
{
// Length of packet, including this header (may be smaller than plen if not
// whole packet recorded).
WebRtc_UWord16 length;
// Actual header+payload length for RTP, 0 for RTCP.
WebRtc_UWord16 plen;
// Milliseconds since the start of recording.
WebRtc_UWord32 offset;
} rtpDumpPktHdr_t;
RtpDump* RtpDump::CreateRtpDump()
{
WEBRTC_TRACE(kTraceModuleCall, kTraceUtility, -1, "CreateRtpDump()");
return new RtpDumpImpl();
}
void RtpDump::DestroyRtpDump(RtpDump* object)
{
WEBRTC_TRACE(kTraceModuleCall, kTraceUtility, -1, "DestroyRtpDump()");
delete object;
}
RtpDumpImpl::RtpDumpImpl()
: _critSect(*CriticalSectionWrapper::CreateCriticalSection()),
_file(*FileWrapper::Create()),
_startTime(0)
{
WEBRTC_TRACE(kTraceMemory, kTraceUtility, -1, "%s created", __FUNCTION__);
}
RtpDump::~RtpDump()
{
}
RtpDumpImpl::~RtpDumpImpl()
{
_file.Flush();
_file.CloseFile();
delete &_file;
delete &_critSect;
WEBRTC_TRACE(kTraceMemory, kTraceUtility, -1, "%s deleted", __FUNCTION__);
}
WebRtc_Word32 RtpDumpImpl::Start(const WebRtc_Word8* fileNameUTF8)
{
WEBRTC_TRACE(kTraceModuleCall, kTraceUtility, -1, "Start()");
if (fileNameUTF8 == NULL)
{
return -1;
}
CriticalSectionScoped lock(_critSect);
_file.Flush();
_file.CloseFile();
if (_file.OpenFile(fileNameUTF8, false, false, false) == -1)
{
WEBRTC_TRACE(kTraceError, kTraceUtility, -1,
"failed to open the specified file");
return -1;
}
// Store start of RTP dump (to be used for offset calculation later).
_startTime = GetTimeInMS();
// All rtp dump files start with #!rtpplay.
WebRtc_Word8 magic[16];
sprintf(magic, "#!rtpplay%s \n", RTPFILE_VERSION);
_file.WriteText(magic);
// The header according to the rtpdump documentation is sizeof(RD_hdr_t)
// which is 8 + 4 + 2 = 14 bytes for 32-bit architecture (and 22 bytes on
// 64-bit architecture). However, Wireshark use 16 bytes for the header
// regardless of if the binary is 32-bit or 64-bit. Go by the same approach
// as Wireshark since it makes more sense.
// http://wiki.wireshark.org/rtpdump explains that an additional 2 bytes
// of padding should be added to the header.
WebRtc_Word8 dummyHdr[16];
memset(dummyHdr, 0, 16);
_file.Write(dummyHdr, sizeof(dummyHdr));
return 0;
}
WebRtc_Word32 RtpDumpImpl::Stop()
{
WEBRTC_TRACE(kTraceModuleCall, kTraceUtility, -1, "Stop()");
CriticalSectionScoped lock(_critSect);
_file.Flush();
_file.CloseFile();
return 0;
}
bool RtpDumpImpl::IsActive() const
{
CriticalSectionScoped lock(_critSect);
return _file.Open();
}
WebRtc_Word32 RtpDumpImpl::DumpPacket(const WebRtc_UWord8* packet,
WebRtc_UWord16 packetLength)
{
CriticalSectionScoped lock(_critSect);
if (!IsActive())
{
return 0;
}
if (packet == NULL)
{
return -1;
}
if (packetLength < 1)
{
return -1;
}
// If the packet doesn't contain a valid RTCP header the packet will be
// considered RTP (without further verification).
bool isRTCP = RTCP(packet);
rtpDumpPktHdr_t hdr;
WebRtc_UWord32 offset;
// Offset is relative to when recording was started.
offset = GetTimeInMS();
if (offset < _startTime)
{
// Compensate for wraparound.
offset += MAX_UWORD32 - _startTime + 1;
} else {
offset -= _startTime;
}
hdr.offset = RtpDumpHtonl(offset);
hdr.length = RtpDumpHtons((WebRtc_UWord16)(packetLength + sizeof(hdr)));
if (isRTCP)
{
hdr.plen = 0;
}
else
{
hdr.plen = RtpDumpHtons((WebRtc_UWord16)packetLength);
}
_file.Write(&hdr, sizeof(hdr));
_file.Write(packet, packetLength);
return 0;
}
bool RtpDumpImpl::RTCP(const WebRtc_UWord8* packet) const
{
const WebRtc_UWord8 payloadType = packet[1];
bool is_rtcp = false;
switch(payloadType)
{
case 192:
is_rtcp = true;
break;
case 193: case 195:
break;
case 200: case 201: case 202: case 203:
case 204: case 205: case 206: case 207:
is_rtcp = true;
break;
}
return is_rtcp;
}
// TODO (hellner): why is TickUtil not used here?
inline WebRtc_UWord32 RtpDumpImpl::GetTimeInMS() const
{
#if defined(_WIN32)
return timeGetTime();
#elif defined(WEBRTC_LINUX) || defined(WEBRTC_MAC)
struct timeval tv;
struct timezone tz;
unsigned long val;
gettimeofday(&tv, &tz);
val = tv.tv_sec * 1000 + tv.tv_usec / 1000;
return val;
#else
#error Either _WIN32 or LINUX or WEBRTC_MAC has to be defined!
assert(false);
return 0;
#endif
}
inline WebRtc_UWord32 RtpDumpImpl::RtpDumpHtonl(WebRtc_UWord32 x) const
{
#if defined(WEBRTC_BIG_ENDIAN)
return x;
#elif defined(WEBRTC_LITTLE_ENDIAN)
return (x >> 24) + ((((x >> 16) & 0xFF) << 8) + ((((x >> 8) & 0xFF) << 16) +
((x & 0xFF) << 24)));
#else
#error Either WEBRTC_BIG_ENDIAN or WEBRTC_LITTLE_ENDIAN has to be defined!
assert(false);
return 0;
#endif
}
inline WebRtc_UWord16 RtpDumpImpl::RtpDumpHtons(WebRtc_UWord16 x) const
{
#if defined(WEBRTC_BIG_ENDIAN)
return x;
#elif defined(WEBRTC_LITTLE_ENDIAN)
return (x >> 8) + ((x & 0xFF) << 8);
#else
#error Either WEBRTC_BIG_ENDIAN or WEBRTC_LITTLE_ENDIAN has to be defined!
assert(false);
return 0;
#endif
}
} // namespace webrtc
<commit_msg>Fix code review comments.<commit_after>/*
* Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "rtp_dump_impl.h"
#include <cassert>
#include <stdio.h>
#include "critical_section_wrapper.h"
#include "trace.h"
#if defined(_WIN32)
#include <Windows.h>
#include <mmsystem.h>
#elif defined(WEBRTC_LINUX) || defined(WEBRTC_MAC)
#include <string.h>
#include <sys/time.h>
#include <time.h>
#endif
#if (defined(_DEBUG) && defined(_WIN32))
#define DEBUG_PRINT(expr) OutputDebugString(##expr)
#define DEBUG_PRINTP(expr, p) \
{ \
char msg[128]; \
sprintf(msg, ##expr, p); \
OutputDebugString(msg); \
}
#else
#define DEBUG_PRINT(expr) ((void)0)
#define DEBUG_PRINTP(expr,p) ((void)0)
#endif // defined(_DEBUG) && defined(_WIN32)
namespace webrtc {
const WebRtc_Word8 RTPFILE_VERSION[] = "1.0";
const WebRtc_UWord32 MAX_UWORD32 = 0xffffffff;
// This stucture is specified in the rtpdump documentation.
// This struct corresponds to RD_packet_t in
// http://www.cs.columbia.edu/irt/software/rtptools/
typedef struct
{
// Length of packet, including this header (may be smaller than plen if not
// whole packet recorded).
WebRtc_UWord16 length;
// Actual header+payload length for RTP, 0 for RTCP.
WebRtc_UWord16 plen;
// Milliseconds since the start of recording.
WebRtc_UWord32 offset;
} rtpDumpPktHdr_t;
RtpDump* RtpDump::CreateRtpDump()
{
WEBRTC_TRACE(kTraceModuleCall, kTraceUtility, -1, "CreateRtpDump()");
return new RtpDumpImpl();
}
void RtpDump::DestroyRtpDump(RtpDump* object)
{
WEBRTC_TRACE(kTraceModuleCall, kTraceUtility, -1, "DestroyRtpDump()");
delete object;
}
RtpDumpImpl::RtpDumpImpl()
: _critSect(*CriticalSectionWrapper::CreateCriticalSection()),
_file(*FileWrapper::Create()),
_startTime(0)
{
WEBRTC_TRACE(kTraceMemory, kTraceUtility, -1, "%s created", __FUNCTION__);
}
RtpDump::~RtpDump()
{
}
RtpDumpImpl::~RtpDumpImpl()
{
_file.Flush();
_file.CloseFile();
delete &_file;
delete &_critSect;
WEBRTC_TRACE(kTraceMemory, kTraceUtility, -1, "%s deleted", __FUNCTION__);
}
WebRtc_Word32 RtpDumpImpl::Start(const WebRtc_Word8* fileNameUTF8)
{
WEBRTC_TRACE(kTraceModuleCall, kTraceUtility, -1, "Start()");
if (fileNameUTF8 == NULL)
{
return -1;
}
CriticalSectionScoped lock(_critSect);
_file.Flush();
_file.CloseFile();
if (_file.OpenFile(fileNameUTF8, false, false, false) == -1)
{
WEBRTC_TRACE(kTraceError, kTraceUtility, -1,
"failed to open the specified file");
return -1;
}
// Store start of RTP dump (to be used for offset calculation later).
_startTime = GetTimeInMS();
// All rtp dump files start with #!rtpplay.
WebRtc_Word8 magic[16];
sprintf(magic, "#!rtpplay%s \n", RTPFILE_VERSION);
_file.WriteText(magic);
// The header according to the rtpdump documentation is sizeof(RD_hdr_t)
// which is 8 + 4 + 2 = 14 bytes for 32-bit architecture (and 22 bytes on
// 64-bit architecture). However, Wireshark use 16 bytes for the header
// regardless of if the binary is 32-bit or 64-bit. Go by the same approach
// as Wireshark since it makes more sense.
// http://wiki.wireshark.org/rtpdump explains that an additional 2 bytes
// of padding should be added to the header.
WebRtc_Word8 dummyHdr[16];
memset(dummyHdr, 0, 16);
_file.Write(dummyHdr, sizeof(dummyHdr));
return 0;
}
WebRtc_Word32 RtpDumpImpl::Stop()
{
WEBRTC_TRACE(kTraceModuleCall, kTraceUtility, -1, "Stop()");
CriticalSectionScoped lock(_critSect);
_file.Flush();
_file.CloseFile();
return 0;
}
bool RtpDumpImpl::IsActive() const
{
CriticalSectionScoped lock(_critSect);
return _file.Open();
}
WebRtc_Word32 RtpDumpImpl::DumpPacket(const WebRtc_UWord8* packet,
WebRtc_UWord16 packetLength)
{
CriticalSectionScoped lock(_critSect);
if (!IsActive())
{
return 0;
}
if (packet == NULL)
{
return -1;
}
if (packetLength < 1)
{
return -1;
}
// If the packet doesn't contain a valid RTCP header the packet will be
// considered RTP (without further verification).
bool isRTCP = RTCP(packet);
rtpDumpPktHdr_t hdr;
WebRtc_UWord32 offset;
// Offset is relative to when recording was started.
offset = GetTimeInMS();
if (offset < _startTime)
{
// Compensate for wraparound.
offset += MAX_UWORD32 - _startTime + 1;
} else {
offset -= _startTime;
}
hdr.offset = RtpDumpHtonl(offset);
hdr.length = RtpDumpHtons((WebRtc_UWord16)(packetLength + sizeof(hdr)));
if (isRTCP)
{
hdr.plen = 0;
}
else
{
hdr.plen = RtpDumpHtons((WebRtc_UWord16)packetLength);
}
_file.Write(&hdr, sizeof(hdr));
_file.Write(packet, packetLength);
return 0;
}
bool RtpDumpImpl::RTCP(const WebRtc_UWord8* packet) const
{
const WebRtc_UWord8 payloadType = packet[1];
bool is_rtcp = false;
switch(payloadType)
{
case 192:
is_rtcp = true;
break;
case 193: case 195:
break;
case 200: case 201: case 202: case 203:
case 204: case 205: case 206: case 207:
is_rtcp = true;
break;
}
return is_rtcp;
}
// TODO (hellner): why is TickUtil not used here?
inline WebRtc_UWord32 RtpDumpImpl::GetTimeInMS() const
{
#if defined(_WIN32)
return timeGetTime();
#elif defined(WEBRTC_LINUX) || defined(WEBRTC_MAC)
struct timeval tv;
struct timezone tz;
unsigned long val;
gettimeofday(&tv, &tz);
val = tv.tv_sec * 1000 + tv.tv_usec / 1000;
return val;
#else
#error Either _WIN32 or LINUX or WEBRTC_MAC has to be defined!
assert(false);
return 0;
#endif
}
inline WebRtc_UWord32 RtpDumpImpl::RtpDumpHtonl(WebRtc_UWord32 x) const
{
#if defined(WEBRTC_BIG_ENDIAN)
return x;
#elif defined(WEBRTC_LITTLE_ENDIAN)
return (x >> 24) + ((((x >> 16) & 0xFF) << 8) + ((((x >> 8) & 0xFF) << 16) +
((x & 0xFF) << 24)));
#else
#error Either WEBRTC_BIG_ENDIAN or WEBRTC_LITTLE_ENDIAN has to be defined!
assert(false);
return 0;
#endif
}
inline WebRtc_UWord16 RtpDumpImpl::RtpDumpHtons(WebRtc_UWord16 x) const
{
#if defined(WEBRTC_BIG_ENDIAN)
return x;
#elif defined(WEBRTC_LITTLE_ENDIAN)
return (x >> 8) + ((x & 0xFF) << 8);
#else
#error Either WEBRTC_BIG_ENDIAN or WEBRTC_LITTLE_ENDIAN has to be defined!
assert(false);
return 0;
#endif
}
} // namespace webrtc
<|endoftext|> |
<commit_before>//////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007-2016 musikcube team
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of the author nor the names of other 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 "stdafx.h"
#include "TransportWindow.h"
#include <cursespp/Screen.h>
#include <cursespp/Colors.h>
#include <cursespp/Message.h>
#include <cursespp/Text.h>
#include <app/util/Duration.h>
#include <core/debug.h>
#include <core/library/LocalLibraryConstants.h>
#include <boost/format.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/chrono.hpp>
#include <boost/lexical_cast.hpp>
#include <algorithm>
#include <memory>
using namespace musik::core;
using namespace musik::core::audio;
using namespace musik::core::library;
using namespace musik::core::db;
using namespace musik::box;
using namespace boost::chrono;
using namespace cursespp;
#define REFRESH_TRANSPORT_READOUT 1001
#define REFRESH_INTERVAL_MS 500
#define DEBOUNCE_REFRESH(x) \
this->RemoveMessage(REFRESH_TRANSPORT_READOUT); \
this->PostMessage(REFRESH_TRANSPORT_READOUT, 0, 0, x);
static std::string playingFormat = "playing $title from $album";
struct Token {
enum Type { Normal, Placeholder };
static std::unique_ptr<Token> New(const std::string& value, Type type) {
return std::unique_ptr<Token>(new Token(value, type));
}
Token(const std::string& value, Type type) {
this->value = value;
this->type = type;
}
std::string value;
Type type;
};
typedef std::unique_ptr<Token> TokenPtr;
typedef std::vector<TokenPtr> TokenList;
/* tokenizes an input string that has $placeholder values */
void tokenize(const std::string& format, TokenList& tokens) {
tokens.clear();
Token::Type type = Token::Normal;
size_t i = 0;
size_t start = 0;
while (i < format.size()) {
char c = format[i];
if ((type == Token::Placeholder && c == ' ') ||
(type == Token::Normal && c == '$')) {
/* escape $ with $$ */
if (c == '$' && i < format.size() - 1 && format[i + 1] == '$') {
i++;
}
else {
if (i > start) {
tokens.push_back(Token::New(format.substr(start, i - start), type));
}
start = i;
type = (c == ' ') ? Token::Normal : Token::Placeholder;
}
}
++i;
}
if (i > 0) {
tokens.push_back(Token::New(format.substr(start, i - start), type));
}
}
/* writes the colorized formatted string to the specified window. accounts for
utf8 characters and ellipsizing */
size_t writePlayingFormat(
WINDOW *w,
std::string title,
std::string album,
size_t width)
{
TokenList tokens;
tokenize(playingFormat, tokens);
int64 gb = COLOR_PAIR(BOX_COLOR_GREEN_ON_BLACK);
size_t remaining = width;
auto it = tokens.begin();
while (it != tokens.end() && remaining > 0) {
Token *token = it->get();
int64 attr = -1;
std::string value;
if (token->type == Token::Placeholder) {
attr = gb;
if (token->value == "$title") {
value = title;
}
else if (token->value == "$album") {
value = album;
}
}
if (!value.size()) {
value = token->value;
}
size_t len = u8len(value);
if (len > remaining) {
text::Ellipsize(value, remaining);
len = remaining;
}
if (attr != -1) {
wattron(w, attr);
}
wprintw(w, value.c_str());
if (attr != -1) {
wattroff(w, attr);
}
remaining -= len;
++it;
}
return (width - remaining);
}
TransportWindow::TransportWindow(musik::box::PlaybackService& playback)
: Window(NULL)
, playback(playback)
, transport(playback.GetTransport())
{
this->SetContentColor(BOX_COLOR_WHITE_ON_BLACK);
this->SetFrameVisible(false);
this->playback.TrackChanged.connect(this, &TransportWindow::OnPlaybackServiceTrackChanged);
this->transport.VolumeChanged.connect(this, &TransportWindow::OnTransportVolumeChanged);
this->transport.TimeChanged.connect(this, &TransportWindow::OnTransportTimeChanged);
this->paused = this->focused = false;
}
TransportWindow::~TransportWindow() {
}
void TransportWindow::Show() {
Window::Show();
this->Update();
}
void TransportWindow::ProcessMessage(IMessage &message) {
int type = message.Type();
if (type == REFRESH_TRANSPORT_READOUT) {
this->Update();
DEBOUNCE_REFRESH(REFRESH_INTERVAL_MS)
}
}
void TransportWindow::OnPlaybackServiceTrackChanged(size_t index, TrackPtr track) {
this->currentTrack = track;
DEBOUNCE_REFRESH(0)
}
void TransportWindow::OnTransportVolumeChanged() {
DEBOUNCE_REFRESH(0)
}
void TransportWindow::OnTransportTimeChanged(double time) {
DEBOUNCE_REFRESH(0)
}
void TransportWindow::Focus() {
this->focused = true;
DEBOUNCE_REFRESH(0)
}
void TransportWindow::Blur() {
this->focused = false;
DEBOUNCE_REFRESH(0)
}
void TransportWindow::Update() {
this->Clear();
WINDOW *c = this->GetContent();
bool paused = (transport.GetPlaybackState() == ITransport::PlaybackPaused);
bool stopped = (transport.GetPlaybackState() == ITransport::PlaybackStopped);
int64 gb = COLOR_PAIR(BOX_COLOR_GREEN_ON_BLACK);
if (focused) {
gb = COLOR_PAIR(BOX_COLOR_RED_ON_BLACK);
}
/* playing SONG TITLE from ALBUM NAME */
std::string duration = "0";
if (stopped) {
wattron(c, gb);
wprintw(c, "playback is stopped\n");
wattroff(c, gb);
}
else {
std::string title, album;
if (this->currentTrack) {
title = this->currentTrack->GetValue(constants::Track::TITLE);
album = this->currentTrack->GetValue(constants::Track::ALBUM);
duration = this->currentTrack->GetValue(constants::Track::DURATION);
}
title = title.size() ? title : "[song]";
album = album.size() ? album : "[album]";
duration = duration.size() ? duration : "0";
size_t written = writePlayingFormat(c, title, album, this->GetContentWidth());
if (written < this->GetContentWidth()) {
wprintw(c, "\n");
}
}
/* volume slider */
int volumePercent = (size_t) round(this->transport.Volume() * 100.0f) - 1;
int thumbOffset = std::min(9, (volumePercent * 10) / 100);
std::string volume = "vol ";
for (int i = 0; i < 10; i++) {
volume += (i == thumbOffset) ? "■" : "─";
}
volume += " ";
wprintw(c, volume.c_str());
/* time slider */
int64 timerAttrs = 0;
if (paused) { /* blink the track if paused */
int64 now = duration_cast<seconds>(
system_clock::now().time_since_epoch()).count();
if (now % 2 == 0) {
timerAttrs = COLOR_PAIR(BOX_COLOR_BLACK_ON_BLACK);
}
}
transport.Position();
int secondsCurrent = (int) round(transport.Position());
int secondsTotal = boost::lexical_cast<int>(duration);
std::string currentTime = duration::Duration(std::min(secondsCurrent, secondsTotal));
std::string totalTime = duration::Duration(secondsTotal);
size_t timerWidth =
this->GetContentWidth() -
u8len(volume) -
currentTime.size() -
totalTime.size() -
2; /* padding */
thumbOffset = 0;
if (secondsTotal) {
size_t progress = (secondsCurrent * 100) / secondsTotal;
thumbOffset = std::min(timerWidth - 1, (progress * timerWidth) / 100);
}
std::string timerTrack = "";
for (size_t i = 0; i < timerWidth; i++) {
timerTrack += (i == thumbOffset) ? "■" : "─";
}
wattron(c, timerAttrs); /* blink if paused */
wprintw(c, currentTime.c_str());
wattroff(c, timerAttrs);
/* using wprintw() here on large displays (1440p+) will exceed the internal
buffer length of 512 characters, so use boost format. */
std::string fmt = boost::str(boost::format(
" %s %s") % timerTrack % totalTime);
waddstr(c, fmt.c_str());
this->Repaint();
}
<commit_msg>MSVC warning cleanup.<commit_after>//////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007-2016 musikcube team
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of the author nor the names of other 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 "stdafx.h"
#include "TransportWindow.h"
#include <cursespp/Screen.h>
#include <cursespp/Colors.h>
#include <cursespp/Message.h>
#include <cursespp/Text.h>
#include <app/util/Duration.h>
#include <core/debug.h>
#include <core/library/LocalLibraryConstants.h>
#include <boost/format.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/chrono.hpp>
#include <boost/lexical_cast.hpp>
#include <algorithm>
#include <memory>
using namespace musik::core;
using namespace musik::core::audio;
using namespace musik::core::library;
using namespace musik::core::db;
using namespace musik::box;
using namespace boost::chrono;
using namespace cursespp;
#define REFRESH_TRANSPORT_READOUT 1001
#define REFRESH_INTERVAL_MS 500
#define DEBOUNCE_REFRESH(x) \
this->RemoveMessage(REFRESH_TRANSPORT_READOUT); \
this->PostMessage(REFRESH_TRANSPORT_READOUT, 0, 0, x);
static std::string playingFormat = "playing $title from $album";
struct Token {
enum Type { Normal, Placeholder };
static std::unique_ptr<Token> New(const std::string& value, Type type) {
return std::unique_ptr<Token>(new Token(value, type));
}
Token(const std::string& value, Type type) {
this->value = value;
this->type = type;
}
std::string value;
Type type;
};
typedef std::unique_ptr<Token> TokenPtr;
typedef std::vector<TokenPtr> TokenList;
/* tokenizes an input string that has $placeholder values */
void tokenize(const std::string& format, TokenList& tokens) {
tokens.clear();
Token::Type type = Token::Normal;
size_t i = 0;
size_t start = 0;
while (i < format.size()) {
char c = format[i];
if ((type == Token::Placeholder && c == ' ') ||
(type == Token::Normal && c == '$')) {
/* escape $ with $$ */
if (c == '$' && i < format.size() - 1 && format[i + 1] == '$') {
i++;
}
else {
if (i > start) {
tokens.push_back(Token::New(format.substr(start, i - start), type));
}
start = i;
type = (c == ' ') ? Token::Normal : Token::Placeholder;
}
}
++i;
}
if (i > 0) {
tokens.push_back(Token::New(format.substr(start, i - start), type));
}
}
/* writes the colorized formatted string to the specified window. accounts for
utf8 characters and ellipsizing */
size_t writePlayingFormat(
WINDOW *w,
std::string title,
std::string album,
size_t width)
{
TokenList tokens;
tokenize(playingFormat, tokens);
int64 gb = COLOR_PAIR(BOX_COLOR_GREEN_ON_BLACK);
size_t remaining = width;
auto it = tokens.begin();
while (it != tokens.end() && remaining > 0) {
Token *token = it->get();
int64 attr = -1;
std::string value;
if (token->type == Token::Placeholder) {
attr = gb;
if (token->value == "$title") {
value = title;
}
else if (token->value == "$album") {
value = album;
}
}
if (!value.size()) {
value = token->value;
}
size_t len = u8len(value);
if (len > remaining) {
text::Ellipsize(value, remaining);
len = remaining;
}
if (attr != -1) {
wattron(w, attr);
}
wprintw(w, value.c_str());
if (attr != -1) {
wattroff(w, attr);
}
remaining -= len;
++it;
}
return (width - remaining);
}
TransportWindow::TransportWindow(musik::box::PlaybackService& playback)
: Window(NULL)
, playback(playback)
, transport(playback.GetTransport())
{
this->SetContentColor(BOX_COLOR_WHITE_ON_BLACK);
this->SetFrameVisible(false);
this->playback.TrackChanged.connect(this, &TransportWindow::OnPlaybackServiceTrackChanged);
this->transport.VolumeChanged.connect(this, &TransportWindow::OnTransportVolumeChanged);
this->transport.TimeChanged.connect(this, &TransportWindow::OnTransportTimeChanged);
this->paused = this->focused = false;
}
TransportWindow::~TransportWindow() {
}
void TransportWindow::Show() {
Window::Show();
this->Update();
}
void TransportWindow::ProcessMessage(IMessage &message) {
int type = message.Type();
if (type == REFRESH_TRANSPORT_READOUT) {
this->Update();
DEBOUNCE_REFRESH(REFRESH_INTERVAL_MS)
}
}
void TransportWindow::OnPlaybackServiceTrackChanged(size_t index, TrackPtr track) {
this->currentTrack = track;
DEBOUNCE_REFRESH(0)
}
void TransportWindow::OnTransportVolumeChanged() {
DEBOUNCE_REFRESH(0)
}
void TransportWindow::OnTransportTimeChanged(double time) {
DEBOUNCE_REFRESH(0)
}
void TransportWindow::Focus() {
this->focused = true;
DEBOUNCE_REFRESH(0)
}
void TransportWindow::Blur() {
this->focused = false;
DEBOUNCE_REFRESH(0)
}
void TransportWindow::Update() {
this->Clear();
WINDOW *c = this->GetContent();
bool paused = (transport.GetPlaybackState() == ITransport::PlaybackPaused);
bool stopped = (transport.GetPlaybackState() == ITransport::PlaybackStopped);
int64 gb = COLOR_PAIR(BOX_COLOR_GREEN_ON_BLACK);
/* playing SONG TITLE from ALBUM NAME */
std::string duration = "0";
if (stopped) {
wattron(c, gb);
wprintw(c, "playback is stopped\n");
wattroff(c, gb);
}
else {
std::string title, album;
if (this->currentTrack) {
title = this->currentTrack->GetValue(constants::Track::TITLE);
album = this->currentTrack->GetValue(constants::Track::ALBUM);
duration = this->currentTrack->GetValue(constants::Track::DURATION);
}
title = title.size() ? title : "[song]";
album = album.size() ? album : "[album]";
duration = duration.size() ? duration : "0";
size_t written = writePlayingFormat(c, title, album, this->GetContentWidth());
if (written < (size_t) this->GetContentWidth()) {
wprintw(c, "\n");
}
}
/* volume slider */
int volumePercent = (size_t) round(this->transport.Volume() * 100.0f) - 1;
int thumbOffset = std::min(9, (volumePercent * 10) / 100);
std::string volume = "vol ";
for (int i = 0; i < 10; i++) {
volume += (i == thumbOffset) ? "■" : "─";
}
volume += " ";
wprintw(c, volume.c_str());
/* time slider */
int64 timerAttrs = 0;
if (paused) { /* blink the track if paused */
int64 now = duration_cast<seconds>(
system_clock::now().time_since_epoch()).count();
if (now % 2 == 0) {
timerAttrs = COLOR_PAIR(BOX_COLOR_BLACK_ON_BLACK);
}
}
transport.Position();
int secondsCurrent = (int) round(transport.Position());
int secondsTotal = boost::lexical_cast<int>(duration);
std::string currentTime = duration::Duration(std::min(secondsCurrent, secondsTotal));
std::string totalTime = duration::Duration(secondsTotal);
size_t timerWidth =
this->GetContentWidth() -
u8len(volume) -
currentTime.size() -
totalTime.size() -
2; /* padding */
thumbOffset = 0;
if (secondsTotal) {
size_t progress = (secondsCurrent * 100) / secondsTotal;
thumbOffset = std::min(timerWidth - 1, (progress * timerWidth) / 100);
}
std::string timerTrack = "";
for (size_t i = 0; i < timerWidth; i++) {
timerTrack += (i == thumbOffset) ? "■" : "─";
}
wattron(c, timerAttrs); /* blink if paused */
wprintw(c, currentTime.c_str());
wattroff(c, timerAttrs);
/* using wprintw() here on large displays (1440p+) will exceed the internal
buffer length of 512 characters, so use boost format. */
std::string fmt = boost::str(boost::format(
" %s %s") % timerTrack % totalTime);
waddstr(c, fmt.c_str());
this->Repaint();
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.